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