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,
57 ParseSess::with_span_handler(handler, cm)
60 pub fn with_span_handler(handler: Handler, code_map: Rc<CodeMap>) -> ParseSess {
62 span_diagnostic: handler,
63 included_mod_stack: RefCell::new(vec![]),
68 pub fn codemap(&self) -> &CodeMap {
73 // a bunch of utility functions of the form parse_<thing>_from_<source>
74 // where <thing> includes crate, expr, item, stmt, tts, and one that
75 // uses a HOF to parse anything, and <source> includes file and
78 pub fn parse_crate_from_file<'a>(input: &Path,
79 cfg: ast::CrateConfig,
81 -> PResult<'a, ast::Crate> {
82 let mut parser = new_parser_from_file(sess, cfg, input);
83 parser.parse_crate_mod()
86 pub fn parse_crate_attrs_from_file<'a>(input: &Path,
87 cfg: ast::CrateConfig,
89 -> PResult<'a, Vec<ast::Attribute>> {
90 let mut parser = new_parser_from_file(sess, cfg, input);
91 parser.parse_inner_attributes()
94 pub fn parse_crate_from_source_str<'a>(name: String,
96 cfg: ast::CrateConfig,
98 -> PResult<'a, ast::Crate> {
99 let mut p = new_parser_from_source_str(sess,
106 pub fn parse_crate_attrs_from_source_str<'a>(name: String,
108 cfg: ast::CrateConfig,
110 -> PResult<'a, Vec<ast::Attribute>> {
111 let mut p = new_parser_from_source_str(sess,
115 p.parse_inner_attributes()
118 pub fn parse_expr_from_source_str<'a>(name: String,
120 cfg: ast::CrateConfig,
122 -> PResult<'a, P<ast::Expr>> {
123 let mut p = new_parser_from_source_str(sess, cfg, name, source);
129 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and`Err`
130 /// when a syntax error occurred.
131 pub fn parse_item_from_source_str<'a>(name: String,
133 cfg: ast::CrateConfig,
135 -> PResult<'a, Option<P<ast::Item>>> {
136 let mut p = new_parser_from_source_str(sess, cfg, name, source);
140 pub fn parse_meta_from_source_str<'a>(name: String,
142 cfg: ast::CrateConfig,
144 -> PResult<'a, P<ast::MetaItem>> {
145 let mut p = new_parser_from_source_str(sess, cfg, name, source);
149 pub fn parse_stmt_from_source_str<'a>(name: String,
151 cfg: ast::CrateConfig,
153 -> PResult<'a, Option<ast::Stmt>> {
154 let mut p = new_parser_from_source_str(
163 // Warning: This parses with quote_depth > 0, which is not the default.
164 pub fn parse_tts_from_source_str<'a>(name: String,
166 cfg: ast::CrateConfig,
168 -> PResult<'a, Vec<tokenstream::TokenTree>> {
169 let mut p = new_parser_from_source_str(
176 // right now this is re-creating the token trees from ... token trees.
177 p.parse_all_token_trees()
180 // Create a new parser from a source string
181 pub fn new_parser_from_source_str<'a>(sess: &'a ParseSess,
182 cfg: ast::CrateConfig,
186 filemap_to_parser(sess, sess.codemap().new_filemap(name, None, source), cfg)
189 /// Create a new parser, handling errors as appropriate
190 /// if the file doesn't exist
191 pub fn new_parser_from_file<'a>(sess: &'a ParseSess,
192 cfg: ast::CrateConfig,
193 path: &Path) -> Parser<'a> {
194 filemap_to_parser(sess, file_to_filemap(sess, path, None), cfg)
197 /// Given a session, a crate config, a path, and a span, add
198 /// the file at the given path to the codemap, and return a parser.
199 /// On an error, use the given span as the source of the problem.
200 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
201 cfg: ast::CrateConfig,
203 owns_directory: bool,
204 module_name: Option<String>,
205 sp: Span) -> Parser<'a> {
206 let mut p = filemap_to_parser(sess, file_to_filemap(sess, path, Some(sp)), cfg);
207 p.owns_directory = owns_directory;
208 p.root_module_name = module_name;
212 /// Given a filemap and config, return a parser
213 pub fn filemap_to_parser<'a>(sess: &'a ParseSess,
214 filemap: Rc<FileMap>,
215 cfg: ast::CrateConfig) -> Parser<'a> {
216 let end_pos = filemap.end_pos;
217 let mut parser = tts_to_parser(sess, filemap_to_tts(sess, filemap), cfg);
219 if parser.token == token::Eof && parser.span == syntax_pos::DUMMY_SP {
220 parser.span = syntax_pos::mk_sp(end_pos, end_pos);
226 // must preserve old name for now, because quote! from the *existing*
227 // compiler expands into it
228 pub fn new_parser_from_tts<'a>(sess: &'a ParseSess,
229 cfg: ast::CrateConfig,
230 tts: Vec<tokenstream::TokenTree>)
232 tts_to_parser(sess, tts, cfg)
235 pub fn new_parser_from_ts<'a>(sess: &'a ParseSess,
236 cfg: ast::CrateConfig,
237 ts: tokenstream::TokenStream)
239 tts_to_parser(sess, ts.to_tts(), cfg)
245 /// Given a session and a path and an optional span (for error reporting),
246 /// add the path to the session's codemap and return the new filemap.
247 fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
249 match sess.codemap().load_file(path) {
250 Ok(filemap) => filemap,
252 let msg = format!("couldn't read {:?}: {}", path.display(), e);
254 Some(sp) => panic!(sess.span_diagnostic.span_fatal(sp, &msg)),
255 None => panic!(sess.span_diagnostic.fatal(&msg))
261 /// Given a filemap, produce a sequence of token-trees
262 pub fn filemap_to_tts(sess: &ParseSess, filemap: Rc<FileMap>)
263 -> Vec<tokenstream::TokenTree> {
264 // it appears to me that the cfg doesn't matter here... indeed,
265 // parsing tt's probably shouldn't require a parser at all.
266 let cfg = Vec::new();
267 let srdr = lexer::StringReader::new(&sess.span_diagnostic, filemap);
268 let mut p1 = Parser::new(sess, cfg, Box::new(srdr));
269 panictry!(p1.parse_all_token_trees())
272 /// Given tts and cfg, produce a parser
273 pub fn tts_to_parser<'a>(sess: &'a ParseSess,
274 tts: Vec<tokenstream::TokenTree>,
275 cfg: ast::CrateConfig) -> Parser<'a> {
276 let trdr = lexer::new_tt_reader(&sess.span_diagnostic, None, None, tts);
277 let mut p = Parser::new(sess, cfg, Box::new(trdr));
278 p.check_unknown_macro_variable();
282 /// Parse a string representing a character literal into its final form.
283 /// Rather than just accepting/rejecting a given literal, unescapes it as
284 /// well. Can take any slice prefixed by a character escape. Returns the
285 /// character and the number of characters consumed.
286 pub fn char_lit(lit: &str) -> (char, isize) {
289 let mut chars = lit.chars();
290 let c = match (chars.next(), chars.next()) {
291 (Some(c), None) if c != '\\' => return (c, 1),
292 (Some('\\'), Some(c)) => match c {
302 _ => panic!("lexer accepted invalid char escape `{}`", lit)
306 Some(x) => return (x, 2),
310 let msg = format!("lexer should have rejected a bad character escape {}", lit);
313 fn esc(len: usize, lit: &str) -> Option<(char, isize)> {
314 u32::from_str_radix(&lit[2..len], 16).ok()
315 .and_then(char::from_u32)
316 .map(|x| (x, len as isize))
319 let unicode_escape = || -> Option<(char, isize)> {
320 if lit.as_bytes()[2] == b'{' {
321 let idx = lit.find('}').expect(msg2);
322 let subslice = &lit[3..idx];
323 u32::from_str_radix(subslice, 16).ok()
324 .and_then(char::from_u32)
325 .map(|x| (x, subslice.chars().count() as isize + 4))
332 return match lit.as_bytes()[1] as char {
333 'x' | 'X' => esc(4, lit),
334 'u' => unicode_escape(),
340 /// Parse a string representing a string literal into its final form. Does
342 pub fn str_lit(lit: &str) -> String {
343 debug!("parse_str_lit: given {}", lit.escape_default());
344 let mut res = String::with_capacity(lit.len());
346 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
347 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
349 /// Eat everything up to a non-whitespace
350 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
352 match it.peek().map(|x| x.1) {
353 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
361 let mut chars = lit.char_indices().peekable();
367 let ch = chars.peek().unwrap_or_else(|| {
368 panic!("{}", error(i))
373 } else if ch == '\r' {
375 let ch = chars.peek().unwrap_or_else(|| {
376 panic!("{}", error(i))
380 panic!("lexer accepted bare CR");
384 // otherwise, a normal escape
385 let (c, n) = char_lit(&lit[i..]);
386 for _ in 0..n - 1 { // we don't need to move past the first \
393 let ch = chars.peek().unwrap_or_else(|| {
394 panic!("{}", error(i))
398 panic!("lexer accepted bare CR");
410 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
411 debug!("parse_str_lit: returning {}", res);
415 /// Parse a string representing a raw string literal into its final form. The
416 /// only operation this does is convert embedded CRLF into a single LF.
417 pub fn raw_str_lit(lit: &str) -> String {
418 debug!("raw_str_lit: given {}", lit.escape_default());
419 let mut res = String::with_capacity(lit.len());
421 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
422 let mut chars = lit.chars().peekable();
427 if *chars.peek().unwrap() != '\n' {
428 panic!("lexer accepted bare CR");
444 // check if `s` looks like i32 or u1234 etc.
445 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
447 first_chars.contains(&char_at(s, 0)) &&
448 s[1..].chars().all(|c| '0' <= c && c <= '9')
451 fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>,
452 sd: &Handler, sp: Span) -> ast::LitKind {
453 debug!("filtered_float_lit: {}, {:?}", data, suffix);
454 match suffix.as_ref().map(|s| &**s) {
455 Some("f32") => ast::LitKind::Float(data, ast::FloatTy::F32),
456 Some("f64") => ast::LitKind::Float(data, ast::FloatTy::F64),
458 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
459 // if it looks like a width, lets try to be helpful.
460 sd.struct_span_err(sp, &format!("invalid width `{}` for float literal", &suf[1..]))
461 .help("valid widths are 32 and 64")
464 sd.struct_span_err(sp, &format!("invalid suffix `{}` for float literal", suf))
465 .help("valid suffixes are `f32` and `f64`")
469 ast::LitKind::FloatUnsuffixed(data)
471 None => ast::LitKind::FloatUnsuffixed(data)
474 pub fn float_lit(s: &str, suffix: Option<InternedString>,
475 sd: &Handler, sp: Span) -> ast::LitKind {
476 debug!("float_lit: {:?}, {:?}", s, suffix);
477 // FIXME #2252: bounds checking float literals is deferred until trans
478 let s = s.chars().filter(|&c| c != '_').collect::<String>();
479 let data = token::intern_and_get_ident(&s);
480 filtered_float_lit(data, suffix.as_ref().map(|s| &**s), sd, sp)
483 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
484 pub fn byte_lit(lit: &str) -> (u8, usize) {
485 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
488 (lit.as_bytes()[0], 1)
490 assert!(lit.as_bytes()[0] == b'\\', err(0));
491 let b = match lit.as_bytes()[1] {
500 match u64::from_str_radix(&lit[2..4], 16).ok() {
507 None => panic!(err(3))
515 pub fn byte_str_lit(lit: &str) -> Rc<Vec<u8>> {
516 let mut res = Vec::with_capacity(lit.len());
518 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
519 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
521 /// Eat everything up to a non-whitespace
522 fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
524 match it.peek().map(|x| x.1) {
525 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
533 // byte string literals *must* be ASCII, but the escapes don't have to be
534 let mut chars = lit.bytes().enumerate().peekable();
537 Some((i, b'\\')) => {
539 match chars.peek().expect(&em).1 {
540 b'\n' => eat(&mut chars),
543 if chars.peek().expect(&em).1 != b'\n' {
544 panic!("lexer accepted bare CR");
549 // otherwise, a normal escape
550 let (c, n) = byte_lit(&lit[i..]);
551 // we don't need to move past the first \
559 Some((i, b'\r')) => {
561 if chars.peek().expect(&em).1 != b'\n' {
562 panic!("lexer accepted bare CR");
567 Some((_, c)) => res.push(c),
575 pub fn integer_lit(s: &str,
576 suffix: Option<InternedString>,
580 // s can only be ascii, byte indexing is fine
582 let s2 = s.chars().filter(|&c| c != '_').collect::<String>();
585 debug!("integer_lit: {}, {:?}", s, suffix);
589 let mut ty = ast::LitIntType::Unsuffixed;
591 if char_at(s, 0) == '0' && s.len() > 1 {
592 match char_at(s, 1) {
600 // 1f64 and 2f32 etc. are valid float literals.
601 if let Some(ref suf) = suffix {
602 if looks_like_width_suffix(&['f'], suf) {
604 16 => sd.span_err(sp, "hexadecimal float literal is not supported"),
605 8 => sd.span_err(sp, "octal float literal is not supported"),
606 2 => sd.span_err(sp, "binary float literal is not supported"),
609 let ident = token::intern_and_get_ident(&s);
610 return filtered_float_lit(ident, Some(&suf), sd, sp)
618 if let Some(ref suf) = suffix {
619 if suf.is_empty() { sd.span_bug(sp, "found empty literal suffix in Some")}
621 "isize" => ast::LitIntType::Signed(ast::IntTy::Is),
622 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
623 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
624 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
625 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
626 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Us),
627 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
628 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
629 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
630 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
632 // i<digits> and u<digits> look like widths, so lets
633 // give an error message along those lines
634 if looks_like_width_suffix(&['i', 'u'], suf) {
635 sd.struct_span_err(sp, &format!("invalid width `{}` for integer literal",
637 .help("valid widths are 8, 16, 32 and 64")
640 sd.struct_span_err(sp, &format!("invalid suffix `{}` for numeric literal", suf))
641 .help("the suffix must be one of the integral types \
642 (`u32`, `isize`, etc)")
651 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
652 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
654 match u64::from_str_radix(s, base) {
655 Ok(r) => ast::LitKind::Int(r, ty),
657 // small bases are lexed as if they were base 10, e.g, the string
658 // might be `0b10201`. This will cause the conversion above to fail,
659 // but these cases have errors in the lexer: we don't want to emit
660 // two errors, and we especially don't want to emit this error since
661 // it isn't necessarily true.
662 let already_errored = base < 10 &&
663 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
665 if !already_errored {
666 sd.span_err(sp, "int literal is too large");
668 ast::LitKind::Int(0, ty)
677 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
678 use codemap::Spanned;
679 use ast::{self, PatKind};
681 use attr::{first_attr_value_str_by_name, AttrMetaMethods};
683 use parse::parser::Parser;
684 use parse::token::{str_to_ident};
685 use print::pprust::item_to_string;
687 use tokenstream::{self, TokenTree};
688 use util::parser_testing::{string_to_tts, string_to_parser};
689 use util::parser_testing::{string_to_expr, string_to_item, string_to_stmt};
692 // produce a syntax_pos::span
693 fn sp(a: u32, b: u32) -> Span {
694 Span {lo: BytePos(a), hi: BytePos(b), expn_id: NO_EXPANSION}
697 #[test] fn path_exprs_1() {
698 assert!(string_to_expr("a".to_string()) ==
700 id: ast::DUMMY_NODE_ID,
701 node: ast::ExprKind::Path(None, ast::Path {
706 identifier: str_to_ident("a"),
707 parameters: ast::PathParameters::none(),
712 attrs: ThinVec::new(),
716 #[test] fn path_exprs_2 () {
717 assert!(string_to_expr("::a::b".to_string()) ==
719 id: ast::DUMMY_NODE_ID,
720 node: ast::ExprKind::Path(None, ast::Path {
725 identifier: str_to_ident("a"),
726 parameters: ast::PathParameters::none(),
729 identifier: str_to_ident("b"),
730 parameters: ast::PathParameters::none(),
735 attrs: ThinVec::new(),
740 #[test] fn bad_path_expr_1() {
741 string_to_expr("::abc::def::return".to_string());
744 // check the token-tree-ization of macros
746 fn string_to_tts_macro () {
747 let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_string());
748 let tts: &[tokenstream::TokenTree] = &tts[..];
750 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
753 Some(&TokenTree::Token(_, token::Ident(name_macro_rules))),
754 Some(&TokenTree::Token(_, token::Not)),
755 Some(&TokenTree::Token(_, token::Ident(name_zip))),
756 Some(&TokenTree::Delimited(_, ref macro_delimed)),
758 if name_macro_rules.name.as_str() == "macro_rules"
759 && name_zip.name.as_str() == "zip" => {
760 let tts = ¯o_delimed.tts[..];
761 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
764 Some(&TokenTree::Delimited(_, ref first_delimed)),
765 Some(&TokenTree::Token(_, token::FatArrow)),
766 Some(&TokenTree::Delimited(_, ref second_delimed)),
768 if macro_delimed.delim == token::Paren => {
769 let tts = &first_delimed.tts[..];
770 match (tts.len(), tts.get(0), tts.get(1)) {
773 Some(&TokenTree::Token(_, token::Dollar)),
774 Some(&TokenTree::Token(_, token::Ident(ident))),
776 if first_delimed.delim == token::Paren
777 && ident.name.as_str() == "a" => {},
778 _ => panic!("value 3: {:?}", **first_delimed),
780 let tts = &second_delimed.tts[..];
781 match (tts.len(), tts.get(0), tts.get(1)) {
784 Some(&TokenTree::Token(_, token::Dollar)),
785 Some(&TokenTree::Token(_, token::Ident(ident))),
787 if second_delimed.delim == token::Paren
788 && ident.name.as_str() == "a" => {},
789 _ => panic!("value 4: {:?}", **second_delimed),
792 _ => panic!("value 2: {:?}", **macro_delimed),
795 _ => panic!("value: {:?}",tts),
800 fn string_to_tts_1() {
801 let tts = string_to_tts("fn a (b : i32) { b; }".to_string());
804 TokenTree::Token(sp(0, 2), token::Ident(str_to_ident("fn"))),
805 TokenTree::Token(sp(3, 4), token::Ident(str_to_ident("a"))),
806 TokenTree::Delimited(
808 Rc::new(tokenstream::Delimited {
809 delim: token::DelimToken::Paren,
812 TokenTree::Token(sp(6, 7), token::Ident(str_to_ident("b"))),
813 TokenTree::Token(sp(8, 9), token::Colon),
814 TokenTree::Token(sp(10, 13), token::Ident(str_to_ident("i32"))),
816 close_span: sp(13, 14),
818 TokenTree::Delimited(
820 Rc::new(tokenstream::Delimited {
821 delim: token::DelimToken::Brace,
822 open_span: sp(15, 16),
824 TokenTree::Token(sp(17, 18), token::Ident(str_to_ident("b"))),
825 TokenTree::Token(sp(18, 19), token::Semi),
827 close_span: sp(20, 21),
831 assert_eq!(tts, expected);
834 #[test] fn ret_expr() {
835 assert!(string_to_expr("return d".to_string()) ==
837 id: ast::DUMMY_NODE_ID,
838 node:ast::ExprKind::Ret(Some(P(ast::Expr{
839 id: ast::DUMMY_NODE_ID,
840 node:ast::ExprKind::Path(None, ast::Path{
845 identifier: str_to_ident("d"),
846 parameters: ast::PathParameters::none(),
851 attrs: ThinVec::new(),
854 attrs: ThinVec::new(),
858 #[test] fn parse_stmt_1 () {
859 assert!(string_to_stmt("b;".to_string()) ==
861 node: ast::StmtKind::Expr(P(ast::Expr {
862 id: ast::DUMMY_NODE_ID,
863 node: ast::ExprKind::Path(None, ast::Path {
868 identifier: str_to_ident("b"),
869 parameters: ast::PathParameters::none(),
874 attrs: ThinVec::new()})),
875 id: ast::DUMMY_NODE_ID,
880 fn parser_done(p: Parser){
881 assert_eq!(p.token.clone(), token::Eof);
884 #[test] fn parse_ident_pat () {
885 let sess = ParseSess::new();
886 let mut parser = string_to_parser(&sess, "b".to_string());
887 assert!(panictry!(parser.parse_pat())
889 id: ast::DUMMY_NODE_ID,
890 node: PatKind::Ident(ast::BindingMode::ByValue(ast::Mutability::Immutable),
891 Spanned{ span:sp(0, 1),
892 node: str_to_ident("b")
899 // check the contents of the tt manually:
900 #[test] fn parse_fundecl () {
901 // this test depends on the intern order of "fn" and "i32"
902 assert_eq!(string_to_item("fn a (b : i32) { b; }".to_string()),
904 P(ast::Item{ident:str_to_ident("a"),
906 id: ast::DUMMY_NODE_ID,
907 node: ast::ItemKind::Fn(P(ast::FnDecl {
908 inputs: vec!(ast::Arg{
909 ty: P(ast::Ty{id: ast::DUMMY_NODE_ID,
910 node: ast::TyKind::Path(None, ast::Path{
917 parameters: ast::PathParameters::none(),
924 id: ast::DUMMY_NODE_ID,
925 node: PatKind::Ident(
926 ast::BindingMode::ByValue(ast::Mutability::Immutable),
929 node: str_to_ident("b")},
934 id: ast::DUMMY_NODE_ID
936 output: ast::FunctionRetTy::Default(sp(15, 15)),
939 ast::Unsafety::Normal,
940 ast::Constness::NotConst,
942 ast::Generics{ // no idea on either of these:
943 lifetimes: Vec::new(),
945 where_clause: ast::WhereClause {
946 id: ast::DUMMY_NODE_ID,
947 predicates: Vec::new(),
951 stmts: vec!(ast::Stmt {
952 node: ast::StmtKind::Semi(P(ast::Expr{
953 id: ast::DUMMY_NODE_ID,
954 node: ast::ExprKind::Path(None,
964 ast::PathParameters::none(),
969 attrs: ThinVec::new()})),
970 id: ast::DUMMY_NODE_ID,
972 id: ast::DUMMY_NODE_ID,
973 rules: ast::BlockCheckMode::Default, // no idea
976 vis: ast::Visibility::Inherited,
980 #[test] fn parse_use() {
981 let use_s = "use foo::bar::baz;";
982 let vitem = string_to_item(use_s.to_string()).unwrap();
983 let vitem_s = item_to_string(&vitem);
984 assert_eq!(&vitem_s[..], use_s);
986 let use_s = "use foo::bar as baz;";
987 let vitem = string_to_item(use_s.to_string()).unwrap();
988 let vitem_s = item_to_string(&vitem);
989 assert_eq!(&vitem_s[..], use_s);
992 #[test] fn parse_extern_crate() {
993 let ex_s = "extern crate foo;";
994 let vitem = string_to_item(ex_s.to_string()).unwrap();
995 let vitem_s = item_to_string(&vitem);
996 assert_eq!(&vitem_s[..], ex_s);
998 let ex_s = "extern crate foo as bar;";
999 let vitem = string_to_item(ex_s.to_string()).unwrap();
1000 let vitem_s = item_to_string(&vitem);
1001 assert_eq!(&vitem_s[..], ex_s);
1004 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
1005 let item = string_to_item(src.to_string()).unwrap();
1007 struct PatIdentVisitor {
1010 impl ::visit::Visitor for PatIdentVisitor {
1011 fn visit_pat(&mut self, p: &ast::Pat) {
1013 PatKind::Ident(_ , ref spannedident, _) => {
1014 self.spans.push(spannedident.span.clone());
1017 ::visit::walk_pat(self, p);
1022 let mut v = PatIdentVisitor { spans: Vec::new() };
1023 ::visit::walk_item(&mut v, &item);
1027 #[test] fn span_of_self_arg_pat_idents_are_correct() {
1029 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
1030 "impl z { fn a (&mut self, &myarg: i32) {} }",
1031 "impl z { fn a (&'a self, &myarg: i32) {} }",
1032 "impl z { fn a (self, &myarg: i32) {} }",
1033 "impl z { fn a (self: Foo, &myarg: i32) {} }",
1037 let spans = get_spans_of_pat_idents(src);
1038 let Span{ lo, hi, .. } = spans[0];
1039 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
1040 "\"{}\" != \"self\". src=\"{}\"",
1041 &src[lo.to_usize()..hi.to_usize()], src)
1045 #[test] fn parse_exprs () {
1046 // just make sure that they parse....
1047 string_to_expr("3 + 4".to_string());
1048 string_to_expr("a::z.froob(b,&(987+3))".to_string());
1051 #[test] fn attrs_fix_bug () {
1052 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
1053 -> Result<Box<Writer>, String> {
1056 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1060 fn wb() -> c_int { O_WRONLY as c_int }
1062 let mut fflags: c_int = wb();
1066 #[test] fn crlf_doc_comments() {
1067 let sess = ParseSess::new();
1069 let name = "<source>".to_string();
1070 let source = "/// doc comment\r\nfn foo() {}".to_string();
1071 let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess)
1073 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1074 assert_eq!(&doc[..], "/// doc comment");
1076 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1077 let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess)
1079 let docs = item.attrs.iter().filter(|a| &*a.name() == "doc")
1080 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1081 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1082 assert_eq!(&docs[..], b);
1084 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1085 let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap().unwrap();
1086 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1087 assert_eq!(&doc[..], "/** doc comment\n * with CRLF */");
1092 let sess = ParseSess::new();
1093 let expr = parse::parse_expr_from_source_str("foo".to_string(),
1094 "foo!( fn main() { body } )".to_string(), vec![], &sess).unwrap();
1096 let tts = match expr.node {
1097 ast::ExprKind::Mac(ref mac) => mac.node.tts.clone(),
1098 _ => panic!("not a macro"),
1101 let span = tts.iter().rev().next().unwrap().get_span();
1103 match sess.codemap().span_to_snippet(span) {
1104 Ok(s) => assert_eq!(&s[..], "{ body }"),
1105 Err(_) => panic!("could not get snippet"),