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