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