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
15 use syntax_pos::{self, Span, FileMap};
16 use errors::{Handler, ColorConfig, DiagnosticBuilder};
17 use parse::parser::Parser;
18 use parse::token::InternedString;
23 use std::cell::RefCell;
25 use std::path::{Path, PathBuf};
29 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
42 /// Info about a parsing session.
43 pub struct ParseSess {
44 pub span_diagnostic: Handler, // better be the same as the one in the reader!
45 /// Used to determine and report recursive mod inclusions
46 included_mod_stack: RefCell<Vec<PathBuf>>,
47 code_map: Rc<CodeMap>,
51 pub fn new() -> ParseSess {
52 let cm = Rc::new(CodeMap::new());
53 let handler = Handler::with_tty_emitter(ColorConfig::Auto, None, true, false, cm.clone());
54 ParseSess::with_span_handler(handler, cm)
57 pub fn with_span_handler(handler: Handler, code_map: Rc<CodeMap>) -> ParseSess {
59 span_diagnostic: handler,
60 included_mod_stack: RefCell::new(vec![]),
65 pub fn codemap(&self) -> &CodeMap {
70 // a bunch of utility functions of the form parse_<thing>_from_<source>
71 // where <thing> includes crate, expr, item, stmt, tts, and one that
72 // uses a HOF to parse anything, and <source> includes file and
75 pub fn parse_crate_from_file<'a>(input: &Path,
76 cfg: ast::CrateConfig,
78 -> PResult<'a, ast::Crate> {
79 let mut parser = new_parser_from_file(sess, cfg, input);
80 parser.parse_crate_mod()
83 pub fn parse_crate_attrs_from_file<'a>(input: &Path,
84 cfg: ast::CrateConfig,
86 -> PResult<'a, Vec<ast::Attribute>> {
87 let mut parser = new_parser_from_file(sess, cfg, input);
88 parser.parse_inner_attributes()
91 pub fn parse_crate_from_source_str<'a>(name: String,
93 cfg: ast::CrateConfig,
95 -> PResult<'a, ast::Crate> {
96 let mut p = new_parser_from_source_str(sess,
103 pub fn parse_crate_attrs_from_source_str<'a>(name: String,
105 cfg: ast::CrateConfig,
107 -> PResult<'a, Vec<ast::Attribute>> {
108 let mut p = new_parser_from_source_str(sess,
112 p.parse_inner_attributes()
115 pub fn parse_expr_from_source_str<'a>(name: String,
117 cfg: ast::CrateConfig,
119 -> PResult<'a, P<ast::Expr>> {
120 let mut p = new_parser_from_source_str(sess, cfg, name, source);
126 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and`Err`
127 /// when a syntax error occurred.
128 pub fn parse_item_from_source_str<'a>(name: String,
130 cfg: ast::CrateConfig,
132 -> PResult<'a, Option<P<ast::Item>>> {
133 let mut p = new_parser_from_source_str(sess, cfg, name, source);
137 pub fn parse_meta_from_source_str<'a>(name: String,
139 cfg: ast::CrateConfig,
141 -> PResult<'a, P<ast::MetaItem>> {
142 let mut p = new_parser_from_source_str(sess, cfg, name, source);
146 pub fn parse_stmt_from_source_str<'a>(name: String,
148 cfg: ast::CrateConfig,
150 -> PResult<'a, Option<ast::Stmt>> {
151 let mut p = new_parser_from_source_str(
160 // Warning: This parses with quote_depth > 0, which is not the default.
161 pub fn parse_tts_from_source_str<'a>(name: String,
163 cfg: ast::CrateConfig,
165 -> PResult<'a, Vec<tokenstream::TokenTree>> {
166 let mut p = new_parser_from_source_str(
173 // right now this is re-creating the token trees from ... token trees.
174 p.parse_all_token_trees()
177 // Create a new parser from a source string
178 pub fn new_parser_from_source_str<'a>(sess: &'a ParseSess,
179 cfg: ast::CrateConfig,
183 filemap_to_parser(sess, sess.codemap().new_filemap(name, None, source), cfg)
186 /// Create a new parser, handling errors as appropriate
187 /// if the file doesn't exist
188 pub fn new_parser_from_file<'a>(sess: &'a ParseSess,
189 cfg: ast::CrateConfig,
190 path: &Path) -> Parser<'a> {
191 filemap_to_parser(sess, file_to_filemap(sess, path, None), cfg)
194 /// Given a session, a crate config, a path, and a span, add
195 /// the file at the given path to the codemap, and return a parser.
196 /// On an error, use the given span as the source of the problem.
197 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
198 cfg: ast::CrateConfig,
200 owns_directory: bool,
201 module_name: Option<String>,
202 sp: Span) -> Parser<'a> {
203 let mut p = filemap_to_parser(sess, file_to_filemap(sess, path, Some(sp)), cfg);
204 p.owns_directory = owns_directory;
205 p.root_module_name = module_name;
209 /// Given a filemap and config, return a parser
210 pub fn filemap_to_parser<'a>(sess: &'a ParseSess,
211 filemap: Rc<FileMap>,
212 cfg: ast::CrateConfig) -> Parser<'a> {
213 let end_pos = filemap.end_pos;
214 let mut parser = tts_to_parser(sess, filemap_to_tts(sess, filemap), cfg);
216 if parser.token == token::Eof && parser.span == syntax_pos::DUMMY_SP {
217 parser.span = syntax_pos::mk_sp(end_pos, end_pos);
223 // must preserve old name for now, because quote! from the *existing*
224 // compiler expands into it
225 pub fn new_parser_from_tts<'a>(sess: &'a ParseSess,
226 cfg: ast::CrateConfig,
227 tts: Vec<tokenstream::TokenTree>) -> Parser<'a> {
228 tts_to_parser(sess, tts, cfg)
234 /// Given a session and a path and an optional span (for error reporting),
235 /// add the path to the session's codemap and return the new filemap.
236 fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
238 match sess.codemap().load_file(path) {
239 Ok(filemap) => filemap,
241 let msg = format!("couldn't read {:?}: {}", path.display(), e);
243 Some(sp) => panic!(sess.span_diagnostic.span_fatal(sp, &msg)),
244 None => panic!(sess.span_diagnostic.fatal(&msg))
250 /// Given a filemap, produce a sequence of token-trees
251 pub fn filemap_to_tts(sess: &ParseSess, filemap: Rc<FileMap>)
252 -> Vec<tokenstream::TokenTree> {
253 // it appears to me that the cfg doesn't matter here... indeed,
254 // parsing tt's probably shouldn't require a parser at all.
255 let cfg = Vec::new();
256 let srdr = lexer::StringReader::new(&sess.span_diagnostic, filemap);
257 let mut p1 = Parser::new(sess, cfg, Box::new(srdr));
258 panictry!(p1.parse_all_token_trees())
261 /// Given tts and cfg, produce a parser
262 pub fn tts_to_parser<'a>(sess: &'a ParseSess,
263 tts: Vec<tokenstream::TokenTree>,
264 cfg: ast::CrateConfig) -> Parser<'a> {
265 let trdr = lexer::new_tt_reader(&sess.span_diagnostic, None, None, tts);
266 let mut p = Parser::new(sess, cfg, Box::new(trdr));
267 p.check_unknown_macro_variable();
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: &Handler, sp: Span) -> ast::LitKind {
442 debug!("filtered_float_lit: {}, {:?}", data, suffix);
443 match suffix.as_ref().map(|s| &**s) {
444 Some("f32") => ast::LitKind::Float(data, ast::FloatTy::F32),
445 Some("f64") => ast::LitKind::Float(data, ast::FloatTy::F64),
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.struct_span_err(sp, &format!("invalid width `{}` for float literal", &suf[1..]))
450 .help("valid widths are 32 and 64")
453 sd.struct_span_err(sp, &format!("invalid suffix `{}` for float literal", suf))
454 .help("valid suffixes are `f32` and `f64`")
458 ast::LitKind::FloatUnsuffixed(data)
460 None => ast::LitKind::FloatUnsuffixed(data)
463 pub fn float_lit(s: &str, suffix: Option<InternedString>,
464 sd: &Handler, sp: Span) -> ast::LitKind {
465 debug!("float_lit: {:?}, {:?}", s, suffix);
466 // FIXME #2252: bounds checking float literals is deferred until trans
467 let s = s.chars().filter(|&c| c != '_').collect::<String>();
468 let data = token::intern_and_get_ident(&s);
469 filtered_float_lit(data, suffix.as_ref().map(|s| &**s), sd, sp)
472 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
473 pub fn byte_lit(lit: &str) -> (u8, usize) {
474 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
477 (lit.as_bytes()[0], 1)
479 assert!(lit.as_bytes()[0] == b'\\', err(0));
480 let b = match lit.as_bytes()[1] {
489 match u64::from_str_radix(&lit[2..4], 16).ok() {
496 None => panic!(err(3))
504 pub fn byte_str_lit(lit: &str) -> Rc<Vec<u8>> {
505 let mut res = Vec::with_capacity(lit.len());
507 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
508 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
510 /// Eat everything up to a non-whitespace
511 fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
513 match it.peek().map(|x| x.1) {
514 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
522 // byte string literals *must* be ASCII, but the escapes don't have to be
523 let mut chars = lit.bytes().enumerate().peekable();
526 Some((i, b'\\')) => {
528 match chars.peek().expect(&em).1 {
529 b'\n' => eat(&mut chars),
532 if chars.peek().expect(&em).1 != b'\n' {
533 panic!("lexer accepted bare CR");
538 // otherwise, a normal escape
539 let (c, n) = byte_lit(&lit[i..]);
540 // we don't need to move past the first \
548 Some((i, b'\r')) => {
550 if chars.peek().expect(&em).1 != b'\n' {
551 panic!("lexer accepted bare CR");
556 Some((_, c)) => res.push(c),
564 pub fn integer_lit(s: &str,
565 suffix: Option<InternedString>,
569 // s can only be ascii, byte indexing is fine
571 let s2 = s.chars().filter(|&c| c != '_').collect::<String>();
574 debug!("integer_lit: {}, {:?}", s, suffix);
578 let mut ty = ast::LitIntType::Unsuffixed;
580 if char_at(s, 0) == '0' && s.len() > 1 {
581 match char_at(s, 1) {
589 // 1f64 and 2f32 etc. are valid float literals.
590 if let Some(ref suf) = suffix {
591 if looks_like_width_suffix(&['f'], suf) {
593 16 => sd.span_err(sp, "hexadecimal float literal is not supported"),
594 8 => sd.span_err(sp, "octal float literal is not supported"),
595 2 => sd.span_err(sp, "binary float literal is not supported"),
598 let ident = token::intern_and_get_ident(&s);
599 return filtered_float_lit(ident, Some(&suf), sd, sp)
607 if let Some(ref suf) = suffix {
608 if suf.is_empty() { sd.span_bug(sp, "found empty literal suffix in Some")}
610 "isize" => ast::LitIntType::Signed(ast::IntTy::Is),
611 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
612 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
613 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
614 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
615 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Us),
616 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
617 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
618 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
619 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
621 // i<digits> and u<digits> look like widths, so lets
622 // give an error message along those lines
623 if looks_like_width_suffix(&['i', 'u'], suf) {
624 sd.struct_span_err(sp, &format!("invalid width `{}` for integer literal",
626 .help("valid widths are 8, 16, 32 and 64")
629 sd.struct_span_err(sp, &format!("invalid suffix `{}` for numeric literal", suf))
630 .help("the suffix must be one of the integral types \
631 (`u32`, `isize`, etc)")
640 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
641 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
643 match u64::from_str_radix(s, base) {
644 Ok(r) => ast::LitKind::Int(r, ty),
646 // small bases are lexed as if they were base 10, e.g, the string
647 // might be `0b10201`. This will cause the conversion above to fail,
648 // but these cases have errors in the lexer: we don't want to emit
649 // two errors, and we especially don't want to emit this error since
650 // it isn't necessarily true.
651 let already_errored = base < 10 &&
652 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
654 if !already_errored {
655 sd.span_err(sp, "int literal is too large");
657 ast::LitKind::Int(0, ty)
665 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
666 use codemap::Spanned;
667 use ast::{self, PatKind};
669 use attr::{first_attr_value_str_by_name, AttrMetaMethods};
671 use parse::parser::Parser;
672 use parse::token::{str_to_ident};
673 use print::pprust::item_to_string;
675 use tokenstream::{self, TokenTree};
676 use util::parser_testing::{string_to_tts, string_to_parser};
677 use util::parser_testing::{string_to_expr, string_to_item, string_to_stmt};
680 // produce a syntax_pos::span
681 fn sp(a: u32, b: u32) -> Span {
682 Span {lo: BytePos(a), hi: BytePos(b), expn_id: NO_EXPANSION}
685 #[test] fn path_exprs_1() {
686 assert!(string_to_expr("a".to_string()) ==
688 id: ast::DUMMY_NODE_ID,
689 node: ast::ExprKind::Path(None, ast::Path {
694 identifier: str_to_ident("a"),
695 parameters: ast::PathParameters::none(),
700 attrs: ThinVec::new(),
704 #[test] fn path_exprs_2 () {
705 assert!(string_to_expr("::a::b".to_string()) ==
707 id: ast::DUMMY_NODE_ID,
708 node: ast::ExprKind::Path(None, ast::Path {
713 identifier: str_to_ident("a"),
714 parameters: ast::PathParameters::none(),
717 identifier: str_to_ident("b"),
718 parameters: ast::PathParameters::none(),
723 attrs: ThinVec::new(),
728 #[test] fn bad_path_expr_1() {
729 string_to_expr("::abc::def::return".to_string());
732 // check the token-tree-ization of macros
734 fn string_to_tts_macro () {
735 let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_string());
736 let tts: &[tokenstream::TokenTree] = &tts[..];
738 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
741 Some(&TokenTree::Token(_, token::Ident(name_macro_rules))),
742 Some(&TokenTree::Token(_, token::Not)),
743 Some(&TokenTree::Token(_, token::Ident(name_zip))),
744 Some(&TokenTree::Delimited(_, ref macro_delimed)),
746 if name_macro_rules.name.as_str() == "macro_rules"
747 && name_zip.name.as_str() == "zip" => {
748 let tts = ¯o_delimed.tts[..];
749 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
752 Some(&TokenTree::Delimited(_, ref first_delimed)),
753 Some(&TokenTree::Token(_, token::FatArrow)),
754 Some(&TokenTree::Delimited(_, ref second_delimed)),
756 if macro_delimed.delim == token::Paren => {
757 let tts = &first_delimed.tts[..];
758 match (tts.len(), tts.get(0), tts.get(1)) {
761 Some(&TokenTree::Token(_, token::Dollar)),
762 Some(&TokenTree::Token(_, token::Ident(ident))),
764 if first_delimed.delim == token::Paren
765 && ident.name.as_str() == "a" => {},
766 _ => panic!("value 3: {:?}", *first_delimed),
768 let tts = &second_delimed.tts[..];
769 match (tts.len(), tts.get(0), tts.get(1)) {
772 Some(&TokenTree::Token(_, token::Dollar)),
773 Some(&TokenTree::Token(_, token::Ident(ident))),
775 if second_delimed.delim == token::Paren
776 && ident.name.as_str() == "a" => {},
777 _ => panic!("value 4: {:?}", *second_delimed),
780 _ => panic!("value 2: {:?}", *macro_delimed),
783 _ => panic!("value: {:?}",tts),
788 fn string_to_tts_1() {
789 let tts = string_to_tts("fn a (b : i32) { b; }".to_string());
792 TokenTree::Token(sp(0, 2), token::Ident(str_to_ident("fn"))),
793 TokenTree::Token(sp(3, 4), token::Ident(str_to_ident("a"))),
794 TokenTree::Delimited(
796 tokenstream::Delimited {
797 delim: token::DelimToken::Paren,
800 TokenTree::Token(sp(6, 7), token::Ident(str_to_ident("b"))),
801 TokenTree::Token(sp(8, 9), token::Colon),
802 TokenTree::Token(sp(10, 13), token::Ident(str_to_ident("i32"))),
804 close_span: sp(13, 14),
806 TokenTree::Delimited(
808 tokenstream::Delimited {
809 delim: token::DelimToken::Brace,
810 open_span: sp(15, 16),
812 TokenTree::Token(sp(17, 18), token::Ident(str_to_ident("b"))),
813 TokenTree::Token(sp(18, 19), token::Semi),
815 close_span: sp(20, 21),
819 assert_eq!(tts, expected);
822 #[test] fn ret_expr() {
823 assert!(string_to_expr("return d".to_string()) ==
825 id: ast::DUMMY_NODE_ID,
826 node:ast::ExprKind::Ret(Some(P(ast::Expr{
827 id: ast::DUMMY_NODE_ID,
828 node:ast::ExprKind::Path(None, ast::Path{
833 identifier: str_to_ident("d"),
834 parameters: ast::PathParameters::none(),
839 attrs: ThinVec::new(),
842 attrs: ThinVec::new(),
846 #[test] fn parse_stmt_1 () {
847 assert!(string_to_stmt("b;".to_string()) ==
849 node: ast::StmtKind::Expr(P(ast::Expr {
850 id: ast::DUMMY_NODE_ID,
851 node: ast::ExprKind::Path(None, ast::Path {
856 identifier: str_to_ident("b"),
857 parameters: ast::PathParameters::none(),
862 attrs: ThinVec::new()})),
863 id: ast::DUMMY_NODE_ID,
868 fn parser_done(p: Parser){
869 assert_eq!(p.token.clone(), token::Eof);
872 #[test] fn parse_ident_pat () {
873 let sess = ParseSess::new();
874 let mut parser = string_to_parser(&sess, "b".to_string());
875 assert!(panictry!(parser.parse_pat())
877 id: ast::DUMMY_NODE_ID,
878 node: PatKind::Ident(ast::BindingMode::ByValue(ast::Mutability::Immutable),
879 Spanned{ span:sp(0, 1),
880 node: str_to_ident("b")
887 // check the contents of the tt manually:
888 #[test] fn parse_fundecl () {
889 // this test depends on the intern order of "fn" and "i32"
890 assert_eq!(string_to_item("fn a (b : i32) { b; }".to_string()),
892 P(ast::Item{ident:str_to_ident("a"),
894 id: ast::DUMMY_NODE_ID,
895 node: ast::ItemKind::Fn(P(ast::FnDecl {
896 inputs: vec!(ast::Arg{
897 ty: P(ast::Ty{id: ast::DUMMY_NODE_ID,
898 node: ast::TyKind::Path(None, ast::Path{
905 parameters: ast::PathParameters::none(),
912 id: ast::DUMMY_NODE_ID,
913 node: PatKind::Ident(
914 ast::BindingMode::ByValue(ast::Mutability::Immutable),
917 node: str_to_ident("b")},
922 id: ast::DUMMY_NODE_ID
924 output: ast::FunctionRetTy::Default(sp(15, 15)),
927 ast::Unsafety::Normal,
928 ast::Constness::NotConst,
930 ast::Generics{ // no idea on either of these:
931 lifetimes: Vec::new(),
933 where_clause: ast::WhereClause {
934 id: ast::DUMMY_NODE_ID,
935 predicates: Vec::new(),
939 stmts: vec!(ast::Stmt {
940 node: ast::StmtKind::Semi(P(ast::Expr{
941 id: ast::DUMMY_NODE_ID,
942 node: ast::ExprKind::Path(None,
952 ast::PathParameters::none(),
957 attrs: ThinVec::new()})),
958 id: ast::DUMMY_NODE_ID,
961 id: ast::DUMMY_NODE_ID,
962 rules: ast::BlockCheckMode::Default, // no idea
965 vis: ast::Visibility::Inherited,
969 #[test] fn parse_use() {
970 let use_s = "use foo::bar::baz;";
971 let vitem = string_to_item(use_s.to_string()).unwrap();
972 let vitem_s = item_to_string(&vitem);
973 assert_eq!(&vitem_s[..], use_s);
975 let use_s = "use foo::bar as baz;";
976 let vitem = string_to_item(use_s.to_string()).unwrap();
977 let vitem_s = item_to_string(&vitem);
978 assert_eq!(&vitem_s[..], use_s);
981 #[test] fn parse_extern_crate() {
982 let ex_s = "extern crate foo;";
983 let vitem = string_to_item(ex_s.to_string()).unwrap();
984 let vitem_s = item_to_string(&vitem);
985 assert_eq!(&vitem_s[..], ex_s);
987 let ex_s = "extern crate foo as bar;";
988 let vitem = string_to_item(ex_s.to_string()).unwrap();
989 let vitem_s = item_to_string(&vitem);
990 assert_eq!(&vitem_s[..], ex_s);
993 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
994 let item = string_to_item(src.to_string()).unwrap();
996 struct PatIdentVisitor {
999 impl ::visit::Visitor for PatIdentVisitor {
1000 fn visit_pat(&mut self, p: &ast::Pat) {
1002 PatKind::Ident(_ , ref spannedident, _) => {
1003 self.spans.push(spannedident.span.clone());
1006 ::visit::walk_pat(self, p);
1011 let mut v = PatIdentVisitor { spans: Vec::new() };
1012 ::visit::walk_item(&mut v, &item);
1016 #[test] fn span_of_self_arg_pat_idents_are_correct() {
1018 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
1019 "impl z { fn a (&mut self, &myarg: i32) {} }",
1020 "impl z { fn a (&'a self, &myarg: i32) {} }",
1021 "impl z { fn a (self, &myarg: i32) {} }",
1022 "impl z { fn a (self: Foo, &myarg: i32) {} }",
1026 let spans = get_spans_of_pat_idents(src);
1027 let Span{ lo, hi, .. } = spans[0];
1028 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
1029 "\"{}\" != \"self\". src=\"{}\"",
1030 &src[lo.to_usize()..hi.to_usize()], src)
1034 #[test] fn parse_exprs () {
1035 // just make sure that they parse....
1036 string_to_expr("3 + 4".to_string());
1037 string_to_expr("a::z.froob(b,&(987+3))".to_string());
1040 #[test] fn attrs_fix_bug () {
1041 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
1042 -> Result<Box<Writer>, String> {
1045 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1049 fn wb() -> c_int { O_WRONLY as c_int }
1051 let mut fflags: c_int = wb();
1055 #[test] fn crlf_doc_comments() {
1056 let sess = ParseSess::new();
1058 let name = "<source>".to_string();
1059 let source = "/// doc comment\r\nfn foo() {}".to_string();
1060 let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess)
1062 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1063 assert_eq!(&doc[..], "/// doc comment");
1065 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1066 let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess)
1068 let docs = item.attrs.iter().filter(|a| &*a.name() == "doc")
1069 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1070 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1071 assert_eq!(&docs[..], b);
1073 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1074 let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap().unwrap();
1075 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1076 assert_eq!(&doc[..], "/** doc comment\n * with CRLF */");
1081 let sess = ParseSess::new();
1082 let expr = parse::parse_expr_from_source_str("foo".to_string(),
1083 "foo!( fn main() { body } )".to_string(), vec![], &sess).unwrap();
1085 let tts = match expr.node {
1086 ast::ExprKind::Mac(ref mac) => mac.node.tts.clone(),
1087 _ => panic!("not a macro"),
1090 let span = tts.iter().rev().next().unwrap().get_span();
1092 match sess.codemap().span_to_snippet(span) {
1093 Ok(s) => assert_eq!(&s[..], "{ body }"),
1094 Err(_) => panic!("could not get snippet"),