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