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