]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/mod.rs
rollup merge of #20608: nikomatsakis/assoc-types-method-dispatch
[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)[]);
255             unreachable!()
256         }
257     };
258     match str::from_utf8(bytes[]).ok() {
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())[])
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[];
395
396     fn esc(len: uint, lit: &str) -> Option<(char, int)> {
397         num::from_str_radix(lit[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[3..idx];
406             num::from_str_radix(subslice, 16)
407                 .and_then(char::from_u32)
408                 .map(|x| (x, subslice.chars().count() 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::CharIndices<'a>>) {
433         loop {
434             match it.peek().map(|x| x.1) {
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                         }).1;
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                             }).1;
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[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                         }).1;
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[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[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[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<Item=(uint, u8)>>(it: &mut iter::Peekable<(uint, u8), I>) {
602         loop {
603             match it.peek().map(|x| x.1) {
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()).1 {
619                     b'\n' => eat(&mut chars),
620                     b'\r' => {
621                         chars.next();
622                         if chars.peek().expect(em.as_slice()).1 != 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[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()).1 != 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[];
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[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[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::{first_attr_value_str_by_name, AttrMetaMethods};
749     use parse::parser::Parser;
750     use parse::token::{str_to_ident};
751     use print::pprust::view_item_to_string;
752     use ptr::P;
753     use util::parser_testing::{string_to_tts, string_to_parser};
754     use util::parser_testing::{string_to_expr, string_to_item};
755     use util::parser_testing::{string_to_stmt, string_to_view_item};
756
757     // produce a codemap::span
758     fn sp(a: u32, b: u32) -> Span {
759         Span {lo: BytePos(a), hi: BytePos(b), expn_id: NO_EXPANSION}
760     }
761
762     #[test] fn path_exprs_1() {
763         assert!(string_to_expr("a".to_string()) ==
764                    P(ast::Expr{
765                     id: ast::DUMMY_NODE_ID,
766                     node: ast::ExprPath(ast::Path {
767                         span: sp(0, 1),
768                         global: false,
769                         segments: vec!(
770                             ast::PathSegment {
771                                 identifier: str_to_ident("a"),
772                                 parameters: ast::PathParameters::none(),
773                             }
774                         ),
775                     }),
776                     span: sp(0, 1)
777                    }))
778     }
779
780     #[test] fn path_exprs_2 () {
781         assert!(string_to_expr("::a::b".to_string()) ==
782                    P(ast::Expr {
783                     id: ast::DUMMY_NODE_ID,
784                     node: ast::ExprPath(ast::Path {
785                             span: sp(0, 6),
786                             global: true,
787                             segments: vec!(
788                                 ast::PathSegment {
789                                     identifier: str_to_ident("a"),
790                                     parameters: ast::PathParameters::none(),
791                                 },
792                                 ast::PathSegment {
793                                     identifier: str_to_ident("b"),
794                                     parameters: ast::PathParameters::none(),
795                                 }
796                             )
797                         }),
798                     span: sp(0, 6)
799                    }))
800     }
801
802     #[should_fail]
803     #[test] fn bad_path_expr_1() {
804         string_to_expr("::abc::def::return".to_string());
805     }
806
807     // check the token-tree-ization of macros
808     #[test]
809     fn string_to_tts_macro () {
810         let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_string());
811         let tts: &[ast::TokenTree] = tts[];
812         match tts {
813             [ast::TtToken(_, token::Ident(name_macro_rules, token::Plain)),
814              ast::TtToken(_, token::Not),
815              ast::TtToken(_, token::Ident(name_zip, token::Plain)),
816              ast::TtDelimited(_, ref macro_delimed)]
817             if name_macro_rules.as_str() == "macro_rules"
818             && name_zip.as_str() == "zip" => {
819                 match macro_delimed.tts[] {
820                     [ast::TtDelimited(_, ref first_delimed),
821                      ast::TtToken(_, token::FatArrow),
822                      ast::TtDelimited(_, ref second_delimed)]
823                     if macro_delimed.delim == token::Paren => {
824                         match first_delimed.tts[] {
825                             [ast::TtToken(_, token::Dollar),
826                              ast::TtToken(_, token::Ident(name, token::Plain))]
827                             if first_delimed.delim == token::Paren
828                             && name.as_str() == "a" => {},
829                             _ => panic!("value 3: {}", **first_delimed),
830                         }
831                         match second_delimed.tts[] {
832                             [ast::TtToken(_, token::Dollar),
833                              ast::TtToken(_, token::Ident(name, token::Plain))]
834                             if second_delimed.delim == token::Paren
835                             && name.as_str() == "a" => {},
836                             _ => panic!("value 4: {}", **second_delimed),
837                         }
838                     },
839                     _ => panic!("value 2: {}", **macro_delimed),
840                 }
841             },
842             _ => panic!("value: {}",tts),
843         }
844     }
845
846     #[test]
847     fn string_to_tts_1 () {
848         let tts = string_to_tts("fn a (b : int) { b; }".to_string());
849         assert_eq!(json::encode(&tts),
850         "[\
851     {\
852         \"variant\":\"TtToken\",\
853         \"fields\":[\
854             null,\
855             {\
856                 \"variant\":\"Ident\",\
857                 \"fields\":[\
858                     \"fn\",\
859                     \"Plain\"\
860                 ]\
861             }\
862         ]\
863     },\
864     {\
865         \"variant\":\"TtToken\",\
866         \"fields\":[\
867             null,\
868             {\
869                 \"variant\":\"Ident\",\
870                 \"fields\":[\
871                     \"a\",\
872                     \"Plain\"\
873                 ]\
874             }\
875         ]\
876     },\
877     {\
878         \"variant\":\"TtDelimited\",\
879         \"fields\":[\
880             null,\
881             {\
882                 \"delim\":\"Paren\",\
883                 \"open_span\":null,\
884                 \"tts\":[\
885                     {\
886                         \"variant\":\"TtToken\",\
887                         \"fields\":[\
888                             null,\
889                             {\
890                                 \"variant\":\"Ident\",\
891                                 \"fields\":[\
892                                     \"b\",\
893                                     \"Plain\"\
894                                 ]\
895                             }\
896                         ]\
897                     },\
898                     {\
899                         \"variant\":\"TtToken\",\
900                         \"fields\":[\
901                             null,\
902                             \"Colon\"\
903                         ]\
904                     },\
905                     {\
906                         \"variant\":\"TtToken\",\
907                         \"fields\":[\
908                             null,\
909                             {\
910                                 \"variant\":\"Ident\",\
911                                 \"fields\":[\
912                                     \"int\",\
913                                     \"Plain\"\
914                                 ]\
915                             }\
916                         ]\
917                     }\
918                 ],\
919                 \"close_span\":null\
920             }\
921         ]\
922     },\
923     {\
924         \"variant\":\"TtDelimited\",\
925         \"fields\":[\
926             null,\
927             {\
928                 \"delim\":\"Brace\",\
929                 \"open_span\":null,\
930                 \"tts\":[\
931                     {\
932                         \"variant\":\"TtToken\",\
933                         \"fields\":[\
934                             null,\
935                             {\
936                                 \"variant\":\"Ident\",\
937                                 \"fields\":[\
938                                     \"b\",\
939                                     \"Plain\"\
940                                 ]\
941                             }\
942                         ]\
943                     },\
944                     {\
945                         \"variant\":\"TtToken\",\
946                         \"fields\":[\
947                             null,\
948                             \"Semi\"\
949                         ]\
950                     }\
951                 ],\
952                 \"close_span\":null\
953             }\
954         ]\
955     }\
956 ]"
957         );
958     }
959
960     #[test] fn ret_expr() {
961         assert!(string_to_expr("return d".to_string()) ==
962                    P(ast::Expr{
963                     id: ast::DUMMY_NODE_ID,
964                     node:ast::ExprRet(Some(P(ast::Expr{
965                         id: ast::DUMMY_NODE_ID,
966                         node:ast::ExprPath(ast::Path{
967                             span: sp(7, 8),
968                             global: false,
969                             segments: vec!(
970                                 ast::PathSegment {
971                                     identifier: str_to_ident("d"),
972                                     parameters: ast::PathParameters::none(),
973                                 }
974                             ),
975                         }),
976                         span:sp(7,8)
977                     }))),
978                     span:sp(0,8)
979                    }))
980     }
981
982     #[test] fn parse_stmt_1 () {
983         assert!(string_to_stmt("b;".to_string()) ==
984                    P(Spanned{
985                        node: ast::StmtExpr(P(ast::Expr {
986                            id: ast::DUMMY_NODE_ID,
987                            node: ast::ExprPath(ast::Path {
988                                span:sp(0,1),
989                                global:false,
990                                segments: vec!(
991                                 ast::PathSegment {
992                                     identifier: str_to_ident("b"),
993                                     parameters: ast::PathParameters::none(),
994                                 }
995                                ),
996                             }),
997                            span: sp(0,1)}),
998                                            ast::DUMMY_NODE_ID),
999                        span: sp(0,1)}))
1000
1001     }
1002
1003     fn parser_done(p: Parser){
1004         assert_eq!(p.token.clone(), token::Eof);
1005     }
1006
1007     #[test] fn parse_ident_pat () {
1008         let sess = new_parse_sess();
1009         let mut parser = string_to_parser(&sess, "b".to_string());
1010         assert!(parser.parse_pat()
1011                 == P(ast::Pat{
1012                 id: ast::DUMMY_NODE_ID,
1013                 node: ast::PatIdent(ast::BindByValue(ast::MutImmutable),
1014                                     Spanned{ span:sp(0, 1),
1015                                              node: str_to_ident("b")
1016                     },
1017                                     None),
1018                 span: sp(0,1)}));
1019         parser_done(parser);
1020     }
1021
1022     // check the contents of the tt manually:
1023     #[test] fn parse_fundecl () {
1024         // this test depends on the intern order of "fn" and "int"
1025         assert!(string_to_item("fn a (b : int) { b; }".to_string()) ==
1026                   Some(
1027                       P(ast::Item{ident:str_to_ident("a"),
1028                             attrs:Vec::new(),
1029                             id: ast::DUMMY_NODE_ID,
1030                             node: ast::ItemFn(P(ast::FnDecl {
1031                                 inputs: vec!(ast::Arg{
1032                                     ty: P(ast::Ty{id: ast::DUMMY_NODE_ID,
1033                                                   node: ast::TyPath(ast::Path{
1034                                         span:sp(10,13),
1035                                         global:false,
1036                                         segments: vec!(
1037                                             ast::PathSegment {
1038                                                 identifier:
1039                                                     str_to_ident("int"),
1040                                                 parameters: ast::PathParameters::none(),
1041                                             }
1042                                         ),
1043                                         }, ast::DUMMY_NODE_ID),
1044                                         span:sp(10,13)
1045                                     }),
1046                                     pat: P(ast::Pat {
1047                                         id: ast::DUMMY_NODE_ID,
1048                                         node: ast::PatIdent(
1049                                             ast::BindByValue(ast::MutImmutable),
1050                                                 Spanned{
1051                                                     span: sp(6,7),
1052                                                     node: str_to_ident("b")},
1053                                                 None
1054                                                     ),
1055                                             span: sp(6,7)
1056                                     }),
1057                                         id: ast::DUMMY_NODE_ID
1058                                     }),
1059                                 output: ast::Return(P(ast::Ty{id: ast::DUMMY_NODE_ID,
1060                                                   node: ast::TyTup(vec![]),
1061                                                   span:sp(15,15)})), // not sure
1062                                 variadic: false
1063                             }),
1064                                     ast::Unsafety::Normal,
1065                                     abi::Rust,
1066                                     ast::Generics{ // no idea on either of these:
1067                                         lifetimes: Vec::new(),
1068                                         ty_params: OwnedSlice::empty(),
1069                                         where_clause: ast::WhereClause {
1070                                             id: ast::DUMMY_NODE_ID,
1071                                             predicates: Vec::new(),
1072                                         }
1073                                     },
1074                                     P(ast::Block {
1075                                         view_items: Vec::new(),
1076                                         stmts: vec!(P(Spanned{
1077                                             node: ast::StmtSemi(P(ast::Expr{
1078                                                 id: ast::DUMMY_NODE_ID,
1079                                                 node: ast::ExprPath(
1080                                                       ast::Path{
1081                                                         span:sp(17,18),
1082                                                         global:false,
1083                                                         segments: vec!(
1084                                                             ast::PathSegment {
1085                                                                 identifier:
1086                                                                 str_to_ident(
1087                                                                     "b"),
1088                                                                 parameters:
1089                                                                 ast::PathParameters::none(),
1090                                                             }
1091                                                         ),
1092                                                       }),
1093                                                 span: sp(17,18)}),
1094                                                 ast::DUMMY_NODE_ID),
1095                                             span: sp(17,19)})),
1096                                         expr: None,
1097                                         id: ast::DUMMY_NODE_ID,
1098                                         rules: ast::DefaultBlock, // no idea
1099                                         span: sp(15,21),
1100                                     })),
1101                             vis: ast::Inherited,
1102                             span: sp(0,21)})));
1103     }
1104
1105     #[test] fn parse_use() {
1106         let use_s = "use foo::bar::baz;";
1107         let vitem = string_to_view_item(use_s.to_string());
1108         let vitem_s = view_item_to_string(&vitem);
1109         assert_eq!(vitem_s[], use_s);
1110
1111         let use_s = "use foo::bar as baz;";
1112         let vitem = string_to_view_item(use_s.to_string());
1113         let vitem_s = view_item_to_string(&vitem);
1114         assert_eq!(vitem_s[], use_s);
1115     }
1116
1117     #[test] fn parse_extern_crate() {
1118         let ex_s = "extern crate foo;";
1119         let vitem = string_to_view_item(ex_s.to_string());
1120         let vitem_s = view_item_to_string(&vitem);
1121         assert_eq!(vitem_s[], ex_s);
1122
1123         let ex_s = "extern crate \"foo\" as bar;";
1124         let vitem = string_to_view_item(ex_s.to_string());
1125         let vitem_s = view_item_to_string(&vitem);
1126         assert_eq!(vitem_s[], ex_s);
1127     }
1128
1129     fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
1130         let item = string_to_item(src.to_string()).unwrap();
1131
1132         struct PatIdentVisitor {
1133             spans: Vec<Span>
1134         }
1135         impl<'v> ::visit::Visitor<'v> for PatIdentVisitor {
1136             fn visit_pat(&mut self, p: &'v ast::Pat) {
1137                 match p.node {
1138                     ast::PatIdent(_ , ref spannedident, _) => {
1139                         self.spans.push(spannedident.span.clone());
1140                     }
1141                     _ => {
1142                         ::visit::walk_pat(self, p);
1143                     }
1144                 }
1145             }
1146         }
1147         let mut v = PatIdentVisitor { spans: Vec::new() };
1148         ::visit::walk_item(&mut v, &*item);
1149         return v.spans;
1150     }
1151
1152     #[test] fn span_of_self_arg_pat_idents_are_correct() {
1153
1154         let srcs = ["impl z { fn a (&self, &myarg: int) {} }",
1155                     "impl z { fn a (&mut self, &myarg: int) {} }",
1156                     "impl z { fn a (&'a self, &myarg: int) {} }",
1157                     "impl z { fn a (self, &myarg: int) {} }",
1158                     "impl z { fn a (self: Foo, &myarg: int) {} }",
1159                     ];
1160
1161         for &src in srcs.iter() {
1162             let spans = get_spans_of_pat_idents(src);
1163             let Span{lo:lo,hi:hi,..} = spans[0];
1164             assert!("self" == src[lo.to_uint()..hi.to_uint()],
1165                     "\"{}\" != \"self\". src=\"{}\"",
1166                     src[lo.to_uint()..hi.to_uint()], src)
1167         }
1168     }
1169
1170     #[test] fn parse_exprs () {
1171         // just make sure that they parse....
1172         string_to_expr("3 + 4".to_string());
1173         string_to_expr("a::z.froob(b,&(987+3))".to_string());
1174     }
1175
1176     #[test] fn attrs_fix_bug () {
1177         string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
1178                    -> Result<Box<Writer>, String> {
1179     #[cfg(windows)]
1180     fn wb() -> c_int {
1181       (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1182     }
1183
1184     #[cfg(unix)]
1185     fn wb() -> c_int { O_WRONLY as c_int }
1186
1187     let mut fflags: c_int = wb();
1188 }".to_string());
1189     }
1190
1191     #[test] fn crlf_doc_comments() {
1192         let sess = new_parse_sess();
1193
1194         let name = "<source>".to_string();
1195         let source = "/// doc comment\r\nfn foo() {}".to_string();
1196         let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap();
1197         let doc = first_attr_value_str_by_name(item.attrs.as_slice(), "doc").unwrap();
1198         assert_eq!(doc.get(), "/// doc comment");
1199
1200         let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1201         let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap();
1202         let docs = item.attrs.iter().filter(|a| a.name().get() == "doc")
1203                     .map(|a| a.value_str().unwrap().get().to_string()).collect::<Vec<_>>();
1204         let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1205         assert_eq!(docs[], b);
1206
1207         let source = "/** doc comment\r\n *  with CRLF */\r\nfn foo() {}".to_string();
1208         let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap();
1209         let doc = first_attr_value_str_by_name(item.attrs.as_slice(), "doc").unwrap();
1210         assert_eq!(doc.get(), "/** doc comment\n *  with CRLF */");
1211     }
1212 }