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.
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.
11 //! The main parser interface
14 use codemap::{self, Span, CodeMap, FileMap};
15 use diagnostic::{SpanHandler, Handler, Auto, FatalError};
16 use parse::parser::Parser;
17 use parse::token::InternedString;
21 use std::cell::RefCell;
24 use std::path::{Path, PathBuf};
28 pub type PResult<T> = Result<T, FatalError>;
41 /// Info about a parsing session.
42 pub struct ParseSess {
43 pub span_diagnostic: SpanHandler, // better be the same as the one in the reader!
44 /// Used to determine and report recursive mod inclusions
45 included_mod_stack: RefCell<Vec<PathBuf>>,
49 pub fn new() -> ParseSess {
50 let handler = SpanHandler::new(Handler::new(Auto, None, true), CodeMap::new());
51 ParseSess::with_span_handler(handler)
54 pub fn with_span_handler(sh: SpanHandler) -> ParseSess {
57 included_mod_stack: RefCell::new(vec![])
61 pub fn codemap(&self) -> &CodeMap {
62 &self.span_diagnostic.cm
66 // a bunch of utility functions of the form parse_<thing>_from_<source>
67 // where <thing> includes crate, expr, item, stmt, tts, and one that
68 // uses a HOF to parse anything, and <source> includes file and
71 pub fn parse_crate_from_file(
73 cfg: ast::CrateConfig,
76 panictry!(new_parser_from_file(sess, cfg, input).parse_crate_mod())
77 // why is there no p.abort_if_errors here?
80 pub fn parse_crate_attrs_from_file(
82 cfg: ast::CrateConfig,
84 ) -> Vec<ast::Attribute> {
85 // FIXME: maybe_aborted?
86 panictry!(new_parser_from_file(sess, cfg, input).parse_inner_attributes())
89 pub fn parse_crate_from_source_str(name: String,
91 cfg: ast::CrateConfig,
94 let mut p = new_parser_from_source_str(sess,
98 maybe_aborted(panictry!(p.parse_crate_mod()),p)
101 pub fn parse_crate_attrs_from_source_str(name: String,
103 cfg: ast::CrateConfig,
105 -> Vec<ast::Attribute> {
106 let mut p = new_parser_from_source_str(sess,
110 maybe_aborted(panictry!(p.parse_inner_attributes()), p)
113 pub fn parse_expr_from_source_str(name: String,
115 cfg: ast::CrateConfig,
118 let mut p = new_parser_from_source_str(sess, cfg, name, source);
119 maybe_aborted(panictry!(p.parse_expr()), p)
122 pub fn parse_item_from_source_str(name: String,
124 cfg: ast::CrateConfig,
126 -> Option<P<ast::Item>> {
127 let mut p = new_parser_from_source_str(sess, cfg, name, source);
128 maybe_aborted(panictry!(p.parse_item()), p)
131 pub fn parse_meta_from_source_str(name: String,
133 cfg: ast::CrateConfig,
135 -> P<ast::MetaItem> {
136 let mut p = new_parser_from_source_str(sess, cfg, name, source);
137 maybe_aborted(panictry!(p.parse_meta_item()), p)
140 pub fn parse_stmt_from_source_str(name: String,
142 cfg: ast::CrateConfig,
144 -> Option<P<ast::Stmt>> {
145 let mut p = new_parser_from_source_str(
151 maybe_aborted(panictry!(p.parse_stmt()), p)
154 // Warning: This parses with quote_depth > 0, which is not the default.
155 pub fn parse_tts_from_source_str(name: String,
157 cfg: ast::CrateConfig,
159 -> Vec<ast::TokenTree> {
160 let mut p = new_parser_from_source_str(
167 // right now this is re-creating the token trees from ... token trees.
168 maybe_aborted(panictry!(p.parse_all_token_trees()),p)
171 // Create a new parser from a source string
172 pub fn new_parser_from_source_str<'a>(sess: &'a ParseSess,
173 cfg: ast::CrateConfig,
177 filemap_to_parser(sess, sess.codemap().new_filemap(name, source), cfg)
180 /// Create a new parser, handling errors as appropriate
181 /// if the file doesn't exist
182 pub fn new_parser_from_file<'a>(sess: &'a ParseSess,
183 cfg: ast::CrateConfig,
184 path: &Path) -> Parser<'a> {
185 filemap_to_parser(sess, file_to_filemap(sess, path, None), cfg)
188 /// Given a session, a crate config, a path, and a span, add
189 /// the file at the given path to the codemap, and return a parser.
190 /// On an error, use the given span as the source of the problem.
191 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
192 cfg: ast::CrateConfig,
194 owns_directory: bool,
195 module_name: Option<String>,
196 sp: Span) -> Parser<'a> {
197 let mut p = filemap_to_parser(sess, file_to_filemap(sess, path, Some(sp)), cfg);
198 p.owns_directory = owns_directory;
199 p.root_module_name = module_name;
203 /// Given a filemap and config, return a parser
204 pub fn filemap_to_parser<'a>(sess: &'a ParseSess,
205 filemap: Rc<FileMap>,
206 cfg: ast::CrateConfig) -> Parser<'a> {
207 let end_pos = filemap.end_pos;
208 let mut parser = tts_to_parser(sess, filemap_to_tts(sess, filemap), cfg);
210 if parser.token == token::Eof && parser.span == codemap::DUMMY_SP {
211 parser.span = codemap::mk_sp(end_pos, end_pos);
217 // must preserve old name for now, because quote! from the *existing*
218 // compiler expands into it
219 pub fn new_parser_from_tts<'a>(sess: &'a ParseSess,
220 cfg: ast::CrateConfig,
221 tts: Vec<ast::TokenTree>) -> Parser<'a> {
222 tts_to_parser(sess, tts, cfg)
228 /// Given a session and a path and an optional span (for error reporting),
229 /// add the path to the session's codemap and return the new filemap.
230 fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
232 match sess.codemap().load_file(path) {
233 Ok(filemap) => filemap,
235 let msg = format!("couldn't read {:?}: {}", path.display(), e);
237 Some(sp) => panic!(sess.span_diagnostic.span_fatal(sp, &msg)),
238 None => panic!(sess.span_diagnostic.handler().fatal(&msg))
244 /// Given a filemap, produce a sequence of token-trees
245 pub fn filemap_to_tts(sess: &ParseSess, filemap: Rc<FileMap>)
246 -> Vec<ast::TokenTree> {
247 // it appears to me that the cfg doesn't matter here... indeed,
248 // parsing tt's probably shouldn't require a parser at all.
249 let cfg = Vec::new();
250 let srdr = lexer::StringReader::new(&sess.span_diagnostic, filemap);
251 let mut p1 = Parser::new(sess, cfg, Box::new(srdr));
252 panictry!(p1.parse_all_token_trees())
255 /// Given tts and cfg, produce a parser
256 pub fn tts_to_parser<'a>(sess: &'a ParseSess,
257 tts: Vec<ast::TokenTree>,
258 cfg: ast::CrateConfig) -> Parser<'a> {
259 let trdr = lexer::new_tt_reader(&sess.span_diagnostic, None, None, tts);
260 let mut p = Parser::new(sess, cfg, Box::new(trdr));
261 panictry!(p.check_unknown_macro_variable());
265 /// Abort if necessary
266 pub fn maybe_aborted<T>(result: T, p: Parser) -> T {
271 /// Parse a string representing a character literal into its final form.
272 /// Rather than just accepting/rejecting a given literal, unescapes it as
273 /// well. Can take any slice prefixed by a character escape. Returns the
274 /// character and the number of characters consumed.
275 pub fn char_lit(lit: &str) -> (char, isize) {
278 let mut chars = lit.chars();
279 let c = match (chars.next(), chars.next()) {
280 (Some(c), None) if c != '\\' => return (c, 1),
281 (Some('\\'), Some(c)) => match c {
291 _ => panic!("lexer accepted invalid char escape `{}`", lit)
295 Some(x) => return (x, 2),
299 let msg = format!("lexer should have rejected a bad character escape {}", lit);
302 fn esc(len: usize, lit: &str) -> Option<(char, isize)> {
303 u32::from_str_radix(&lit[2..len], 16).ok()
304 .and_then(char::from_u32)
305 .map(|x| (x, len as isize))
308 let unicode_escape = || -> Option<(char, isize)> {
309 if lit.as_bytes()[2] == b'{' {
310 let idx = lit.find('}').expect(msg2);
311 let subslice = &lit[3..idx];
312 u32::from_str_radix(subslice, 16).ok()
313 .and_then(char::from_u32)
314 .map(|x| (x, subslice.chars().count() as isize + 4))
321 return match lit.as_bytes()[1] as char {
322 'x' | 'X' => esc(4, lit),
323 'u' => unicode_escape(),
329 /// Parse a string representing a string literal into its final form. Does
331 pub fn str_lit(lit: &str) -> String {
332 debug!("parse_str_lit: given {}", lit.escape_default());
333 let mut res = String::with_capacity(lit.len());
335 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
336 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
338 /// Eat everything up to a non-whitespace
339 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
341 match it.peek().map(|x| x.1) {
342 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
350 let mut chars = lit.char_indices().peekable();
356 let ch = chars.peek().unwrap_or_else(|| {
357 panic!("{}", error(i))
362 } else if ch == '\r' {
364 let ch = chars.peek().unwrap_or_else(|| {
365 panic!("{}", error(i))
369 panic!("lexer accepted bare CR");
373 // otherwise, a normal escape
374 let (c, n) = char_lit(&lit[i..]);
375 for _ in 0..n - 1 { // we don't need to move past the first \
382 let ch = chars.peek().unwrap_or_else(|| {
383 panic!("{}", error(i))
387 panic!("lexer accepted bare CR");
399 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
400 debug!("parse_str_lit: returning {}", res);
404 /// Parse a string representing a raw string literal into its final form. The
405 /// only operation this does is convert embedded CRLF into a single LF.
406 pub fn raw_str_lit(lit: &str) -> String {
407 debug!("raw_str_lit: given {}", lit.escape_default());
408 let mut res = String::with_capacity(lit.len());
410 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
411 let mut chars = lit.chars().peekable();
416 if *chars.peek().unwrap() != '\n' {
417 panic!("lexer accepted bare CR");
433 // check if `s` looks like i32 or u1234 etc.
434 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
436 first_chars.contains(&char_at(s, 0)) &&
437 s[1..].chars().all(|c| '0' <= c && c <= '9')
440 fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>,
441 sd: &SpanHandler, sp: Span) -> ast::Lit_ {
442 debug!("filtered_float_lit: {}, {:?}", data, suffix);
443 match suffix.as_ref().map(|s| &**s) {
444 Some("f32") => ast::LitFloat(data, ast::TyF32),
445 Some("f64") => ast::LitFloat(data, ast::TyF64),
447 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
448 // if it looks like a width, lets try to be helpful.
449 sd.span_err(sp, &format!("invalid width `{}` for float literal", &suf[1..]));
450 sd.fileline_help(sp, "valid widths are 32 and 64");
452 sd.span_err(sp, &format!("invalid suffix `{}` for float literal", suf));
453 sd.fileline_help(sp, "valid suffixes are `f32` and `f64`");
456 ast::LitFloatUnsuffixed(data)
458 None => ast::LitFloatUnsuffixed(data)
461 pub fn float_lit(s: &str, suffix: Option<InternedString>,
462 sd: &SpanHandler, sp: Span) -> ast::Lit_ {
463 debug!("float_lit: {:?}, {:?}", s, suffix);
464 // FIXME #2252: bounds checking float literals is deferred until trans
465 let s = s.chars().filter(|&c| c != '_').collect::<String>();
466 let data = token::intern_and_get_ident(&s);
467 filtered_float_lit(data, suffix.as_ref().map(|s| &**s), sd, sp)
470 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
471 pub fn byte_lit(lit: &str) -> (u8, usize) {
472 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
475 (lit.as_bytes()[0], 1)
477 assert!(lit.as_bytes()[0] == b'\\', err(0));
478 let b = match lit.as_bytes()[1] {
487 match u64::from_str_radix(&lit[2..4], 16).ok() {
494 None => panic!(err(3))
502 pub fn byte_str_lit(lit: &str) -> Rc<Vec<u8>> {
503 let mut res = Vec::with_capacity(lit.len());
505 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
506 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
508 /// Eat everything up to a non-whitespace
509 fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
511 match it.peek().map(|x| x.1) {
512 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
520 // byte string literals *must* be ASCII, but the escapes don't have to be
521 let mut chars = lit.bytes().enumerate().peekable();
524 Some((i, b'\\')) => {
526 match chars.peek().expect(&em).1 {
527 b'\n' => eat(&mut chars),
530 if chars.peek().expect(&em).1 != b'\n' {
531 panic!("lexer accepted bare CR");
536 // otherwise, a normal escape
537 let (c, n) = byte_lit(&lit[i..]);
538 // we don't need to move past the first \
546 Some((i, b'\r')) => {
548 if chars.peek().expect(&em).1 != b'\n' {
549 panic!("lexer accepted bare CR");
554 Some((_, c)) => res.push(c),
562 pub fn integer_lit(s: &str,
563 suffix: Option<InternedString>,
567 // s can only be ascii, byte indexing is fine
569 let s2 = s.chars().filter(|&c| c != '_').collect::<String>();
572 debug!("integer_lit: {}, {:?}", s, suffix);
576 let mut ty = ast::UnsuffixedIntLit(ast::Plus);
578 if char_at(s, 0) == '0' && s.len() > 1 {
579 match char_at(s, 1) {
587 // 1f64 and 2f32 etc. are valid float literals.
588 if let Some(ref suf) = suffix {
589 if looks_like_width_suffix(&['f'], suf) {
591 16 => sd.span_err(sp, "hexadecimal float literal is not supported"),
592 8 => sd.span_err(sp, "octal float literal is not supported"),
593 2 => sd.span_err(sp, "binary float literal is not supported"),
596 let ident = token::intern_and_get_ident(&*s);
597 return filtered_float_lit(ident, Some(&**suf), sd, sp)
605 if let Some(ref suf) = suffix {
606 if suf.is_empty() { sd.span_bug(sp, "found empty literal suffix in Some")}
608 "isize" => ast::SignedIntLit(ast::TyIs, ast::Plus),
609 "i8" => ast::SignedIntLit(ast::TyI8, ast::Plus),
610 "i16" => ast::SignedIntLit(ast::TyI16, ast::Plus),
611 "i32" => ast::SignedIntLit(ast::TyI32, ast::Plus),
612 "i64" => ast::SignedIntLit(ast::TyI64, ast::Plus),
613 "usize" => ast::UnsignedIntLit(ast::TyUs),
614 "u8" => ast::UnsignedIntLit(ast::TyU8),
615 "u16" => ast::UnsignedIntLit(ast::TyU16),
616 "u32" => ast::UnsignedIntLit(ast::TyU32),
617 "u64" => ast::UnsignedIntLit(ast::TyU64),
619 // i<digits> and u<digits> look like widths, so lets
620 // give an error message along those lines
621 if looks_like_width_suffix(&['i', 'u'], suf) {
622 sd.span_err(sp, &format!("invalid width `{}` for integer literal",
624 sd.fileline_help(sp, "valid widths are 8, 16, 32 and 64");
626 sd.span_err(sp, &format!("invalid suffix `{}` for numeric literal", suf));
627 sd.fileline_help(sp, "the suffix must be one of the integral types \
628 (`u32`, `isize`, etc)");
636 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
637 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
639 let res = match u64::from_str_radix(s, base).ok() {
642 // small bases are lexed as if they were base 10, e.g, the string
643 // might be `0b10201`. This will cause the conversion above to fail,
644 // but these cases have errors in the lexer: we don't want to emit
645 // two errors, and we especially don't want to emit this error since
646 // it isn't necessarily true.
647 let already_errored = base < 10 &&
648 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
650 if !already_errored {
651 sd.span_err(sp, "int literal is too large");
658 let sign = ast::Sign::new(res);
660 ast::SignedIntLit(t, _) => ast::LitInt(res, ast::SignedIntLit(t, sign)),
661 ast::UnsuffixedIntLit(_) => ast::LitInt(res, ast::UnsuffixedIntLit(sign)),
662 us@ast::UnsignedIntLit(_) => ast::LitInt(res, us)
670 use codemap::{Span, BytePos, Pos, Spanned, NO_EXPANSION};
671 use ast::{self, TokenTree};
673 use attr::{first_attr_value_str_by_name, AttrMetaMethods};
675 use parse::parser::Parser;
676 use parse::token::{str_to_ident};
677 use print::pprust::item_to_string;
679 use util::parser_testing::{string_to_tts, string_to_parser};
680 use util::parser_testing::{string_to_expr, string_to_item, string_to_stmt};
682 // produce a codemap::span
683 fn sp(a: u32, b: u32) -> Span {
684 Span {lo: BytePos(a), hi: BytePos(b), expn_id: NO_EXPANSION}
687 #[test] fn path_exprs_1() {
688 assert!(string_to_expr("a".to_string()) ==
690 id: ast::DUMMY_NODE_ID,
691 node: ast::ExprPath(None, ast::Path {
696 identifier: str_to_ident("a"),
697 parameters: ast::PathParameters::none(),
706 #[test] fn path_exprs_2 () {
707 assert!(string_to_expr("::a::b".to_string()) ==
709 id: ast::DUMMY_NODE_ID,
710 node: ast::ExprPath(None, ast::Path {
715 identifier: str_to_ident("a"),
716 parameters: ast::PathParameters::none(),
719 identifier: str_to_ident("b"),
720 parameters: ast::PathParameters::none(),
730 #[test] fn bad_path_expr_1() {
731 string_to_expr("::abc::def::return".to_string());
734 // check the token-tree-ization of macros
736 fn string_to_tts_macro () {
737 let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_string());
738 let tts: &[ast::TokenTree] = &tts[..];
740 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
743 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, token::Plain))),
744 Some(&TokenTree::Token(_, token::Not)),
745 Some(&TokenTree::Token(_, token::Ident(name_zip, token::Plain))),
746 Some(&TokenTree::Delimited(_, ref macro_delimed)),
748 if name_macro_rules.name.as_str() == "macro_rules"
749 && name_zip.name.as_str() == "zip" => {
750 let tts = ¯o_delimed.tts[..];
751 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
754 Some(&TokenTree::Delimited(_, ref first_delimed)),
755 Some(&TokenTree::Token(_, token::FatArrow)),
756 Some(&TokenTree::Delimited(_, ref second_delimed)),
758 if macro_delimed.delim == token::Paren => {
759 let tts = &first_delimed.tts[..];
760 match (tts.len(), tts.get(0), tts.get(1)) {
763 Some(&TokenTree::Token(_, token::Dollar)),
764 Some(&TokenTree::Token(_, token::Ident(ident, token::Plain))),
766 if first_delimed.delim == token::Paren
767 && ident.name.as_str() == "a" => {},
768 _ => panic!("value 3: {:?}", **first_delimed),
770 let tts = &second_delimed.tts[..];
771 match (tts.len(), tts.get(0), tts.get(1)) {
774 Some(&TokenTree::Token(_, token::Dollar)),
775 Some(&TokenTree::Token(_, token::Ident(ident, token::Plain))),
777 if second_delimed.delim == token::Paren
778 && ident.name.as_str() == "a" => {},
779 _ => panic!("value 4: {:?}", **second_delimed),
782 _ => panic!("value 2: {:?}", **macro_delimed),
785 _ => panic!("value: {:?}",tts),
790 fn string_to_tts_1() {
791 let tts = string_to_tts("fn a (b : i32) { b; }".to_string());
794 TokenTree::Token(sp(0, 2),
795 token::Ident(str_to_ident("fn"),
796 token::IdentStyle::Plain)),
797 TokenTree::Token(sp(3, 4),
798 token::Ident(str_to_ident("a"),
799 token::IdentStyle::Plain)),
800 TokenTree::Delimited(
802 Rc::new(ast::Delimited {
803 delim: token::DelimToken::Paren,
806 TokenTree::Token(sp(6, 7),
807 token::Ident(str_to_ident("b"),
808 token::IdentStyle::Plain)),
809 TokenTree::Token(sp(8, 9),
811 TokenTree::Token(sp(10, 13),
812 token::Ident(str_to_ident("i32"),
813 token::IdentStyle::Plain)),
815 close_span: sp(13, 14),
817 TokenTree::Delimited(
819 Rc::new(ast::Delimited {
820 delim: token::DelimToken::Brace,
821 open_span: sp(15, 16),
823 TokenTree::Token(sp(17, 18),
824 token::Ident(str_to_ident("b"),
825 token::IdentStyle::Plain)),
826 TokenTree::Token(sp(18, 19),
829 close_span: sp(20, 21),
833 assert_eq!(tts, expected);
836 #[test] fn ret_expr() {
837 assert!(string_to_expr("return d".to_string()) ==
839 id: ast::DUMMY_NODE_ID,
840 node:ast::ExprRet(Some(P(ast::Expr{
841 id: ast::DUMMY_NODE_ID,
842 node:ast::ExprPath(None, ast::Path{
847 identifier: str_to_ident("d"),
848 parameters: ast::PathParameters::none(),
860 #[test] fn parse_stmt_1 () {
861 assert!(string_to_stmt("b;".to_string()) ==
863 node: ast::StmtExpr(P(ast::Expr {
864 id: ast::DUMMY_NODE_ID,
865 node: ast::ExprPath(None, ast::Path {
870 identifier: str_to_ident("b"),
871 parameters: ast::PathParameters::none(),
882 fn parser_done(p: Parser){
883 assert_eq!(p.token.clone(), token::Eof);
886 #[test] fn parse_ident_pat () {
887 let sess = ParseSess::new();
888 let mut parser = string_to_parser(&sess, "b".to_string());
889 assert!(panictry!(parser.parse_pat())
891 id: ast::DUMMY_NODE_ID,
892 node: ast::PatIdent(ast::BindByValue(ast::MutImmutable),
893 Spanned{ span:sp(0, 1),
894 node: str_to_ident("b")
901 // check the contents of the tt manually:
902 #[test] fn parse_fundecl () {
903 // this test depends on the intern order of "fn" and "i32"
904 assert_eq!(string_to_item("fn a (b : i32) { b; }".to_string()),
906 P(ast::Item{ident:str_to_ident("a"),
908 id: ast::DUMMY_NODE_ID,
909 node: ast::ItemFn(P(ast::FnDecl {
910 inputs: vec!(ast::Arg{
911 ty: P(ast::Ty{id: ast::DUMMY_NODE_ID,
912 node: ast::TyPath(None, ast::Path{
919 parameters: ast::PathParameters::none(),
926 id: ast::DUMMY_NODE_ID,
928 ast::BindByValue(ast::MutImmutable),
931 node: str_to_ident("b")},
936 id: ast::DUMMY_NODE_ID
938 output: ast::DefaultReturn(sp(15, 15)),
941 ast::Unsafety::Normal,
942 ast::Constness::NotConst,
944 ast::Generics{ // no idea on either of these:
945 lifetimes: Vec::new(),
946 ty_params: P::empty(),
947 where_clause: ast::WhereClause {
948 id: ast::DUMMY_NODE_ID,
949 predicates: Vec::new(),
953 stmts: vec!(P(Spanned{
954 node: ast::StmtSemi(P(ast::Expr{
955 id: ast::DUMMY_NODE_ID,
956 node: ast::ExprPath(None,
966 ast::PathParameters::none(),
975 id: ast::DUMMY_NODE_ID,
976 rules: ast::DefaultBlock, // no idea
983 #[test] fn parse_use() {
984 let use_s = "use foo::bar::baz;";
985 let vitem = string_to_item(use_s.to_string()).unwrap();
986 let vitem_s = item_to_string(&*vitem);
987 assert_eq!(&vitem_s[..], use_s);
989 let use_s = "use foo::bar as baz;";
990 let vitem = string_to_item(use_s.to_string()).unwrap();
991 let vitem_s = item_to_string(&*vitem);
992 assert_eq!(&vitem_s[..], use_s);
995 #[test] fn parse_extern_crate() {
996 let ex_s = "extern crate foo;";
997 let vitem = string_to_item(ex_s.to_string()).unwrap();
998 let vitem_s = item_to_string(&*vitem);
999 assert_eq!(&vitem_s[..], ex_s);
1001 let ex_s = "extern crate foo as bar;";
1002 let vitem = string_to_item(ex_s.to_string()).unwrap();
1003 let vitem_s = item_to_string(&*vitem);
1004 assert_eq!(&vitem_s[..], ex_s);
1007 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
1008 let item = string_to_item(src.to_string()).unwrap();
1010 struct PatIdentVisitor {
1013 impl<'v> ::visit::Visitor<'v> for PatIdentVisitor {
1014 fn visit_pat(&mut self, p: &'v ast::Pat) {
1016 ast::PatIdent(_ , ref spannedident, _) => {
1017 self.spans.push(spannedident.span.clone());
1020 ::visit::walk_pat(self, p);
1025 let mut v = PatIdentVisitor { spans: Vec::new() };
1026 ::visit::walk_item(&mut v, &*item);
1030 #[test] fn span_of_self_arg_pat_idents_are_correct() {
1032 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
1033 "impl z { fn a (&mut self, &myarg: i32) {} }",
1034 "impl z { fn a (&'a self, &myarg: i32) {} }",
1035 "impl z { fn a (self, &myarg: i32) {} }",
1036 "impl z { fn a (self: Foo, &myarg: i32) {} }",
1040 let spans = get_spans_of_pat_idents(src);
1041 let Span{ lo, hi, .. } = spans[0];
1042 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
1043 "\"{}\" != \"self\". src=\"{}\"",
1044 &src[lo.to_usize()..hi.to_usize()], src)
1048 #[test] fn parse_exprs () {
1049 // just make sure that they parse....
1050 string_to_expr("3 + 4".to_string());
1051 string_to_expr("a::z.froob(b,&(987+3))".to_string());
1054 #[test] fn attrs_fix_bug () {
1055 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
1056 -> Result<Box<Writer>, String> {
1059 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1063 fn wb() -> c_int { O_WRONLY as c_int }
1065 let mut fflags: c_int = wb();
1069 #[test] fn crlf_doc_comments() {
1070 let sess = ParseSess::new();
1072 let name = "<source>".to_string();
1073 let source = "/// doc comment\r\nfn foo() {}".to_string();
1074 let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap();
1075 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1076 assert_eq!(&doc[..], "/// doc comment");
1078 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1079 let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap();
1080 let docs = item.attrs.iter().filter(|a| &*a.name() == "doc")
1081 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1082 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1083 assert_eq!(&docs[..], b);
1085 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1086 let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap();
1087 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1088 assert_eq!(&doc[..], "/** doc comment\n * with CRLF */");
1093 let sess = ParseSess::new();
1094 let expr = parse::parse_expr_from_source_str("foo".to_string(),
1095 "foo!( fn main() { body } )".to_string(), vec![], &sess);
1097 let tts = match expr.node {
1098 ast::ExprMac(ref mac) => mac.node.tts.clone(),
1099 _ => panic!("not a macro"),
1102 let span = tts.iter().rev().next().unwrap().get_span();
1104 match sess.codemap().span_to_snippet(span) {
1105 Ok(s) => assert_eq!(&s[..], "{ body }"),
1106 Err(_) => panic!("could not get snippet"),