]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/tt/macro_rules.rs
auto merge of #15422 : steveklabnik/rust/guide_compound_data_types, r=brson
[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, MacroExpander};
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     /// 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 {
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             match parser.parse_item_with_outer_attributes() {
77                 Some(item) => ret.push(item),
78                 None => break
79             }
80         }
81         self.ensure_complete_parse(false);
82         Some(ret)
83     }
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);
88         Some(ret)
89     }
90 }
91
92 struct MacroRulesMacroExpander {
93     name: Ident,
94     lhses: Vec<Rc<NamedMatch>>,
95     rhses: Vec<Rc<NamedMatch>>,
96 }
97
98 impl MacroExpander for MacroRulesMacroExpander {
99     fn expand(&self,
100               cx: &mut ExtCtxt,
101               sp: Span,
102               arg: &[ast::TokenTree])
103               -> Box<MacResult> {
104         generic_extension(cx,
105                           sp,
106                           self.name,
107                           arg,
108                           self.lhses.as_slice(),
109                           self.rhses.as_slice())
110     }
111 }
112
113 struct MacroRulesDefiner {
114     def: RefCell<Option<MacroDef>>
115 }
116 impl MacResult for MacroRulesDefiner {
117     fn make_def(&self) -> Option<MacroDef> {
118         Some(self.def.borrow_mut().take().expect("MacroRulesDefiner expanded twice"))
119     }
120 }
121
122 // Given `lhses` and `rhses`, this is the new macro we create
123 fn generic_extension(cx: &ExtCtxt,
124                      sp: Span,
125                      name: Ident,
126                      arg: &[ast::TokenTree],
127                      lhses: &[Rc<NamedMatch>],
128                      rhses: &[Rc<NamedMatch>])
129                      -> Box<MacResult> {
130     if cx.trace_macros() {
131         println!("{}! {} {} {}",
132                  token::get_ident(name),
133                  "{",
134                  print::pprust::tt_to_string(&TTDelim(Rc::new(arg.iter()
135                                                               .map(|x| (*x).clone())
136                                                               .collect()))),
137                  "}");
138     }
139
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();
143
144     for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
145         match **lhs {
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,
149                                         None,
150                                         arg.iter()
151                                            .map(|x| (*x).clone())
152                                            .collect());
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)) => {
158                         match *tt {
159                             // cut off delimiters; don't parse 'em
160                             TTDelim(ref tts) => {
161                                 (*tts).slice(1u,(*tts).len()-1u)
162                                       .iter()
163                                       .map(|x| (*x).clone())
164                                       .collect()
165                             }
166                             _ => cx.span_fatal(
167                                 sp, "macro rhs must be delimited")
168                         }
169                     },
170                     _ => cx.span_bug(sp, "bad thing in rhs")
171                 };
172                 // rhs has holes ( `$id` and `$(...)` that need filled)
173                 let trncbr = new_tt_reader(&cx.parse_sess().span_diagnostic,
174                                            Some(named_matches),
175                                            rhs);
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),
181                 } as Box<MacResult>
182               }
183               Failure(sp, ref msg) => if sp.lo >= best_fail_spot.lo {
184                 best_fail_spot = sp;
185                 best_fail_msg = (*msg).clone();
186               },
187               Error(sp, ref msg) => cx.span_fatal(sp, msg.as_slice())
188             }
189           }
190           _ => cx.bug("non-matcher found in parsed lhses")
191         }
192     }
193     cx.span_fatal(best_fail_spot, best_fail_msg.as_slice());
194 }
195
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,
200                          sp: Span,
201                          name: Ident,
202                          arg: Vec<ast::TokenTree> )
203                          -> Box<base::MacResult> {
204     // these spans won't matter, anyways
205     fn ms(m: Matcher_) -> Matcher {
206         Spanned {
207             node: m.clone(),
208             span: DUMMY_SP
209         }
210     }
211
212     let lhs_nm =  gensym_ident("lhs");
213     let rhs_nm =  gensym_ident("rhs");
214
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!(
220         ms(MatchSeq(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)));
227
228
229     // Parse the macro_rules! invocation (`none` is for no interpolations):
230     let arg_reader = new_tt_reader(&cx.parse_sess().span_diagnostic,
231                                    None,
232                                    arg.clone());
233     let argument_map = parse_or_else(cx.parse_sess(),
234                                      cx.cfg(),
235                                      arg_reader,
236                                      argument_gram);
237
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")
242     };
243
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")
247     };
248
249     let exp = box MacroRulesMacroExpander {
250         name: name,
251         lhses: lhses,
252         rhses: rhses,
253     };
254
255     box MacroRulesDefiner {
256         def: RefCell::new(Some(MacroDef {
257             name: token::get_ident(name).to_string(),
258             ext: NormalTT(exp, Some(sp))
259         }))
260     } as Box<MacResult>
261 }