]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/mod.rs
Rollup merge of #30511 - defyrlt:issue_30507, r=steveklabnik
[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, DiagnosticBuilder};
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<'a, T> = Result<T, DiagnosticBuilder<'a>>;
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     let mut parser = new_parser_from_file(sess, cfg, input);
80     abort_if_errors(parser.parse_crate_mod(), &parser)
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     let mut parser = new_parser_from_file(sess, cfg, input);
89     abort_if_errors(parser.parse_inner_attributes(), &parser)
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 fn abort_if_errors<'a, T>(result: PResult<'a, T>, p: &Parser) -> T {
275     match result {
276         Ok(c) => {
277             p.abort_if_errors();
278             c
279         }
280         Err(mut e) => {
281             e.emit();
282             p.abort_if_errors();
283             unreachable!();
284         }
285     }
286 }
287
288 /// Parse a string representing a character literal into its final form.
289 /// Rather than just accepting/rejecting a given literal, unescapes it as
290 /// well. Can take any slice prefixed by a character escape. Returns the
291 /// character and the number of characters consumed.
292 pub fn char_lit(lit: &str) -> (char, isize) {
293     use std::char;
294
295     let mut chars = lit.chars();
296     let c = match (chars.next(), chars.next()) {
297         (Some(c), None) if c != '\\' => return (c, 1),
298         (Some('\\'), Some(c)) => match c {
299             '"' => Some('"'),
300             'n' => Some('\n'),
301             'r' => Some('\r'),
302             't' => Some('\t'),
303             '\\' => Some('\\'),
304             '\'' => Some('\''),
305             '0' => Some('\0'),
306             _ => { None }
307         },
308         _ => panic!("lexer accepted invalid char escape `{}`", lit)
309     };
310
311     match c {
312         Some(x) => return (x, 2),
313         None => { }
314     }
315
316     let msg = format!("lexer should have rejected a bad character escape {}", lit);
317     let msg2 = &msg[..];
318
319     fn esc(len: usize, lit: &str) -> Option<(char, isize)> {
320         u32::from_str_radix(&lit[2..len], 16).ok()
321         .and_then(char::from_u32)
322         .map(|x| (x, len as isize))
323     }
324
325     let unicode_escape = || -> Option<(char, isize)> {
326         if lit.as_bytes()[2] == b'{' {
327             let idx = lit.find('}').expect(msg2);
328             let subslice = &lit[3..idx];
329             u32::from_str_radix(subslice, 16).ok()
330                 .and_then(char::from_u32)
331                 .map(|x| (x, subslice.chars().count() as isize + 4))
332         } else {
333             esc(6, lit)
334         }
335     };
336
337     // Unicode escapes
338     return match lit.as_bytes()[1] as char {
339         'x' | 'X' => esc(4, lit),
340         'u' => unicode_escape(),
341         'U' => esc(10, lit),
342         _ => None,
343     }.expect(msg2);
344 }
345
346 /// Parse a string representing a string literal into its final form. Does
347 /// unescaping.
348 pub fn str_lit(lit: &str) -> String {
349     debug!("parse_str_lit: given {}", lit.escape_default());
350     let mut res = String::with_capacity(lit.len());
351
352     // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
353     let error = |i| format!("lexer should have rejected {} at {}", lit, i);
354
355     /// Eat everything up to a non-whitespace
356     fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
357         loop {
358             match it.peek().map(|x| x.1) {
359                 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
360                     it.next();
361                 },
362                 _ => { break; }
363             }
364         }
365     }
366
367     let mut chars = lit.char_indices().peekable();
368     loop {
369         match chars.next() {
370             Some((i, c)) => {
371                 match c {
372                     '\\' => {
373                         let ch = chars.peek().unwrap_or_else(|| {
374                             panic!("{}", error(i))
375                         }).1;
376
377                         if ch == '\n' {
378                             eat(&mut chars);
379                         } else if ch == '\r' {
380                             chars.next();
381                             let ch = chars.peek().unwrap_or_else(|| {
382                                 panic!("{}", error(i))
383                             }).1;
384
385                             if ch != '\n' {
386                                 panic!("lexer accepted bare CR");
387                             }
388                             eat(&mut chars);
389                         } else {
390                             // otherwise, a normal escape
391                             let (c, n) = char_lit(&lit[i..]);
392                             for _ in 0..n - 1 { // we don't need to move past the first \
393                                 chars.next();
394                             }
395                             res.push(c);
396                         }
397                     },
398                     '\r' => {
399                         let ch = chars.peek().unwrap_or_else(|| {
400                             panic!("{}", error(i))
401                         }).1;
402
403                         if ch != '\n' {
404                             panic!("lexer accepted bare CR");
405                         }
406                         chars.next();
407                         res.push('\n');
408                     }
409                     c => res.push(c),
410                 }
411             },
412             None => break
413         }
414     }
415
416     res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
417     debug!("parse_str_lit: returning {}", res);
418     res
419 }
420
421 /// Parse a string representing a raw string literal into its final form. The
422 /// only operation this does is convert embedded CRLF into a single LF.
423 pub fn raw_str_lit(lit: &str) -> String {
424     debug!("raw_str_lit: given {}", lit.escape_default());
425     let mut res = String::with_capacity(lit.len());
426
427     // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
428     let mut chars = lit.chars().peekable();
429     loop {
430         match chars.next() {
431             Some(c) => {
432                 if c == '\r' {
433                     if *chars.peek().unwrap() != '\n' {
434                         panic!("lexer accepted bare CR");
435                     }
436                     chars.next();
437                     res.push('\n');
438                 } else {
439                     res.push(c);
440                 }
441             },
442             None => break
443         }
444     }
445
446     res.shrink_to_fit();
447     res
448 }
449
450 // check if `s` looks like i32 or u1234 etc.
451 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
452     s.len() > 1 &&
453         first_chars.contains(&char_at(s, 0)) &&
454         s[1..].chars().all(|c| '0' <= c && c <= '9')
455 }
456
457 fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>,
458                       sd: &Handler, sp: Span) -> ast::Lit_ {
459     debug!("filtered_float_lit: {}, {:?}", data, suffix);
460     match suffix.as_ref().map(|s| &**s) {
461         Some("f32") => ast::LitFloat(data, ast::TyF32),
462         Some("f64") => ast::LitFloat(data, ast::TyF64),
463         Some(suf) => {
464             if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
465                 // if it looks like a width, lets try to be helpful.
466                 sd.struct_span_err(sp, &format!("invalid width `{}` for float literal", &suf[1..]))
467                  .fileline_help(sp, "valid widths are 32 and 64")
468                  .emit();
469             } else {
470                 sd.struct_span_err(sp, &format!("invalid suffix `{}` for float literal", suf))
471                   .fileline_help(sp, "valid suffixes are `f32` and `f64`")
472                   .emit();
473             }
474
475             ast::LitFloatUnsuffixed(data)
476         }
477         None => ast::LitFloatUnsuffixed(data)
478     }
479 }
480 pub fn float_lit(s: &str, suffix: Option<InternedString>,
481                  sd: &Handler, sp: Span) -> ast::Lit_ {
482     debug!("float_lit: {:?}, {:?}", s, suffix);
483     // FIXME #2252: bounds checking float literals is deferred until trans
484     let s = s.chars().filter(|&c| c != '_').collect::<String>();
485     let data = token::intern_and_get_ident(&s);
486     filtered_float_lit(data, suffix.as_ref().map(|s| &**s), sd, sp)
487 }
488
489 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
490 pub fn byte_lit(lit: &str) -> (u8, usize) {
491     let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
492
493     if lit.len() == 1 {
494         (lit.as_bytes()[0], 1)
495     } else {
496         assert!(lit.as_bytes()[0] == b'\\', err(0));
497         let b = match lit.as_bytes()[1] {
498             b'"' => b'"',
499             b'n' => b'\n',
500             b'r' => b'\r',
501             b't' => b'\t',
502             b'\\' => b'\\',
503             b'\'' => b'\'',
504             b'0' => b'\0',
505             _ => {
506                 match u64::from_str_radix(&lit[2..4], 16).ok() {
507                     Some(c) =>
508                         if c > 0xFF {
509                             panic!(err(2))
510                         } else {
511                             return (c as u8, 4)
512                         },
513                     None => panic!(err(3))
514                 }
515             }
516         };
517         return (b, 2);
518     }
519 }
520
521 pub fn byte_str_lit(lit: &str) -> Rc<Vec<u8>> {
522     let mut res = Vec::with_capacity(lit.len());
523
524     // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
525     let error = |i| format!("lexer should have rejected {} at {}", lit, i);
526
527     /// Eat everything up to a non-whitespace
528     fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
529         loop {
530             match it.peek().map(|x| x.1) {
531                 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
532                     it.next();
533                 },
534                 _ => { break; }
535             }
536         }
537     }
538
539     // byte string literals *must* be ASCII, but the escapes don't have to be
540     let mut chars = lit.bytes().enumerate().peekable();
541     loop {
542         match chars.next() {
543             Some((i, b'\\')) => {
544                 let em = error(i);
545                 match chars.peek().expect(&em).1 {
546                     b'\n' => eat(&mut chars),
547                     b'\r' => {
548                         chars.next();
549                         if chars.peek().expect(&em).1 != b'\n' {
550                             panic!("lexer accepted bare CR");
551                         }
552                         eat(&mut chars);
553                     }
554                     _ => {
555                         // otherwise, a normal escape
556                         let (c, n) = byte_lit(&lit[i..]);
557                         // we don't need to move past the first \
558                         for _ in 0..n - 1 {
559                             chars.next();
560                         }
561                         res.push(c);
562                     }
563                 }
564             },
565             Some((i, b'\r')) => {
566                 let em = error(i);
567                 if chars.peek().expect(&em).1 != b'\n' {
568                     panic!("lexer accepted bare CR");
569                 }
570                 chars.next();
571                 res.push(b'\n');
572             }
573             Some((_, c)) => res.push(c),
574             None => break,
575         }
576     }
577
578     Rc::new(res)
579 }
580
581 pub fn integer_lit(s: &str,
582                    suffix: Option<InternedString>,
583                    sd: &Handler,
584                    sp: Span)
585                    -> ast::Lit_ {
586     // s can only be ascii, byte indexing is fine
587
588     let s2 = s.chars().filter(|&c| c != '_').collect::<String>();
589     let mut s = &s2[..];
590
591     debug!("integer_lit: {}, {:?}", s, suffix);
592
593     let mut base = 10;
594     let orig = s;
595     let mut ty = ast::UnsuffixedIntLit(ast::Plus);
596
597     if char_at(s, 0) == '0' && s.len() > 1 {
598         match char_at(s, 1) {
599             'x' => base = 16,
600             'o' => base = 8,
601             'b' => base = 2,
602             _ => { }
603         }
604     }
605
606     // 1f64 and 2f32 etc. are valid float literals.
607     if let Some(ref suf) = suffix {
608         if looks_like_width_suffix(&['f'], suf) {
609             match base {
610                 16 => sd.span_err(sp, "hexadecimal float literal is not supported"),
611                 8 => sd.span_err(sp, "octal float literal is not supported"),
612                 2 => sd.span_err(sp, "binary float literal is not supported"),
613                 _ => ()
614             }
615             let ident = token::intern_and_get_ident(&*s);
616             return filtered_float_lit(ident, Some(&**suf), sd, sp)
617         }
618     }
619
620     if base != 10 {
621         s = &s[2..];
622     }
623
624     if let Some(ref suf) = suffix {
625         if suf.is_empty() { sd.span_bug(sp, "found empty literal suffix in Some")}
626         ty = match &**suf {
627             "isize" => ast::SignedIntLit(ast::TyIs, ast::Plus),
628             "i8"  => ast::SignedIntLit(ast::TyI8, ast::Plus),
629             "i16" => ast::SignedIntLit(ast::TyI16, ast::Plus),
630             "i32" => ast::SignedIntLit(ast::TyI32, ast::Plus),
631             "i64" => ast::SignedIntLit(ast::TyI64, ast::Plus),
632             "usize" => ast::UnsignedIntLit(ast::TyUs),
633             "u8"  => ast::UnsignedIntLit(ast::TyU8),
634             "u16" => ast::UnsignedIntLit(ast::TyU16),
635             "u32" => ast::UnsignedIntLit(ast::TyU32),
636             "u64" => ast::UnsignedIntLit(ast::TyU64),
637             _ => {
638                 // i<digits> and u<digits> look like widths, so lets
639                 // give an error message along those lines
640                 if looks_like_width_suffix(&['i', 'u'], suf) {
641                     sd.struct_span_err(sp, &format!("invalid width `{}` for integer literal",
642                                              &suf[1..]))
643                       .fileline_help(sp, "valid widths are 8, 16, 32 and 64")
644                       .emit();
645                 } else {
646                     sd.struct_span_err(sp, &format!("invalid suffix `{}` for numeric literal", suf))
647                       .fileline_help(sp, "the suffix must be one of the integral types \
648                                       (`u32`, `isize`, etc)")
649                       .emit();
650                 }
651
652                 ty
653             }
654         }
655     }
656
657     debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
658            string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
659
660     let res = match u64::from_str_radix(s, base).ok() {
661         Some(r) => r,
662         None => {
663             // small bases are lexed as if they were base 10, e.g, the string
664             // might be `0b10201`. This will cause the conversion above to fail,
665             // but these cases have errors in the lexer: we don't want to emit
666             // two errors, and we especially don't want to emit this error since
667             // it isn't necessarily true.
668             let already_errored = base < 10 &&
669                 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
670
671             if !already_errored {
672                 sd.span_err(sp, "int literal is too large");
673             }
674             0
675         }
676     };
677
678     // adjust the sign
679     let sign = ast::Sign::new(res);
680     match ty {
681         ast::SignedIntLit(t, _) => ast::LitInt(res, ast::SignedIntLit(t, sign)),
682         ast::UnsuffixedIntLit(_) => ast::LitInt(res, ast::UnsuffixedIntLit(sign)),
683         us@ast::UnsignedIntLit(_) => ast::LitInt(res, us)
684     }
685 }
686
687 #[cfg(test)]
688 mod tests {
689     use super::*;
690     use std::rc::Rc;
691     use codemap::{Span, BytePos, Pos, Spanned, NO_EXPANSION};
692     use ast::{self, TokenTree};
693     use abi;
694     use attr::{first_attr_value_str_by_name, AttrMetaMethods};
695     use parse;
696     use parse::parser::Parser;
697     use parse::token::{str_to_ident};
698     use print::pprust::item_to_string;
699     use ptr::P;
700     use util::parser_testing::{string_to_tts, string_to_parser};
701     use util::parser_testing::{string_to_expr, string_to_item, string_to_stmt};
702
703     // produce a codemap::span
704     fn sp(a: u32, b: u32) -> Span {
705         Span {lo: BytePos(a), hi: BytePos(b), expn_id: NO_EXPANSION}
706     }
707
708     #[test] fn path_exprs_1() {
709         assert!(string_to_expr("a".to_string()) ==
710                    P(ast::Expr{
711                     id: ast::DUMMY_NODE_ID,
712                     node: ast::ExprPath(None, ast::Path {
713                         span: sp(0, 1),
714                         global: false,
715                         segments: vec!(
716                             ast::PathSegment {
717                                 identifier: str_to_ident("a"),
718                                 parameters: ast::PathParameters::none(),
719                             }
720                         ),
721                     }),
722                     span: sp(0, 1),
723                     attrs: None,
724                    }))
725     }
726
727     #[test] fn path_exprs_2 () {
728         assert!(string_to_expr("::a::b".to_string()) ==
729                    P(ast::Expr {
730                     id: ast::DUMMY_NODE_ID,
731                     node: ast::ExprPath(None, ast::Path {
732                             span: sp(0, 6),
733                             global: true,
734                             segments: vec!(
735                                 ast::PathSegment {
736                                     identifier: str_to_ident("a"),
737                                     parameters: ast::PathParameters::none(),
738                                 },
739                                 ast::PathSegment {
740                                     identifier: str_to_ident("b"),
741                                     parameters: ast::PathParameters::none(),
742                                 }
743                             )
744                         }),
745                     span: sp(0, 6),
746                     attrs: None,
747                    }))
748     }
749
750     #[should_panic]
751     #[test] fn bad_path_expr_1() {
752         string_to_expr("::abc::def::return".to_string());
753     }
754
755     // check the token-tree-ization of macros
756     #[test]
757     fn string_to_tts_macro () {
758         let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_string());
759         let tts: &[ast::TokenTree] = &tts[..];
760
761         match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
762             (
763                 4,
764                 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, token::Plain))),
765                 Some(&TokenTree::Token(_, token::Not)),
766                 Some(&TokenTree::Token(_, token::Ident(name_zip, token::Plain))),
767                 Some(&TokenTree::Delimited(_, ref macro_delimed)),
768             )
769             if name_macro_rules.name.as_str() == "macro_rules"
770             && name_zip.name.as_str() == "zip" => {
771                 let tts = &macro_delimed.tts[..];
772                 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
773                     (
774                         3,
775                         Some(&TokenTree::Delimited(_, ref first_delimed)),
776                         Some(&TokenTree::Token(_, token::FatArrow)),
777                         Some(&TokenTree::Delimited(_, ref second_delimed)),
778                     )
779                     if macro_delimed.delim == token::Paren => {
780                         let tts = &first_delimed.tts[..];
781                         match (tts.len(), tts.get(0), tts.get(1)) {
782                             (
783                                 2,
784                                 Some(&TokenTree::Token(_, token::Dollar)),
785                                 Some(&TokenTree::Token(_, token::Ident(ident, token::Plain))),
786                             )
787                             if first_delimed.delim == token::Paren
788                             && ident.name.as_str() == "a" => {},
789                             _ => panic!("value 3: {:?}", **first_delimed),
790                         }
791                         let tts = &second_delimed.tts[..];
792                         match (tts.len(), tts.get(0), tts.get(1)) {
793                             (
794                                 2,
795                                 Some(&TokenTree::Token(_, token::Dollar)),
796                                 Some(&TokenTree::Token(_, token::Ident(ident, token::Plain))),
797                             )
798                             if second_delimed.delim == token::Paren
799                             && ident.name.as_str() == "a" => {},
800                             _ => panic!("value 4: {:?}", **second_delimed),
801                         }
802                     },
803                     _ => panic!("value 2: {:?}", **macro_delimed),
804                 }
805             },
806             _ => panic!("value: {:?}",tts),
807         }
808     }
809
810     #[test]
811     fn string_to_tts_1() {
812         let tts = string_to_tts("fn a (b : i32) { b; }".to_string());
813
814         let expected = vec![
815             TokenTree::Token(sp(0, 2),
816                          token::Ident(str_to_ident("fn"),
817                          token::IdentStyle::Plain)),
818             TokenTree::Token(sp(3, 4),
819                          token::Ident(str_to_ident("a"),
820                          token::IdentStyle::Plain)),
821             TokenTree::Delimited(
822                 sp(5, 14),
823                 Rc::new(ast::Delimited {
824                     delim: token::DelimToken::Paren,
825                     open_span: sp(5, 6),
826                     tts: vec![
827                         TokenTree::Token(sp(6, 7),
828                                      token::Ident(str_to_ident("b"),
829                                      token::IdentStyle::Plain)),
830                         TokenTree::Token(sp(8, 9),
831                                      token::Colon),
832                         TokenTree::Token(sp(10, 13),
833                                      token::Ident(str_to_ident("i32"),
834                                      token::IdentStyle::Plain)),
835                     ],
836                     close_span: sp(13, 14),
837                 })),
838             TokenTree::Delimited(
839                 sp(15, 21),
840                 Rc::new(ast::Delimited {
841                     delim: token::DelimToken::Brace,
842                     open_span: sp(15, 16),
843                     tts: vec![
844                         TokenTree::Token(sp(17, 18),
845                                      token::Ident(str_to_ident("b"),
846                                      token::IdentStyle::Plain)),
847                         TokenTree::Token(sp(18, 19),
848                                      token::Semi)
849                     ],
850                     close_span: sp(20, 21),
851                 }))
852         ];
853
854         assert_eq!(tts, expected);
855     }
856
857     #[test] fn ret_expr() {
858         assert!(string_to_expr("return d".to_string()) ==
859                    P(ast::Expr{
860                     id: ast::DUMMY_NODE_ID,
861                     node:ast::ExprRet(Some(P(ast::Expr{
862                         id: ast::DUMMY_NODE_ID,
863                         node:ast::ExprPath(None, ast::Path{
864                             span: sp(7, 8),
865                             global: false,
866                             segments: vec!(
867                                 ast::PathSegment {
868                                     identifier: str_to_ident("d"),
869                                     parameters: ast::PathParameters::none(),
870                                 }
871                             ),
872                         }),
873                         span:sp(7,8),
874                         attrs: None,
875                     }))),
876                     span:sp(0,8),
877                     attrs: None,
878                    }))
879     }
880
881     #[test] fn parse_stmt_1 () {
882         assert!(string_to_stmt("b;".to_string()) ==
883                    Some(P(Spanned{
884                        node: ast::StmtExpr(P(ast::Expr {
885                            id: ast::DUMMY_NODE_ID,
886                            node: ast::ExprPath(None, ast::Path {
887                                span:sp(0,1),
888                                global:false,
889                                segments: vec!(
890                                 ast::PathSegment {
891                                     identifier: str_to_ident("b"),
892                                     parameters: ast::PathParameters::none(),
893                                 }
894                                ),
895                             }),
896                            span: sp(0,1),
897                            attrs: None}),
898                                            ast::DUMMY_NODE_ID),
899                        span: sp(0,1)})))
900
901     }
902
903     fn parser_done(p: Parser){
904         assert_eq!(p.token.clone(), token::Eof);
905     }
906
907     #[test] fn parse_ident_pat () {
908         let sess = ParseSess::new();
909         let mut parser = string_to_parser(&sess, "b".to_string());
910         assert!(panictry!(parser.parse_pat())
911                 == P(ast::Pat{
912                 id: ast::DUMMY_NODE_ID,
913                 node: ast::PatIdent(ast::BindingMode::ByValue(ast::MutImmutable),
914                                     Spanned{ span:sp(0, 1),
915                                              node: str_to_ident("b")
916                     },
917                                     None),
918                 span: sp(0,1)}));
919         parser_done(parser);
920     }
921
922     // check the contents of the tt manually:
923     #[test] fn parse_fundecl () {
924         // this test depends on the intern order of "fn" and "i32"
925         assert_eq!(string_to_item("fn a (b : i32) { b; }".to_string()),
926                   Some(
927                       P(ast::Item{ident:str_to_ident("a"),
928                             attrs:Vec::new(),
929                             id: ast::DUMMY_NODE_ID,
930                             node: ast::ItemFn(P(ast::FnDecl {
931                                 inputs: vec!(ast::Arg{
932                                     ty: P(ast::Ty{id: ast::DUMMY_NODE_ID,
933                                                   node: ast::TyPath(None, ast::Path{
934                                         span:sp(10,13),
935                                         global:false,
936                                         segments: vec!(
937                                             ast::PathSegment {
938                                                 identifier:
939                                                     str_to_ident("i32"),
940                                                 parameters: ast::PathParameters::none(),
941                                             }
942                                         ),
943                                         }),
944                                         span:sp(10,13)
945                                     }),
946                                     pat: P(ast::Pat {
947                                         id: ast::DUMMY_NODE_ID,
948                                         node: ast::PatIdent(
949                                             ast::BindingMode::ByValue(ast::MutImmutable),
950                                                 Spanned{
951                                                     span: sp(6,7),
952                                                     node: str_to_ident("b")},
953                                                 None
954                                                     ),
955                                             span: sp(6,7)
956                                     }),
957                                         id: ast::DUMMY_NODE_ID
958                                     }),
959                                 output: ast::DefaultReturn(sp(15, 15)),
960                                 variadic: false
961                             }),
962                                     ast::Unsafety::Normal,
963                                     ast::Constness::NotConst,
964                                     abi::Rust,
965                                     ast::Generics{ // no idea on either of these:
966                                         lifetimes: Vec::new(),
967                                         ty_params: P::empty(),
968                                         where_clause: ast::WhereClause {
969                                             id: ast::DUMMY_NODE_ID,
970                                             predicates: Vec::new(),
971                                         }
972                                     },
973                                     P(ast::Block {
974                                         stmts: vec!(P(Spanned{
975                                             node: ast::StmtSemi(P(ast::Expr{
976                                                 id: ast::DUMMY_NODE_ID,
977                                                 node: ast::ExprPath(None,
978                                                       ast::Path{
979                                                         span:sp(17,18),
980                                                         global:false,
981                                                         segments: vec!(
982                                                             ast::PathSegment {
983                                                                 identifier:
984                                                                 str_to_ident(
985                                                                     "b"),
986                                                                 parameters:
987                                                                 ast::PathParameters::none(),
988                                                             }
989                                                         ),
990                                                       }),
991                                                 span: sp(17,18),
992                                                 attrs: None,}),
993                                                 ast::DUMMY_NODE_ID),
994                                             span: sp(17,19)})),
995                                         expr: None,
996                                         id: ast::DUMMY_NODE_ID,
997                                         rules: ast::DefaultBlock, // no idea
998                                         span: sp(15,21),
999                                     })),
1000                             vis: ast::Inherited,
1001                             span: sp(0,21)})));
1002     }
1003
1004     #[test] fn parse_use() {
1005         let use_s = "use foo::bar::baz;";
1006         let vitem = string_to_item(use_s.to_string()).unwrap();
1007         let vitem_s = item_to_string(&*vitem);
1008         assert_eq!(&vitem_s[..], use_s);
1009
1010         let use_s = "use foo::bar as baz;";
1011         let vitem = string_to_item(use_s.to_string()).unwrap();
1012         let vitem_s = item_to_string(&*vitem);
1013         assert_eq!(&vitem_s[..], use_s);
1014     }
1015
1016     #[test] fn parse_extern_crate() {
1017         let ex_s = "extern crate foo;";
1018         let vitem = string_to_item(ex_s.to_string()).unwrap();
1019         let vitem_s = item_to_string(&*vitem);
1020         assert_eq!(&vitem_s[..], ex_s);
1021
1022         let ex_s = "extern crate foo as bar;";
1023         let vitem = string_to_item(ex_s.to_string()).unwrap();
1024         let vitem_s = item_to_string(&*vitem);
1025         assert_eq!(&vitem_s[..], ex_s);
1026     }
1027
1028     fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
1029         let item = string_to_item(src.to_string()).unwrap();
1030
1031         struct PatIdentVisitor {
1032             spans: Vec<Span>
1033         }
1034         impl<'v> ::visit::Visitor<'v> for PatIdentVisitor {
1035             fn visit_pat(&mut self, p: &'v ast::Pat) {
1036                 match p.node {
1037                     ast::PatIdent(_ , ref spannedident, _) => {
1038                         self.spans.push(spannedident.span.clone());
1039                     }
1040                     _ => {
1041                         ::visit::walk_pat(self, p);
1042                     }
1043                 }
1044             }
1045         }
1046         let mut v = PatIdentVisitor { spans: Vec::new() };
1047         ::visit::walk_item(&mut v, &*item);
1048         return v.spans;
1049     }
1050
1051     #[test] fn span_of_self_arg_pat_idents_are_correct() {
1052
1053         let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
1054                     "impl z { fn a (&mut self, &myarg: i32) {} }",
1055                     "impl z { fn a (&'a self, &myarg: i32) {} }",
1056                     "impl z { fn a (self, &myarg: i32) {} }",
1057                     "impl z { fn a (self: Foo, &myarg: i32) {} }",
1058                     ];
1059
1060         for &src in &srcs {
1061             let spans = get_spans_of_pat_idents(src);
1062             let Span{ lo, hi, .. } = spans[0];
1063             assert!("self" == &src[lo.to_usize()..hi.to_usize()],
1064                     "\"{}\" != \"self\". src=\"{}\"",
1065                     &src[lo.to_usize()..hi.to_usize()], src)
1066         }
1067     }
1068
1069     #[test] fn parse_exprs () {
1070         // just make sure that they parse....
1071         string_to_expr("3 + 4".to_string());
1072         string_to_expr("a::z.froob(b,&(987+3))".to_string());
1073     }
1074
1075     #[test] fn attrs_fix_bug () {
1076         string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
1077                    -> Result<Box<Writer>, String> {
1078     #[cfg(windows)]
1079     fn wb() -> c_int {
1080       (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1081     }
1082
1083     #[cfg(unix)]
1084     fn wb() -> c_int { O_WRONLY as c_int }
1085
1086     let mut fflags: c_int = wb();
1087 }".to_string());
1088     }
1089
1090     #[test] fn crlf_doc_comments() {
1091         let sess = ParseSess::new();
1092
1093         let name = "<source>".to_string();
1094         let source = "/// doc comment\r\nfn foo() {}".to_string();
1095         let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap();
1096         let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1097         assert_eq!(&doc[..], "/// doc comment");
1098
1099         let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1100         let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap();
1101         let docs = item.attrs.iter().filter(|a| &*a.name() == "doc")
1102                     .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1103         let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1104         assert_eq!(&docs[..], b);
1105
1106         let source = "/** doc comment\r\n *  with CRLF */\r\nfn foo() {}".to_string();
1107         let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap();
1108         let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1109         assert_eq!(&doc[..], "/** doc comment\n *  with CRLF */");
1110     }
1111
1112     #[test]
1113     fn ttdelim_span() {
1114         let sess = ParseSess::new();
1115         let expr = parse::parse_expr_from_source_str("foo".to_string(),
1116             "foo!( fn main() { body } )".to_string(), vec![], &sess);
1117
1118         let tts = match expr.node {
1119             ast::ExprMac(ref mac) => mac.node.tts.clone(),
1120             _ => panic!("not a macro"),
1121         };
1122
1123         let span = tts.iter().rev().next().unwrap().get_span();
1124
1125         match sess.codemap().span_to_snippet(span) {
1126             Ok(s) => assert_eq!(&s[..], "{ body }"),
1127             Err(_) => panic!("could not get snippet"),
1128         }
1129     }
1130 }