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