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