]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/tt/macro_rules.rs
auto merge of #16809 : nick29581/rust/dst-bug-3, r=alexcrichton
[rust.git] / src / libsyntax / ext / tt / macro_rules.rs
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.
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 use ast::{Ident, Matcher_, Matcher, MatchTok, MatchNonterminal, MatchSeq};
12 use ast::{TTDelim};
13 use ast;
14 use codemap::{Span, Spanned, DUMMY_SP};
15 use ext::base::{ExtCtxt, MacResult, MacroDef};
16 use ext::base::{NormalTT, TTMacroExpander};
17 use ext::tt::macro_parser::{Success, Error, Failure};
18 use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal};
19 use ext::tt::macro_parser::{parse, parse_or_else};
20 use parse::lexer::new_tt_reader;
21 use parse::parser::Parser;
22 use parse::attr::ParserAttr;
23 use parse::token::{special_idents, gensym_ident};
24 use parse::token::{FAT_ARROW, SEMI, NtMatchers, NtTT, EOF};
25 use parse::token;
26 use print;
27 use util::small_vector::SmallVector;
28
29 use std::cell::RefCell;
30 use std::rc::Rc;
31 use std::gc::Gc;
32
33 struct ParserAnyMacro<'a> {
34     parser: RefCell<Parser<'a>>,
35 }
36
37 impl<'a> ParserAnyMacro<'a> {
38     /// Make sure we don't have any tokens left to parse, so we don't
39     /// silently drop anything. `allow_semi` is so that "optional"
40     /// semicolons at the end of normal expressions aren't complained
41     /// about e.g. the semicolon in `macro_rules! kapow( () => {
42     /// fail!(); } )` doesn't get picked up by .parse_expr(), but it's
43     /// allowed to be there.
44     fn ensure_complete_parse(&self, allow_semi: bool) {
45         let mut parser = self.parser.borrow_mut();
46         if allow_semi && parser.token == SEMI {
47             parser.bump()
48         }
49         if parser.token != EOF {
50             let token_str = parser.this_token_to_string();
51             let msg = format!("macro expansion ignores token `{}` and any \
52                                following",
53                               token_str);
54             let span = parser.span;
55             parser.span_err(span, msg.as_slice());
56         }
57     }
58 }
59
60 impl<'a> MacResult for ParserAnyMacro<'a> {
61     fn make_expr(&self) -> Option<Gc<ast::Expr>> {
62         let ret = self.parser.borrow_mut().parse_expr();
63         self.ensure_complete_parse(true);
64         Some(ret)
65     }
66     fn make_pat(&self) -> Option<Gc<ast::Pat>> {
67         let ret = self.parser.borrow_mut().parse_pat();
68         self.ensure_complete_parse(false);
69         Some(ret)
70     }
71     fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
72         let mut ret = SmallVector::zero();
73         loop {
74             let mut parser = self.parser.borrow_mut();
75             // so... do outer attributes attached to the macro invocation
76             // just disappear? This question applies to make_methods, as
77             // well.
78             match parser.parse_item_with_outer_attributes() {
79                 Some(item) => ret.push(item),
80                 None => break
81             }
82         }
83         self.ensure_complete_parse(false);
84         Some(ret)
85     }
86
87     fn make_methods(&self) -> Option<SmallVector<Gc<ast::Method>>> {
88         let mut ret = SmallVector::zero();
89         loop {
90             let mut parser = self.parser.borrow_mut();
91             match parser.token {
92                 EOF => break,
93                 _ => ret.push(parser.parse_method(None))
94             }
95         }
96         self.ensure_complete_parse(false);
97         Some(ret)
98     }
99
100     fn make_stmt(&self) -> Option<Gc<ast::Stmt>> {
101         let attrs = self.parser.borrow_mut().parse_outer_attributes();
102         let ret = self.parser.borrow_mut().parse_stmt(attrs);
103         self.ensure_complete_parse(true);
104         Some(ret)
105     }
106 }
107
108 struct MacroRulesMacroExpander {
109     name: Ident,
110     lhses: Vec<Rc<NamedMatch>>,
111     rhses: Vec<Rc<NamedMatch>>,
112 }
113
114 impl TTMacroExpander for MacroRulesMacroExpander {
115     fn expand<'cx>(&self,
116                    cx: &'cx mut ExtCtxt,
117                    sp: Span,
118                    arg: &[ast::TokenTree])
119                    -> Box<MacResult+'cx> {
120         generic_extension(cx,
121                           sp,
122                           self.name,
123                           arg,
124                           self.lhses.as_slice(),
125                           self.rhses.as_slice())
126     }
127 }
128
129 struct MacroRulesDefiner {
130     def: RefCell<Option<MacroDef>>
131 }
132 impl MacResult for MacroRulesDefiner {
133     fn make_def(&self) -> Option<MacroDef> {
134         Some(self.def.borrow_mut().take().expect("MacroRulesDefiner expanded twice"))
135     }
136 }
137
138 /// Given `lhses` and `rhses`, this is the new macro we create
139 fn generic_extension<'cx>(cx: &'cx ExtCtxt,
140                           sp: Span,
141                           name: Ident,
142                           arg: &[ast::TokenTree],
143                           lhses: &[Rc<NamedMatch>],
144                           rhses: &[Rc<NamedMatch>])
145                           -> Box<MacResult+'cx> {
146     if cx.trace_macros() {
147         println!("{}! {} {} {}",
148                  token::get_ident(name),
149                  "{",
150                  print::pprust::tt_to_string(&TTDelim(Rc::new(arg.iter()
151                                                               .map(|x| (*x).clone())
152                                                               .collect()))),
153                  "}");
154     }
155
156     // Which arm's failure should we report? (the one furthest along)
157     let mut best_fail_spot = DUMMY_SP;
158     let mut best_fail_msg = "internal error: ran no matchers".to_string();
159
160     for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
161         match **lhs {
162           MatchedNonterminal(NtMatchers(ref mtcs)) => {
163             // `None` is because we're not interpolating
164             let arg_rdr = new_tt_reader(&cx.parse_sess().span_diagnostic,
165                                         None,
166                                         arg.iter()
167                                            .map(|x| (*x).clone())
168                                            .collect());
169             match parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtcs.as_slice()) {
170               Success(named_matches) => {
171                 let rhs = match *rhses[i] {
172                     // okay, what's your transcriber?
173                     MatchedNonterminal(NtTT(tt)) => {
174                         match *tt {
175                             // cut off delimiters; don't parse 'em
176                             TTDelim(ref tts) => {
177                                 (*tts).slice(1u,(*tts).len()-1u)
178                                       .iter()
179                                       .map(|x| (*x).clone())
180                                       .collect()
181                             }
182                             _ => cx.span_fatal(
183                                 sp, "macro rhs must be delimited")
184                         }
185                     },
186                     _ => cx.span_bug(sp, "bad thing in rhs")
187                 };
188                 // rhs has holes ( `$id` and `$(...)` that need filled)
189                 let trncbr = new_tt_reader(&cx.parse_sess().span_diagnostic,
190                                            Some(named_matches),
191                                            rhs);
192                 let p = Parser::new(cx.parse_sess(), cx.cfg(), box trncbr);
193                 // Let the context choose how to interpret the result.
194                 // Weird, but useful for X-macros.
195                 return box ParserAnyMacro {
196                     parser: RefCell::new(p),
197                 } as Box<MacResult+'cx>
198               }
199               Failure(sp, ref msg) => if sp.lo >= best_fail_spot.lo {
200                 best_fail_spot = sp;
201                 best_fail_msg = (*msg).clone();
202               },
203               Error(sp, ref msg) => cx.span_fatal(sp, msg.as_slice())
204             }
205           }
206           _ => cx.bug("non-matcher found in parsed lhses")
207         }
208     }
209     cx.span_fatal(best_fail_spot, best_fail_msg.as_slice());
210 }
211
212 /// This procedure performs the expansion of the
213 /// macro_rules! macro. It parses the RHS and adds
214 /// an extension to the current context.
215 pub fn add_new_extension<'cx>(cx: &'cx mut ExtCtxt,
216                               sp: Span,
217                               name: Ident,
218                               arg: Vec<ast::TokenTree> )
219                               -> Box<MacResult+'cx> {
220     // these spans won't matter, anyways
221     fn ms(m: Matcher_) -> Matcher {
222         Spanned {
223             node: m.clone(),
224             span: DUMMY_SP
225         }
226     }
227
228     let lhs_nm =  gensym_ident("lhs");
229     let rhs_nm =  gensym_ident("rhs");
230
231     // The pattern that macro_rules matches.
232     // The grammar for macro_rules! is:
233     // $( $lhs:mtcs => $rhs:tt );+
234     // ...quasiquoting this would be nice.
235     let argument_gram = vec!(
236         ms(MatchSeq(vec!(
237             ms(MatchNonterminal(lhs_nm, special_idents::matchers, 0u)),
238             ms(MatchTok(FAT_ARROW)),
239             ms(MatchNonterminal(rhs_nm, special_idents::tt, 1u))), Some(SEMI), false, 0u, 2u)),
240         //to phase into semicolon-termination instead of
241         //semicolon-separation
242         ms(MatchSeq(vec!(ms(MatchTok(SEMI))), None, true, 2u, 2u)));
243
244
245     // Parse the macro_rules! invocation (`none` is for no interpolations):
246     let arg_reader = new_tt_reader(&cx.parse_sess().span_diagnostic,
247                                    None,
248                                    arg.clone());
249     let argument_map = parse_or_else(cx.parse_sess(),
250                                      cx.cfg(),
251                                      arg_reader,
252                                      argument_gram);
253
254     // Extract the arguments:
255     let lhses = match **argument_map.get(&lhs_nm) {
256         MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(),
257         _ => cx.span_bug(sp, "wrong-structured lhs")
258     };
259
260     let rhses = match **argument_map.get(&rhs_nm) {
261         MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(),
262         _ => cx.span_bug(sp, "wrong-structured rhs")
263     };
264
265     let exp = box MacroRulesMacroExpander {
266         name: name,
267         lhses: lhses,
268         rhses: rhses,
269     };
270
271     box MacroRulesDefiner {
272         def: RefCell::new(Some(MacroDef {
273             name: token::get_ident(name).to_string(),
274             ext: NormalTT(exp, Some(sp))
275         }))
276     } as Box<MacResult+'cx>
277 }