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