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