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