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