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