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