]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/mod.rs
Rollup merge of #30384 - nrc:diagnostics, r=@nikomatsakis
[rust.git] / src / libsyntax / parse / mod.rs
1 // Copyright 2012-2014 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 //! The main parser interface
12
13 use ast;
14 use codemap::{self, Span, CodeMap, FileMap};
15 use errors::{Handler, ColorConfig, FatalError};
16 use parse::parser::Parser;
17 use parse::token::InternedString;
18 use ptr::P;
19 use str::char_at;
20
21 use std::cell::RefCell;
22 use std::io::Read;
23 use std::iter;
24 use std::path::{Path, PathBuf};
25 use std::rc::Rc;
26 use std::str;
27
28 pub type PResult<T> = Result<T, FatalError>;
29
30 #[macro_use]
31 pub mod parser;
32
33 pub mod lexer;
34 pub mod token;
35 pub mod attr;
36
37 pub mod common;
38 pub mod classify;
39 pub mod obsolete;
40
41 /// Info about a parsing session.
42 pub struct ParseSess {
43     pub span_diagnostic: Handler, // better be the same as the one in the reader!
44     /// Used to determine and report recursive mod inclusions
45     included_mod_stack: RefCell<Vec<PathBuf>>,
46     code_map: Rc<CodeMap>,
47 }
48
49 impl ParseSess {
50     pub fn new() -> ParseSess {
51         let cm = Rc::new(CodeMap::new());
52         let handler = Handler::new(ColorConfig::Auto, None, true, false, cm.clone());
53         ParseSess::with_span_handler(handler, cm)
54     }
55
56     pub fn with_span_handler(handler: Handler, code_map: Rc<CodeMap>) -> ParseSess {
57         ParseSess {
58             span_diagnostic: handler,
59             included_mod_stack: RefCell::new(vec![]),
60             code_map: code_map
61         }
62     }
63
64     pub fn codemap(&self) -> &CodeMap {
65         &self.code_map
66     }
67 }
68
69 // a bunch of utility functions of the form parse_<thing>_from_<source>
70 // where <thing> includes crate, expr, item, stmt, tts, and one that
71 // uses a HOF to parse anything, and <source> includes file and
72 // source_str.
73
74 pub fn parse_crate_from_file(
75     input: &Path,
76     cfg: ast::CrateConfig,
77     sess: &ParseSess
78 ) -> ast::Crate {
79     panictry!(new_parser_from_file(sess, cfg, input).parse_crate_mod())
80     // why is there no p.abort_if_errors here?
81 }
82
83 pub fn parse_crate_attrs_from_file(
84     input: &Path,
85     cfg: ast::CrateConfig,
86     sess: &ParseSess
87 ) -> Vec<ast::Attribute> {
88     // FIXME: maybe_aborted?
89     panictry!(new_parser_from_file(sess, cfg, input).parse_inner_attributes())
90 }
91
92 pub fn parse_crate_from_source_str(name: String,
93                                    source: String,
94                                    cfg: ast::CrateConfig,
95                                    sess: &ParseSess)
96                                    -> ast::Crate {
97     let mut p = new_parser_from_source_str(sess,
98                                            cfg,
99                                            name,
100                                            source);
101     maybe_aborted(panictry!(p.parse_crate_mod()),p)
102 }
103
104 pub fn parse_crate_attrs_from_source_str(name: String,
105                                          source: String,
106                                          cfg: ast::CrateConfig,
107                                          sess: &ParseSess)
108                                          -> Vec<ast::Attribute> {
109     let mut p = new_parser_from_source_str(sess,
110                                            cfg,
111                                            name,
112                                            source);
113     maybe_aborted(panictry!(p.parse_inner_attributes()), p)
114 }
115
116 pub fn parse_expr_from_source_str(name: String,
117                                   source: String,
118                                   cfg: ast::CrateConfig,
119                                   sess: &ParseSess)
120                                   -> P<ast::Expr> {
121     let mut p = new_parser_from_source_str(sess, cfg, name, source);
122     maybe_aborted(panictry!(p.parse_expr()), p)
123 }
124
125 pub fn parse_item_from_source_str(name: String,
126                                   source: String,
127                                   cfg: ast::CrateConfig,
128                                   sess: &ParseSess)
129                                   -> Option<P<ast::Item>> {
130     let mut p = new_parser_from_source_str(sess, cfg, name, source);
131     maybe_aborted(panictry!(p.parse_item()), p)
132 }
133
134 pub fn parse_meta_from_source_str(name: String,
135                                   source: String,
136                                   cfg: ast::CrateConfig,
137                                   sess: &ParseSess)
138                                   -> P<ast::MetaItem> {
139     let mut p = new_parser_from_source_str(sess, cfg, name, source);
140     maybe_aborted(panictry!(p.parse_meta_item()), p)
141 }
142
143 pub fn parse_stmt_from_source_str(name: String,
144                                   source: String,
145                                   cfg: ast::CrateConfig,
146                                   sess: &ParseSess)
147                                   -> Option<P<ast::Stmt>> {
148     let mut p = new_parser_from_source_str(
149         sess,
150         cfg,
151         name,
152         source
153     );
154     maybe_aborted(panictry!(p.parse_stmt()), p)
155 }
156
157 // Warning: This parses with quote_depth > 0, which is not the default.
158 pub fn parse_tts_from_source_str(name: String,
159                                  source: String,
160                                  cfg: ast::CrateConfig,
161                                  sess: &ParseSess)
162                                  -> Vec<ast::TokenTree> {
163     let mut p = new_parser_from_source_str(
164         sess,
165         cfg,
166         name,
167         source
168     );
169     p.quote_depth += 1;
170     // right now this is re-creating the token trees from ... token trees.
171     maybe_aborted(panictry!(p.parse_all_token_trees()),p)
172 }
173
174 // Create a new parser from a source string
175 pub fn new_parser_from_source_str<'a>(sess: &'a ParseSess,
176                                       cfg: ast::CrateConfig,
177                                       name: String,
178                                       source: String)
179                                       -> Parser<'a> {
180     filemap_to_parser(sess, sess.codemap().new_filemap(name, source), cfg)
181 }
182
183 /// Create a new parser, handling errors as appropriate
184 /// if the file doesn't exist
185 pub fn new_parser_from_file<'a>(sess: &'a ParseSess,
186                                 cfg: ast::CrateConfig,
187                                 path: &Path) -> Parser<'a> {
188     filemap_to_parser(sess, file_to_filemap(sess, path, None), cfg)
189 }
190
191 /// Given a session, a crate config, a path, and a span, add
192 /// the file at the given path to the codemap, and return a parser.
193 /// On an error, use the given span as the source of the problem.
194 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
195                                     cfg: ast::CrateConfig,
196                                     path: &Path,
197                                     owns_directory: bool,
198                                     module_name: Option<String>,
199                                     sp: Span) -> Parser<'a> {
200     let mut p = filemap_to_parser(sess, file_to_filemap(sess, path, Some(sp)), cfg);
201     p.owns_directory = owns_directory;
202     p.root_module_name = module_name;
203     p
204 }
205
206 /// Given a filemap and config, return a parser
207 pub fn filemap_to_parser<'a>(sess: &'a ParseSess,
208                              filemap: Rc<FileMap>,
209                              cfg: ast::CrateConfig) -> Parser<'a> {
210     let end_pos = filemap.end_pos;
211     let mut parser = tts_to_parser(sess, filemap_to_tts(sess, filemap), cfg);
212
213     if parser.token == token::Eof && parser.span == codemap::DUMMY_SP {
214         parser.span = codemap::mk_sp(end_pos, end_pos);
215     }
216
217     parser
218 }
219
220 // must preserve old name for now, because quote! from the *existing*
221 // compiler expands into it
222 pub fn new_parser_from_tts<'a>(sess: &'a ParseSess,
223                                cfg: ast::CrateConfig,
224                                tts: Vec<ast::TokenTree>) -> Parser<'a> {
225     tts_to_parser(sess, tts, cfg)
226 }
227
228
229 // base abstractions
230
231 /// Given a session and a path and an optional span (for error reporting),
232 /// add the path to the session's codemap and return the new filemap.
233 fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
234                    -> Rc<FileMap> {
235     match sess.codemap().load_file(path) {
236         Ok(filemap) => filemap,
237         Err(e) => {
238             let msg = format!("couldn't read {:?}: {}", path.display(), e);
239             match spanopt {
240                 Some(sp) => panic!(sess.span_diagnostic.span_fatal(sp, &msg)),
241                 None => panic!(sess.span_diagnostic.fatal(&msg))
242             }
243         }
244     }
245 }
246
247 /// Given a filemap, produce a sequence of token-trees
248 pub fn filemap_to_tts(sess: &ParseSess, filemap: Rc<FileMap>)
249     -> Vec<ast::TokenTree> {
250     // it appears to me that the cfg doesn't matter here... indeed,
251     // parsing tt's probably shouldn't require a parser at all.
252     let cfg = Vec::new();
253     let srdr = lexer::StringReader::new(&sess.span_diagnostic, filemap);
254     let mut p1 = Parser::new(sess, cfg, Box::new(srdr));
255     panictry!(p1.parse_all_token_trees())
256 }
257
258 /// Given tts and cfg, produce a parser
259 pub fn tts_to_parser<'a>(sess: &'a ParseSess,
260                          tts: Vec<ast::TokenTree>,
261                          cfg: ast::CrateConfig) -> Parser<'a> {
262     let trdr = lexer::new_tt_reader(&sess.span_diagnostic, None, None, tts);
263     let mut p = Parser::new(sess, cfg, Box::new(trdr));
264     panictry!(p.check_unknown_macro_variable());
265     p
266 }
267
268 /// Abort if necessary
269 pub fn maybe_aborted<T>(result: T, p: Parser) -> T {
270     p.abort_if_errors();
271     result
272 }
273
274 /// Parse a string representing a character literal into its final form.
275 /// Rather than just accepting/rejecting a given literal, unescapes it as
276 /// well. Can take any slice prefixed by a character escape. Returns the
277 /// character and the number of characters consumed.
278 pub fn char_lit(lit: &str) -> (char, isize) {
279     use std::char;
280
281     let mut chars = lit.chars();
282     let c = match (chars.next(), chars.next()) {
283         (Some(c), None) if c != '\\' => return (c, 1),
284         (Some('\\'), Some(c)) => match c {
285             '"' => Some('"'),
286             'n' => Some('\n'),
287             'r' => Some('\r'),
288             't' => Some('\t'),
289             '\\' => Some('\\'),
290             '\'' => Some('\''),
291             '0' => Some('\0'),
292             _ => { None }
293         },
294         _ => panic!("lexer accepted invalid char escape `{}`", lit)
295     };
296
297     match c {
298         Some(x) => return (x, 2),
299         None => { }
300     }
301
302     let msg = format!("lexer should have rejected a bad character escape {}", lit);
303     let msg2 = &msg[..];
304
305     fn esc(len: usize, lit: &str) -> Option<(char, isize)> {
306         u32::from_str_radix(&lit[2..len], 16).ok()
307         .and_then(char::from_u32)
308         .map(|x| (x, len as isize))
309     }
310
311     let unicode_escape = || -> Option<(char, isize)> {
312         if lit.as_bytes()[2] == b'{' {
313             let idx = lit.find('}').expect(msg2);
314             let subslice = &lit[3..idx];
315             u32::from_str_radix(subslice, 16).ok()
316                 .and_then(char::from_u32)
317                 .map(|x| (x, subslice.chars().count() as isize + 4))
318         } else {
319             esc(6, lit)
320         }
321     };
322
323     // Unicode escapes
324     return match lit.as_bytes()[1] as char {
325         'x' | 'X' => esc(4, lit),
326         'u' => unicode_escape(),
327         'U' => esc(10, lit),
328         _ => None,
329     }.expect(msg2);
330 }
331
332 /// Parse a string representing a string literal into its final form. Does
333 /// unescaping.
334 pub fn str_lit(lit: &str) -> String {
335     debug!("parse_str_lit: given {}", lit.escape_default());
336     let mut res = String::with_capacity(lit.len());
337
338     // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
339     let error = |i| format!("lexer should have rejected {} at {}", lit, i);
340
341     /// Eat everything up to a non-whitespace
342     fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
343         loop {
344             match it.peek().map(|x| x.1) {
345                 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
346                     it.next();
347                 },
348                 _ => { break; }
349             }
350         }
351     }
352
353     let mut chars = lit.char_indices().peekable();
354     loop {
355         match chars.next() {
356             Some((i, c)) => {
357                 match c {
358                     '\\' => {
359                         let ch = chars.peek().unwrap_or_else(|| {
360                             panic!("{}", error(i))
361                         }).1;
362
363                         if ch == '\n' {
364                             eat(&mut chars);
365                         } else if ch == '\r' {
366                             chars.next();
367                             let ch = chars.peek().unwrap_or_else(|| {
368                                 panic!("{}", error(i))
369                             }).1;
370
371                             if ch != '\n' {
372                                 panic!("lexer accepted bare CR");
373                             }
374                             eat(&mut chars);
375                         } else {
376                             // otherwise, a normal escape
377                             let (c, n) = char_lit(&lit[i..]);
378                             for _ in 0..n - 1 { // we don't need to move past the first \
379                                 chars.next();
380                             }
381                             res.push(c);
382                         }
383                     },
384                     '\r' => {
385                         let ch = chars.peek().unwrap_or_else(|| {
386                             panic!("{}", error(i))
387                         }).1;
388
389                         if ch != '\n' {
390                             panic!("lexer accepted bare CR");
391                         }
392                         chars.next();
393                         res.push('\n');
394                     }
395                     c => res.push(c),
396                 }
397             },
398             None => break
399         }
400     }
401
402     res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
403     debug!("parse_str_lit: returning {}", res);
404     res
405 }
406
407 /// Parse a string representing a raw string literal into its final form. The
408 /// only operation this does is convert embedded CRLF into a single LF.
409 pub fn raw_str_lit(lit: &str) -> String {
410     debug!("raw_str_lit: given {}", lit.escape_default());
411     let mut res = String::with_capacity(lit.len());
412
413     // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
414     let mut chars = lit.chars().peekable();
415     loop {
416         match chars.next() {
417             Some(c) => {
418                 if c == '\r' {
419                     if *chars.peek().unwrap() != '\n' {
420                         panic!("lexer accepted bare CR");
421                     }
422                     chars.next();
423                     res.push('\n');
424                 } else {
425                     res.push(c);
426                 }
427             },
428             None => break
429         }
430     }
431
432     res.shrink_to_fit();
433     res
434 }
435
436 // check if `s` looks like i32 or u1234 etc.
437 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
438     s.len() > 1 &&
439         first_chars.contains(&char_at(s, 0)) &&
440         s[1..].chars().all(|c| '0' <= c && c <= '9')
441 }
442
443 fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>,
444                       sd: &Handler, sp: Span) -> ast::Lit_ {
445     debug!("filtered_float_lit: {}, {:?}", data, suffix);
446     match suffix.as_ref().map(|s| &**s) {
447         Some("f32") => ast::LitFloat(data, ast::TyF32),
448         Some("f64") => ast::LitFloat(data, ast::TyF64),
449         Some(suf) => {
450             if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
451                 // if it looks like a width, lets try to be helpful.
452                 sd.span_err(sp, &format!("invalid width `{}` for float literal", &suf[1..]));
453                 sd.fileline_help(sp, "valid widths are 32 and 64");
454             } else {
455                 sd.span_err(sp, &format!("invalid suffix `{}` for float literal", suf));
456                 sd.fileline_help(sp, "valid suffixes are `f32` and `f64`");
457             }
458
459             ast::LitFloatUnsuffixed(data)
460         }
461         None => ast::LitFloatUnsuffixed(data)
462     }
463 }
464 pub fn float_lit(s: &str, suffix: Option<InternedString>,
465                  sd: &Handler, sp: Span) -> ast::Lit_ {
466     debug!("float_lit: {:?}, {:?}", s, suffix);
467     // FIXME #2252: bounds checking float literals is deferred until trans
468     let s = s.chars().filter(|&c| c != '_').collect::<String>();
469     let data = token::intern_and_get_ident(&s);
470     filtered_float_lit(data, suffix.as_ref().map(|s| &**s), sd, sp)
471 }
472
473 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
474 pub fn byte_lit(lit: &str) -> (u8, usize) {
475     let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
476
477     if lit.len() == 1 {
478         (lit.as_bytes()[0], 1)
479     } else {
480         assert!(lit.as_bytes()[0] == b'\\', err(0));
481         let b = match lit.as_bytes()[1] {
482             b'"' => b'"',
483             b'n' => b'\n',
484             b'r' => b'\r',
485             b't' => b'\t',
486             b'\\' => b'\\',
487             b'\'' => b'\'',
488             b'0' => b'\0',
489             _ => {
490                 match u64::from_str_radix(&lit[2..4], 16).ok() {
491                     Some(c) =>
492                         if c > 0xFF {
493                             panic!(err(2))
494                         } else {
495                             return (c as u8, 4)
496                         },
497                     None => panic!(err(3))
498                 }
499             }
500         };
501         return (b, 2);
502     }
503 }
504
505 pub fn byte_str_lit(lit: &str) -> Rc<Vec<u8>> {
506     let mut res = Vec::with_capacity(lit.len());
507
508     // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
509     let error = |i| format!("lexer should have rejected {} at {}", lit, i);
510
511     /// Eat everything up to a non-whitespace
512     fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
513         loop {
514             match it.peek().map(|x| x.1) {
515                 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
516                     it.next();
517                 },
518                 _ => { break; }
519             }
520         }
521     }
522
523     // byte string literals *must* be ASCII, but the escapes don't have to be
524     let mut chars = lit.bytes().enumerate().peekable();
525     loop {
526         match chars.next() {
527             Some((i, b'\\')) => {
528                 let em = error(i);
529                 match chars.peek().expect(&em).1 {
530                     b'\n' => eat(&mut chars),
531                     b'\r' => {
532                         chars.next();
533                         if chars.peek().expect(&em).1 != b'\n' {
534                             panic!("lexer accepted bare CR");
535                         }
536                         eat(&mut chars);
537                     }
538                     _ => {
539                         // otherwise, a normal escape
540                         let (c, n) = byte_lit(&lit[i..]);
541                         // we don't need to move past the first \
542                         for _ in 0..n - 1 {
543                             chars.next();
544                         }
545                         res.push(c);
546                     }
547                 }
548             },
549             Some((i, b'\r')) => {
550                 let em = error(i);
551                 if chars.peek().expect(&em).1 != b'\n' {
552                     panic!("lexer accepted bare CR");
553                 }
554                 chars.next();
555                 res.push(b'\n');
556             }
557             Some((_, c)) => res.push(c),
558             None => break,
559         }
560     }
561
562     Rc::new(res)
563 }
564
565 pub fn integer_lit(s: &str,
566                    suffix: Option<InternedString>,
567                    sd: &Handler,
568                    sp: Span)
569                    -> ast::Lit_ {
570     // s can only be ascii, byte indexing is fine
571
572     let s2 = s.chars().filter(|&c| c != '_').collect::<String>();
573     let mut s = &s2[..];
574
575     debug!("integer_lit: {}, {:?}", s, suffix);
576
577     let mut base = 10;
578     let orig = s;
579     let mut ty = ast::UnsuffixedIntLit(ast::Plus);
580
581     if char_at(s, 0) == '0' && s.len() > 1 {
582         match char_at(s, 1) {
583             'x' => base = 16,
584             'o' => base = 8,
585             'b' => base = 2,
586             _ => { }
587         }
588     }
589
590     // 1f64 and 2f32 etc. are valid float literals.
591     if let Some(ref suf) = suffix {
592         if looks_like_width_suffix(&['f'], suf) {
593             match base {
594                 16 => sd.span_err(sp, "hexadecimal float literal is not supported"),
595                 8 => sd.span_err(sp, "octal float literal is not supported"),
596                 2 => sd.span_err(sp, "binary float literal is not supported"),
597                 _ => ()
598             }
599             let ident = token::intern_and_get_ident(&*s);
600             return filtered_float_lit(ident, Some(&**suf), sd, sp)
601         }
602     }
603
604     if base != 10 {
605         s = &s[2..];
606     }
607
608     if let Some(ref suf) = suffix {
609         if suf.is_empty() { sd.span_bug(sp, "found empty literal suffix in Some")}
610         ty = match &**suf {
611             "isize" => ast::SignedIntLit(ast::TyIs, ast::Plus),
612             "i8"  => ast::SignedIntLit(ast::TyI8, ast::Plus),
613             "i16" => ast::SignedIntLit(ast::TyI16, ast::Plus),
614             "i32" => ast::SignedIntLit(ast::TyI32, ast::Plus),
615             "i64" => ast::SignedIntLit(ast::TyI64, ast::Plus),
616             "usize" => ast::UnsignedIntLit(ast::TyUs),
617             "u8"  => ast::UnsignedIntLit(ast::TyU8),
618             "u16" => ast::UnsignedIntLit(ast::TyU16),
619             "u32" => ast::UnsignedIntLit(ast::TyU32),
620             "u64" => ast::UnsignedIntLit(ast::TyU64),
621             _ => {
622                 // i<digits> and u<digits> look like widths, so lets
623                 // give an error message along those lines
624                 if looks_like_width_suffix(&['i', 'u'], suf) {
625                     sd.span_err(sp, &format!("invalid width `{}` for integer literal",
626                                              &suf[1..]));
627                     sd.fileline_help(sp, "valid widths are 8, 16, 32 and 64");
628                 } else {
629                     sd.span_err(sp, &format!("invalid suffix `{}` for numeric literal", suf));
630                     sd.fileline_help(sp, "the suffix must be one of the integral types \
631                                       (`u32`, `isize`, etc)");
632                 }
633
634                 ty
635             }
636         }
637     }
638
639     debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
640            string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
641
642     let res = match u64::from_str_radix(s, base).ok() {
643         Some(r) => r,
644         None => {
645             // small bases are lexed as if they were base 10, e.g, the string
646             // might be `0b10201`. This will cause the conversion above to fail,
647             // but these cases have errors in the lexer: we don't want to emit
648             // two errors, and we especially don't want to emit this error since
649             // it isn't necessarily true.
650             let already_errored = base < 10 &&
651                 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
652
653             if !already_errored {
654                 sd.span_err(sp, "int literal is too large");
655             }
656             0
657         }
658     };
659
660     // adjust the sign
661     let sign = ast::Sign::new(res);
662     match ty {
663         ast::SignedIntLit(t, _) => ast::LitInt(res, ast::SignedIntLit(t, sign)),
664         ast::UnsuffixedIntLit(_) => ast::LitInt(res, ast::UnsuffixedIntLit(sign)),
665         us@ast::UnsignedIntLit(_) => ast::LitInt(res, us)
666     }
667 }
668
669 #[cfg(test)]
670 mod tests {
671     use super::*;
672     use std::rc::Rc;
673     use codemap::{Span, BytePos, Pos, Spanned, NO_EXPANSION};
674     use owned_slice::OwnedSlice;
675     use ast::{self, TokenTree};
676     use abi;
677     use attr::{first_attr_value_str_by_name, AttrMetaMethods};
678     use parse;
679     use parse::parser::Parser;
680     use parse::token::{str_to_ident};
681     use print::pprust::item_to_string;
682     use ptr::P;
683     use util::parser_testing::{string_to_tts, string_to_parser};
684     use util::parser_testing::{string_to_expr, string_to_item, string_to_stmt};
685
686     // produce a codemap::span
687     fn sp(a: u32, b: u32) -> Span {
688         Span {lo: BytePos(a), hi: BytePos(b), expn_id: NO_EXPANSION}
689     }
690
691     #[test] fn path_exprs_1() {
692         assert!(string_to_expr("a".to_string()) ==
693                    P(ast::Expr{
694                     id: ast::DUMMY_NODE_ID,
695                     node: ast::ExprPath(None, ast::Path {
696                         span: sp(0, 1),
697                         global: false,
698                         segments: vec!(
699                             ast::PathSegment {
700                                 identifier: str_to_ident("a"),
701                                 parameters: ast::PathParameters::none(),
702                             }
703                         ),
704                     }),
705                     span: sp(0, 1),
706                     attrs: None,
707                    }))
708     }
709
710     #[test] fn path_exprs_2 () {
711         assert!(string_to_expr("::a::b".to_string()) ==
712                    P(ast::Expr {
713                     id: ast::DUMMY_NODE_ID,
714                     node: ast::ExprPath(None, ast::Path {
715                             span: sp(0, 6),
716                             global: true,
717                             segments: vec!(
718                                 ast::PathSegment {
719                                     identifier: str_to_ident("a"),
720                                     parameters: ast::PathParameters::none(),
721                                 },
722                                 ast::PathSegment {
723                                     identifier: str_to_ident("b"),
724                                     parameters: ast::PathParameters::none(),
725                                 }
726                             )
727                         }),
728                     span: sp(0, 6),
729                     attrs: None,
730                    }))
731     }
732
733     #[should_panic]
734     #[test] fn bad_path_expr_1() {
735         string_to_expr("::abc::def::return".to_string());
736     }
737
738     // check the token-tree-ization of macros
739     #[test]
740     fn string_to_tts_macro () {
741         let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_string());
742         let tts: &[ast::TokenTree] = &tts[..];
743
744         match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
745             (
746                 4,
747                 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, token::Plain))),
748                 Some(&TokenTree::Token(_, token::Not)),
749                 Some(&TokenTree::Token(_, token::Ident(name_zip, token::Plain))),
750                 Some(&TokenTree::Delimited(_, ref macro_delimed)),
751             )
752             if name_macro_rules.name.as_str() == "macro_rules"
753             && name_zip.name.as_str() == "zip" => {
754                 let tts = &macro_delimed.tts[..];
755                 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
756                     (
757                         3,
758                         Some(&TokenTree::Delimited(_, ref first_delimed)),
759                         Some(&TokenTree::Token(_, token::FatArrow)),
760                         Some(&TokenTree::Delimited(_, ref second_delimed)),
761                     )
762                     if macro_delimed.delim == token::Paren => {
763                         let tts = &first_delimed.tts[..];
764                         match (tts.len(), tts.get(0), tts.get(1)) {
765                             (
766                                 2,
767                                 Some(&TokenTree::Token(_, token::Dollar)),
768                                 Some(&TokenTree::Token(_, token::Ident(ident, token::Plain))),
769                             )
770                             if first_delimed.delim == token::Paren
771                             && ident.name.as_str() == "a" => {},
772                             _ => panic!("value 3: {:?}", **first_delimed),
773                         }
774                         let tts = &second_delimed.tts[..];
775                         match (tts.len(), tts.get(0), tts.get(1)) {
776                             (
777                                 2,
778                                 Some(&TokenTree::Token(_, token::Dollar)),
779                                 Some(&TokenTree::Token(_, token::Ident(ident, token::Plain))),
780                             )
781                             if second_delimed.delim == token::Paren
782                             && ident.name.as_str() == "a" => {},
783                             _ => panic!("value 4: {:?}", **second_delimed),
784                         }
785                     },
786                     _ => panic!("value 2: {:?}", **macro_delimed),
787                 }
788             },
789             _ => panic!("value: {:?}",tts),
790         }
791     }
792
793     #[test]
794     fn string_to_tts_1() {
795         let tts = string_to_tts("fn a (b : i32) { b; }".to_string());
796
797         let expected = vec![
798             TokenTree::Token(sp(0, 2),
799                          token::Ident(str_to_ident("fn"),
800                          token::IdentStyle::Plain)),
801             TokenTree::Token(sp(3, 4),
802                          token::Ident(str_to_ident("a"),
803                          token::IdentStyle::Plain)),
804             TokenTree::Delimited(
805                 sp(5, 14),
806                 Rc::new(ast::Delimited {
807                     delim: token::DelimToken::Paren,
808                     open_span: sp(5, 6),
809                     tts: vec![
810                         TokenTree::Token(sp(6, 7),
811                                      token::Ident(str_to_ident("b"),
812                                      token::IdentStyle::Plain)),
813                         TokenTree::Token(sp(8, 9),
814                                      token::Colon),
815                         TokenTree::Token(sp(10, 13),
816                                      token::Ident(str_to_ident("i32"),
817                                      token::IdentStyle::Plain)),
818                     ],
819                     close_span: sp(13, 14),
820                 })),
821             TokenTree::Delimited(
822                 sp(15, 21),
823                 Rc::new(ast::Delimited {
824                     delim: token::DelimToken::Brace,
825                     open_span: sp(15, 16),
826                     tts: vec![
827                         TokenTree::Token(sp(17, 18),
828                                      token::Ident(str_to_ident("b"),
829                                      token::IdentStyle::Plain)),
830                         TokenTree::Token(sp(18, 19),
831                                      token::Semi)
832                     ],
833                     close_span: sp(20, 21),
834                 }))
835         ];
836
837         assert_eq!(tts, expected);
838     }
839
840     #[test] fn ret_expr() {
841         assert!(string_to_expr("return d".to_string()) ==
842                    P(ast::Expr{
843                     id: ast::DUMMY_NODE_ID,
844                     node:ast::ExprRet(Some(P(ast::Expr{
845                         id: ast::DUMMY_NODE_ID,
846                         node:ast::ExprPath(None, ast::Path{
847                             span: sp(7, 8),
848                             global: false,
849                             segments: vec!(
850                                 ast::PathSegment {
851                                     identifier: str_to_ident("d"),
852                                     parameters: ast::PathParameters::none(),
853                                 }
854                             ),
855                         }),
856                         span:sp(7,8),
857                         attrs: None,
858                     }))),
859                     span:sp(0,8),
860                     attrs: None,
861                    }))
862     }
863
864     #[test] fn parse_stmt_1 () {
865         assert!(string_to_stmt("b;".to_string()) ==
866                    Some(P(Spanned{
867                        node: ast::StmtExpr(P(ast::Expr {
868                            id: ast::DUMMY_NODE_ID,
869                            node: ast::ExprPath(None, ast::Path {
870                                span:sp(0,1),
871                                global:false,
872                                segments: vec!(
873                                 ast::PathSegment {
874                                     identifier: str_to_ident("b"),
875                                     parameters: ast::PathParameters::none(),
876                                 }
877                                ),
878                             }),
879                            span: sp(0,1),
880                            attrs: None}),
881                                            ast::DUMMY_NODE_ID),
882                        span: sp(0,1)})))
883
884     }
885
886     fn parser_done(p: Parser){
887         assert_eq!(p.token.clone(), token::Eof);
888     }
889
890     #[test] fn parse_ident_pat () {
891         let sess = ParseSess::new();
892         let mut parser = string_to_parser(&sess, "b".to_string());
893         assert!(panictry!(parser.parse_pat())
894                 == P(ast::Pat{
895                 id: ast::DUMMY_NODE_ID,
896                 node: ast::PatIdent(ast::BindByValue(ast::MutImmutable),
897                                     Spanned{ span:sp(0, 1),
898                                              node: str_to_ident("b")
899                     },
900                                     None),
901                 span: sp(0,1)}));
902         parser_done(parser);
903     }
904
905     // check the contents of the tt manually:
906     #[test] fn parse_fundecl () {
907         // this test depends on the intern order of "fn" and "i32"
908         assert_eq!(string_to_item("fn a (b : i32) { b; }".to_string()),
909                   Some(
910                       P(ast::Item{ident:str_to_ident("a"),
911                             attrs:Vec::new(),
912                             id: ast::DUMMY_NODE_ID,
913                             node: ast::ItemFn(P(ast::FnDecl {
914                                 inputs: vec!(ast::Arg{
915                                     ty: P(ast::Ty{id: ast::DUMMY_NODE_ID,
916                                                   node: ast::TyPath(None, ast::Path{
917                                         span:sp(10,13),
918                                         global:false,
919                                         segments: vec!(
920                                             ast::PathSegment {
921                                                 identifier:
922                                                     str_to_ident("i32"),
923                                                 parameters: ast::PathParameters::none(),
924                                             }
925                                         ),
926                                         }),
927                                         span:sp(10,13)
928                                     }),
929                                     pat: P(ast::Pat {
930                                         id: ast::DUMMY_NODE_ID,
931                                         node: ast::PatIdent(
932                                             ast::BindByValue(ast::MutImmutable),
933                                                 Spanned{
934                                                     span: sp(6,7),
935                                                     node: str_to_ident("b")},
936                                                 None
937                                                     ),
938                                             span: sp(6,7)
939                                     }),
940                                         id: ast::DUMMY_NODE_ID
941                                     }),
942                                 output: ast::DefaultReturn(sp(15, 15)),
943                                 variadic: false
944                             }),
945                                     ast::Unsafety::Normal,
946                                     ast::Constness::NotConst,
947                                     abi::Rust,
948                                     ast::Generics{ // no idea on either of these:
949                                         lifetimes: Vec::new(),
950                                         ty_params: OwnedSlice::empty(),
951                                         where_clause: ast::WhereClause {
952                                             id: ast::DUMMY_NODE_ID,
953                                             predicates: Vec::new(),
954                                         }
955                                     },
956                                     P(ast::Block {
957                                         stmts: vec!(P(Spanned{
958                                             node: ast::StmtSemi(P(ast::Expr{
959                                                 id: ast::DUMMY_NODE_ID,
960                                                 node: ast::ExprPath(None,
961                                                       ast::Path{
962                                                         span:sp(17,18),
963                                                         global:false,
964                                                         segments: vec!(
965                                                             ast::PathSegment {
966                                                                 identifier:
967                                                                 str_to_ident(
968                                                                     "b"),
969                                                                 parameters:
970                                                                 ast::PathParameters::none(),
971                                                             }
972                                                         ),
973                                                       }),
974                                                 span: sp(17,18),
975                                                 attrs: None,}),
976                                                 ast::DUMMY_NODE_ID),
977                                             span: sp(17,19)})),
978                                         expr: None,
979                                         id: ast::DUMMY_NODE_ID,
980                                         rules: ast::DefaultBlock, // no idea
981                                         span: sp(15,21),
982                                     })),
983                             vis: ast::Inherited,
984                             span: sp(0,21)})));
985     }
986
987     #[test] fn parse_use() {
988         let use_s = "use foo::bar::baz;";
989         let vitem = string_to_item(use_s.to_string()).unwrap();
990         let vitem_s = item_to_string(&*vitem);
991         assert_eq!(&vitem_s[..], use_s);
992
993         let use_s = "use foo::bar as baz;";
994         let vitem = string_to_item(use_s.to_string()).unwrap();
995         let vitem_s = item_to_string(&*vitem);
996         assert_eq!(&vitem_s[..], use_s);
997     }
998
999     #[test] fn parse_extern_crate() {
1000         let ex_s = "extern crate foo;";
1001         let vitem = string_to_item(ex_s.to_string()).unwrap();
1002         let vitem_s = item_to_string(&*vitem);
1003         assert_eq!(&vitem_s[..], ex_s);
1004
1005         let ex_s = "extern crate foo as bar;";
1006         let vitem = string_to_item(ex_s.to_string()).unwrap();
1007         let vitem_s = item_to_string(&*vitem);
1008         assert_eq!(&vitem_s[..], ex_s);
1009     }
1010
1011     fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
1012         let item = string_to_item(src.to_string()).unwrap();
1013
1014         struct PatIdentVisitor {
1015             spans: Vec<Span>
1016         }
1017         impl<'v> ::visit::Visitor<'v> for PatIdentVisitor {
1018             fn visit_pat(&mut self, p: &'v ast::Pat) {
1019                 match p.node {
1020                     ast::PatIdent(_ , ref spannedident, _) => {
1021                         self.spans.push(spannedident.span.clone());
1022                     }
1023                     _ => {
1024                         ::visit::walk_pat(self, p);
1025                     }
1026                 }
1027             }
1028         }
1029         let mut v = PatIdentVisitor { spans: Vec::new() };
1030         ::visit::walk_item(&mut v, &*item);
1031         return v.spans;
1032     }
1033
1034     #[test] fn span_of_self_arg_pat_idents_are_correct() {
1035
1036         let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
1037                     "impl z { fn a (&mut self, &myarg: i32) {} }",
1038                     "impl z { fn a (&'a self, &myarg: i32) {} }",
1039                     "impl z { fn a (self, &myarg: i32) {} }",
1040                     "impl z { fn a (self: Foo, &myarg: i32) {} }",
1041                     ];
1042
1043         for &src in &srcs {
1044             let spans = get_spans_of_pat_idents(src);
1045             let Span{ lo, hi, .. } = spans[0];
1046             assert!("self" == &src[lo.to_usize()..hi.to_usize()],
1047                     "\"{}\" != \"self\". src=\"{}\"",
1048                     &src[lo.to_usize()..hi.to_usize()], src)
1049         }
1050     }
1051
1052     #[test] fn parse_exprs () {
1053         // just make sure that they parse....
1054         string_to_expr("3 + 4".to_string());
1055         string_to_expr("a::z.froob(b,&(987+3))".to_string());
1056     }
1057
1058     #[test] fn attrs_fix_bug () {
1059         string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
1060                    -> Result<Box<Writer>, String> {
1061     #[cfg(windows)]
1062     fn wb() -> c_int {
1063       (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1064     }
1065
1066     #[cfg(unix)]
1067     fn wb() -> c_int { O_WRONLY as c_int }
1068
1069     let mut fflags: c_int = wb();
1070 }".to_string());
1071     }
1072
1073     #[test] fn crlf_doc_comments() {
1074         let sess = ParseSess::new();
1075
1076         let name = "<source>".to_string();
1077         let source = "/// doc comment\r\nfn foo() {}".to_string();
1078         let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap();
1079         let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1080         assert_eq!(&doc[..], "/// doc comment");
1081
1082         let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1083         let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap();
1084         let docs = item.attrs.iter().filter(|a| &*a.name() == "doc")
1085                     .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1086         let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1087         assert_eq!(&docs[..], b);
1088
1089         let source = "/** doc comment\r\n *  with CRLF */\r\nfn foo() {}".to_string();
1090         let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap();
1091         let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1092         assert_eq!(&doc[..], "/** doc comment\n *  with CRLF */");
1093     }
1094
1095     #[test]
1096     fn ttdelim_span() {
1097         let sess = ParseSess::new();
1098         let expr = parse::parse_expr_from_source_str("foo".to_string(),
1099             "foo!( fn main() { body } )".to_string(), vec![], &sess);
1100
1101         let tts = match expr.node {
1102             ast::ExprMac(ref mac) => mac.node.tts.clone(),
1103             _ => panic!("not a macro"),
1104         };
1105
1106         let span = tts.iter().rev().next().unwrap().get_span();
1107
1108         match sess.codemap().span_to_snippet(span) {
1109             Ok(s) => assert_eq!(&s[..], "{ body }"),
1110             Err(_) => panic!("could not get snippet"),
1111         }
1112     }
1113 }