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