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