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