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