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
13 use ast::{self, CrateConfig};
14 use codemap::{CodeMap, FilePathMapping};
15 use syntax_pos::{self, Span, FileMap, NO_EXPANSION};
16 use errors::{Handler, ColorConfig, DiagnosticBuilder};
17 use feature_gate::UnstableFeatures;
18 use parse::parser::Parser;
22 use tokenstream::{TokenStream, TokenTree};
24 use std::cell::RefCell;
25 use std::collections::HashSet;
27 use std::path::{Path, PathBuf};
31 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
44 /// Info about a parsing session.
45 pub struct ParseSess {
46 pub span_diagnostic: Handler,
47 pub unstable_features: UnstableFeatures,
48 pub config: CrateConfig,
49 pub missing_fragment_specifiers: RefCell<HashSet<Span>>,
50 /// Used to determine and report recursive mod inclusions
51 included_mod_stack: RefCell<Vec<PathBuf>>,
52 code_map: Rc<CodeMap>,
56 pub fn new(file_path_mapping: FilePathMapping) -> Self {
57 let cm = Rc::new(CodeMap::new(file_path_mapping));
58 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
62 ParseSess::with_span_handler(handler, cm)
65 pub fn with_span_handler(handler: Handler, code_map: Rc<CodeMap>) -> ParseSess {
67 span_diagnostic: handler,
68 unstable_features: UnstableFeatures::from_environment(),
69 config: HashSet::new(),
70 missing_fragment_specifiers: RefCell::new(HashSet::new()),
71 included_mod_stack: RefCell::new(vec![]),
76 pub fn codemap(&self) -> &CodeMap {
82 pub struct Directory {
84 pub ownership: DirectoryOwnership,
87 #[derive(Copy, Clone)]
88 pub enum DirectoryOwnership {
91 UnownedViaMod(bool /* legacy warnings? */),
94 // a bunch of utility functions of the form parse_<thing>_from_<source>
95 // where <thing> includes crate, expr, item, stmt, tts, and one that
96 // uses a HOF to parse anything, and <source> includes file and
99 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
100 let mut parser = new_parser_from_file(sess, input);
101 parser.parse_crate_mod()
104 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
105 -> PResult<'a, Vec<ast::Attribute>> {
106 let mut parser = new_parser_from_file(sess, input);
107 parser.parse_inner_attributes()
110 pub fn parse_crate_from_source_str(name: String, source: String, sess: &ParseSess)
111 -> PResult<ast::Crate> {
112 new_parser_from_source_str(sess, name, source).parse_crate_mod()
115 pub fn parse_crate_attrs_from_source_str(name: String, source: String, sess: &ParseSess)
116 -> PResult<Vec<ast::Attribute>> {
117 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
120 pub fn parse_expr_from_source_str(name: String, source: String, sess: &ParseSess)
121 -> PResult<P<ast::Expr>> {
122 new_parser_from_source_str(sess, name, source).parse_expr()
127 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and`Err`
128 /// when a syntax error occurred.
129 pub fn parse_item_from_source_str(name: String, source: String, sess: &ParseSess)
130 -> PResult<Option<P<ast::Item>>> {
131 new_parser_from_source_str(sess, name, source).parse_item()
134 pub fn parse_meta_from_source_str(name: String, source: String, sess: &ParseSess)
135 -> PResult<ast::MetaItem> {
136 new_parser_from_source_str(sess, name, source).parse_meta_item()
139 pub fn parse_stmt_from_source_str(name: String, source: String, sess: &ParseSess)
140 -> PResult<Option<ast::Stmt>> {
141 new_parser_from_source_str(sess, name, source).parse_stmt()
144 pub fn parse_stream_from_source_str(name: String, source: String, sess: &ParseSess)
146 filemap_to_stream(sess, sess.codemap().new_filemap(name, source))
149 // Create a new parser from a source string
150 pub fn new_parser_from_source_str(sess: &ParseSess, name: String, source: String)
152 filemap_to_parser(sess, sess.codemap().new_filemap(name, source))
155 /// Create a new parser, handling errors as appropriate
156 /// if the file doesn't exist
157 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
158 filemap_to_parser(sess, file_to_filemap(sess, path, None))
161 /// Given a session, a crate config, a path, and a span, add
162 /// the file at the given path to the codemap, and return a parser.
163 /// On an error, use the given span as the source of the problem.
164 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
166 directory_ownership: DirectoryOwnership,
167 module_name: Option<String>,
168 sp: Span) -> Parser<'a> {
169 let mut p = filemap_to_parser(sess, file_to_filemap(sess, path, Some(sp)));
170 p.directory.ownership = directory_ownership;
171 p.root_module_name = module_name;
175 /// Given a filemap and config, return a parser
176 pub fn filemap_to_parser(sess: & ParseSess, filemap: Rc<FileMap>, ) -> Parser {
177 let end_pos = filemap.end_pos;
178 let mut parser = stream_to_parser(sess, filemap_to_stream(sess, filemap));
180 if parser.token == token::Eof && parser.span == syntax_pos::DUMMY_SP {
181 parser.span = Span { lo: end_pos, hi: end_pos, ctxt: NO_EXPANSION };
187 // must preserve old name for now, because quote! from the *existing*
188 // compiler expands into it
189 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser {
190 stream_to_parser(sess, tts.into_iter().collect())
196 /// Given a session and a path and an optional span (for error reporting),
197 /// add the path to the session's codemap and return the new filemap.
198 fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
200 match sess.codemap().load_file(path) {
201 Ok(filemap) => filemap,
203 let msg = format!("couldn't read {:?}: {}", path.display(), e);
205 Some(sp) => panic!(sess.span_diagnostic.span_fatal(sp, &msg)),
206 None => panic!(sess.span_diagnostic.fatal(&msg))
212 /// Given a filemap, produce a sequence of token-trees
213 pub fn filemap_to_stream(sess: &ParseSess, filemap: Rc<FileMap>) -> TokenStream {
214 let mut srdr = lexer::StringReader::new(sess, filemap);
216 panictry!(srdr.parse_all_token_trees())
219 /// Given stream and the `ParseSess`, produce a parser
220 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser {
221 Parser::new(sess, stream, None, false)
224 /// Parse a string representing a character literal into its final form.
225 /// Rather than just accepting/rejecting a given literal, unescapes it as
226 /// well. Can take any slice prefixed by a character escape. Returns the
227 /// character and the number of characters consumed.
228 pub fn char_lit(lit: &str) -> (char, isize) {
231 // Handle non-escaped chars first.
232 if lit.as_bytes()[0] != b'\\' {
233 // If the first byte isn't '\\' it might part of a multi-byte char, so
234 // get the char with chars().
235 let c = lit.chars().next().unwrap();
239 // Handle escaped chars.
240 match lit.as_bytes()[1] as char {
249 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
250 let c = char::from_u32(v).unwrap();
254 assert_eq!(lit.as_bytes()[2], b'{');
255 let idx = lit.find('}').unwrap();
256 let v = u32::from_str_radix(&lit[3..idx], 16).unwrap();
257 let c = char::from_u32(v).unwrap();
258 (c, (idx + 1) as isize)
260 _ => panic!("lexer should have rejected a bad character escape {}", lit)
264 pub fn escape_default(s: &str) -> String {
265 s.chars().map(char::escape_default).flat_map(|x| x).collect()
268 /// Parse a string representing a string literal into its final form. Does
270 pub fn str_lit(lit: &str) -> String {
271 debug!("parse_str_lit: given {}", escape_default(lit));
272 let mut res = String::with_capacity(lit.len());
274 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
275 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
277 /// Eat everything up to a non-whitespace
278 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
280 match it.peek().map(|x| x.1) {
281 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
289 let mut chars = lit.char_indices().peekable();
290 while let Some((i, c)) = chars.next() {
293 let ch = chars.peek().unwrap_or_else(|| {
294 panic!("{}", error(i))
299 } else if ch == '\r' {
301 let ch = chars.peek().unwrap_or_else(|| {
302 panic!("{}", error(i))
306 panic!("lexer accepted bare CR");
310 // otherwise, a normal escape
311 let (c, n) = char_lit(&lit[i..]);
312 for _ in 0..n - 1 { // we don't need to move past the first \
319 let ch = chars.peek().unwrap_or_else(|| {
320 panic!("{}", error(i))
324 panic!("lexer accepted bare CR");
333 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
334 debug!("parse_str_lit: returning {}", res);
338 /// Parse a string representing a raw string literal into its final form. The
339 /// only operation this does is convert embedded CRLF into a single LF.
340 pub fn raw_str_lit(lit: &str) -> String {
341 debug!("raw_str_lit: given {}", escape_default(lit));
342 let mut res = String::with_capacity(lit.len());
344 let mut chars = lit.chars().peekable();
345 while let Some(c) = chars.next() {
347 if *chars.peek().unwrap() != '\n' {
348 panic!("lexer accepted bare CR");
361 // check if `s` looks like i32 or u1234 etc.
362 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
364 first_chars.contains(&char_at(s, 0)) &&
365 s[1..].chars().all(|c| '0' <= c && c <= '9')
369 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
371 Some(($span, $diag)) => { $($body)* }
377 pub fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
378 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
382 token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
383 token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str()).0))),
385 // There are some valid suffixes for integer and float literals,
386 // so all the handling is done internally.
387 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
388 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
391 let s = Symbol::intern(&str_lit(&s.as_str()));
392 (true, Some(LitKind::Str(s, ast::StrStyle::Cooked)))
394 token::StrRaw(s, n) => {
395 let s = Symbol::intern(&raw_str_lit(&s.as_str()));
396 (true, Some(LitKind::Str(s, ast::StrStyle::Raw(n))))
398 token::ByteStr(i) => {
399 (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
401 token::ByteStrRaw(i, _) => {
402 (true, Some(LitKind::ByteStr(Rc::new(i.to_string().into_bytes()))))
407 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
408 -> Option<ast::LitKind> {
409 debug!("filtered_float_lit: {}, {:?}", data, suffix);
410 let suffix = match suffix {
411 Some(suffix) => suffix,
412 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
415 Some(match &*suffix.as_str() {
416 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
417 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
419 err!(diag, |span, diag| {
420 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
421 // if it looks like a width, lets try to be helpful.
422 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
423 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
425 let msg = format!("invalid suffix `{}` for float literal", suf);
426 diag.struct_span_err(span, &msg)
427 .help("valid suffixes are `f32` and `f64`")
432 ast::LitKind::FloatUnsuffixed(data)
436 pub fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
437 -> Option<ast::LitKind> {
438 debug!("float_lit: {:?}, {:?}", s, suffix);
439 // FIXME #2252: bounds checking float literals is deferred until trans
440 let s = s.chars().filter(|&c| c != '_').collect::<String>();
441 filtered_float_lit(Symbol::intern(&s), suffix, diag)
444 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
445 pub fn byte_lit(lit: &str) -> (u8, usize) {
446 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
449 (lit.as_bytes()[0], 1)
451 assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
452 let b = match lit.as_bytes()[1] {
461 match u64::from_str_radix(&lit[2..4], 16).ok() {
468 None => panic!(err(3))
476 pub fn byte_str_lit(lit: &str) -> Rc<Vec<u8>> {
477 let mut res = Vec::with_capacity(lit.len());
479 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
480 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
482 /// Eat everything up to a non-whitespace
483 fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
485 match it.peek().map(|x| x.1) {
486 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
494 // byte string literals *must* be ASCII, but the escapes don't have to be
495 let mut chars = lit.bytes().enumerate().peekable();
498 Some((i, b'\\')) => {
500 match chars.peek().expect(&em).1 {
501 b'\n' => eat(&mut chars),
504 if chars.peek().expect(&em).1 != b'\n' {
505 panic!("lexer accepted bare CR");
510 // otherwise, a normal escape
511 let (c, n) = byte_lit(&lit[i..]);
512 // we don't need to move past the first \
520 Some((i, b'\r')) => {
522 if chars.peek().expect(&em).1 != b'\n' {
523 panic!("lexer accepted bare CR");
528 Some((_, c)) => res.push(c),
536 pub fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
537 -> Option<ast::LitKind> {
538 // s can only be ascii, byte indexing is fine
540 let s2 = s.chars().filter(|&c| c != '_').collect::<String>();
543 debug!("integer_lit: {}, {:?}", s, suffix);
547 let mut ty = ast::LitIntType::Unsuffixed;
549 if char_at(s, 0) == '0' && s.len() > 1 {
550 match char_at(s, 1) {
558 // 1f64 and 2f32 etc. are valid float literals.
559 if let Some(suf) = suffix {
560 if looks_like_width_suffix(&['f'], &suf.as_str()) {
561 let err = match base {
562 16 => Some("hexadecimal float literal is not supported"),
563 8 => Some("octal float literal is not supported"),
564 2 => Some("binary float literal is not supported"),
567 if let Some(err) = err {
568 err!(diag, |span, diag| diag.span_err(span, err));
570 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
578 if let Some(suf) = suffix {
579 if suf.as_str().is_empty() {
580 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
582 ty = match &*suf.as_str() {
583 "isize" => ast::LitIntType::Signed(ast::IntTy::Is),
584 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
585 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
586 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
587 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
588 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
589 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Us),
590 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
591 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
592 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
593 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
594 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
596 // i<digits> and u<digits> look like widths, so lets
597 // give an error message along those lines
598 err!(diag, |span, diag| {
599 if looks_like_width_suffix(&['i', 'u'], suf) {
600 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
601 diag.struct_span_err(span, &msg)
602 .help("valid widths are 8, 16, 32, 64 and 128")
605 let msg = format!("invalid suffix `{}` for numeric literal", suf);
606 diag.struct_span_err(span, &msg)
607 .help("the suffix must be one of the integral types \
608 (`u32`, `isize`, etc)")
618 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
619 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
621 Some(match u128::from_str_radix(s, base) {
622 Ok(r) => ast::LitKind::Int(r, ty),
624 // small bases are lexed as if they were base 10, e.g, the string
625 // might be `0b10201`. This will cause the conversion above to fail,
626 // but these cases have errors in the lexer: we don't want to emit
627 // two errors, and we especially don't want to emit this error since
628 // it isn't necessarily true.
629 let already_errored = base < 10 &&
630 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
632 if !already_errored {
633 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
635 ast::LitKind::Int(0, ty)
643 use syntax_pos::{self, Span, BytePos, Pos, NO_EXPANSION};
644 use codemap::Spanned;
645 use ast::{self, Ident, PatKind};
647 use attr::first_attr_value_str_by_name;
649 use parse::parser::Parser;
650 use print::pprust::item_to_string;
652 use tokenstream::{self, TokenTree};
653 use util::parser_testing::{string_to_stream, string_to_parser};
654 use util::parser_testing::{string_to_expr, string_to_item, string_to_stmt};
657 // produce a syntax_pos::span
658 fn sp(a: u32, b: u32) -> Span {
659 Span {lo: BytePos(a), hi: BytePos(b), ctxt: NO_EXPANSION}
662 fn str2seg(s: &str, lo: u32, hi: u32) -> ast::PathSegment {
663 ast::PathSegment::from_ident(Ident::from_str(s), sp(lo, hi))
666 #[test] fn path_exprs_1() {
667 assert!(string_to_expr("a".to_string()) ==
669 id: ast::DUMMY_NODE_ID,
670 node: ast::ExprKind::Path(None, ast::Path {
672 segments: vec![str2seg("a", 0, 1)],
675 attrs: ThinVec::new(),
679 #[test] fn path_exprs_2 () {
680 assert!(string_to_expr("::a::b".to_string()) ==
682 id: ast::DUMMY_NODE_ID,
683 node: ast::ExprKind::Path(None, ast::Path {
685 segments: vec![ast::PathSegment::crate_root(),
690 attrs: ThinVec::new(),
695 #[test] fn bad_path_expr_1() {
696 string_to_expr("::abc::def::return".to_string());
699 // check the token-tree-ization of macros
701 fn string_to_tts_macro () {
703 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
704 let tts: &[TokenTree] = &tts[..];
706 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
709 Some(&TokenTree::Token(_, token::Ident(name_macro_rules))),
710 Some(&TokenTree::Token(_, token::Not)),
711 Some(&TokenTree::Token(_, token::Ident(name_zip))),
712 Some(&TokenTree::Delimited(_, ref macro_delimed)),
714 if name_macro_rules.name == "macro_rules"
715 && name_zip.name == "zip" => {
716 let tts = ¯o_delimed.stream().trees().collect::<Vec<_>>();
717 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
720 Some(&TokenTree::Delimited(_, ref first_delimed)),
721 Some(&TokenTree::Token(_, token::FatArrow)),
722 Some(&TokenTree::Delimited(_, ref second_delimed)),
724 if macro_delimed.delim == token::Paren => {
725 let tts = &first_delimed.stream().trees().collect::<Vec<_>>();
726 match (tts.len(), tts.get(0), tts.get(1)) {
729 Some(&TokenTree::Token(_, token::Dollar)),
730 Some(&TokenTree::Token(_, token::Ident(ident))),
732 if first_delimed.delim == token::Paren && ident.name == "a" => {},
733 _ => panic!("value 3: {:?}", *first_delimed),
735 let tts = &second_delimed.stream().trees().collect::<Vec<_>>();
736 match (tts.len(), tts.get(0), tts.get(1)) {
739 Some(&TokenTree::Token(_, token::Dollar)),
740 Some(&TokenTree::Token(_, token::Ident(ident))),
742 if second_delimed.delim == token::Paren
743 && ident.name == "a" => {},
744 _ => panic!("value 4: {:?}", *second_delimed),
747 _ => panic!("value 2: {:?}", *macro_delimed),
750 _ => panic!("value: {:?}",tts),
755 fn string_to_tts_1() {
756 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
758 let expected = TokenStream::concat(vec![
759 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"))).into(),
760 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"))).into(),
761 TokenTree::Delimited(
763 tokenstream::Delimited {
764 delim: token::DelimToken::Paren,
765 tts: TokenStream::concat(vec![
766 TokenTree::Token(sp(6, 7), token::Ident(Ident::from_str("b"))).into(),
767 TokenTree::Token(sp(8, 9), token::Colon).into(),
768 TokenTree::Token(sp(10, 13), token::Ident(Ident::from_str("i32"))).into(),
771 TokenTree::Delimited(
773 tokenstream::Delimited {
774 delim: token::DelimToken::Brace,
775 tts: TokenStream::concat(vec![
776 TokenTree::Token(sp(17, 18), token::Ident(Ident::from_str("b"))).into(),
777 TokenTree::Token(sp(18, 19), token::Semi).into(),
782 assert_eq!(tts, expected);
785 #[test] fn ret_expr() {
786 assert!(string_to_expr("return d".to_string()) ==
788 id: ast::DUMMY_NODE_ID,
789 node:ast::ExprKind::Ret(Some(P(ast::Expr{
790 id: ast::DUMMY_NODE_ID,
791 node:ast::ExprKind::Path(None, ast::Path{
793 segments: vec![str2seg("d", 7, 8)],
796 attrs: ThinVec::new(),
799 attrs: ThinVec::new(),
803 #[test] fn parse_stmt_1 () {
804 assert!(string_to_stmt("b;".to_string()) ==
806 node: ast::StmtKind::Expr(P(ast::Expr {
807 id: ast::DUMMY_NODE_ID,
808 node: ast::ExprKind::Path(None, ast::Path {
810 segments: vec![str2seg("b", 0, 1)],
813 attrs: ThinVec::new()})),
814 id: ast::DUMMY_NODE_ID,
819 fn parser_done(p: Parser){
820 assert_eq!(p.token.clone(), token::Eof);
823 #[test] fn parse_ident_pat () {
824 let sess = ParseSess::new(FilePathMapping::empty());
825 let mut parser = string_to_parser(&sess, "b".to_string());
826 assert!(panictry!(parser.parse_pat())
828 id: ast::DUMMY_NODE_ID,
829 node: PatKind::Ident(ast::BindingMode::ByValue(ast::Mutability::Immutable),
830 Spanned{ span:sp(0, 1),
831 node: Ident::from_str("b")
838 // check the contents of the tt manually:
839 #[test] fn parse_fundecl () {
840 // this test depends on the intern order of "fn" and "i32"
841 assert_eq!(string_to_item("fn a (b : i32) { b; }".to_string()),
843 P(ast::Item{ident:Ident::from_str("a"),
845 id: ast::DUMMY_NODE_ID,
846 node: ast::ItemKind::Fn(P(ast::FnDecl {
847 inputs: vec![ast::Arg{
848 ty: P(ast::Ty{id: ast::DUMMY_NODE_ID,
849 node: ast::TyKind::Path(None, ast::Path{
851 segments: vec![str2seg("i32", 10, 13)],
856 id: ast::DUMMY_NODE_ID,
857 node: PatKind::Ident(
858 ast::BindingMode::ByValue(ast::Mutability::Immutable),
861 node: Ident::from_str("b")},
866 id: ast::DUMMY_NODE_ID
868 output: ast::FunctionRetTy::Default(sp(15, 15)),
871 ast::Unsafety::Normal,
874 node: ast::Constness::NotConst,
877 ast::Generics{ // no idea on either of these:
878 lifetimes: Vec::new(),
879 ty_params: Vec::new(),
880 where_clause: ast::WhereClause {
881 id: ast::DUMMY_NODE_ID,
882 predicates: Vec::new(),
884 span: syntax_pos::DUMMY_SP,
887 stmts: vec![ast::Stmt {
888 node: ast::StmtKind::Semi(P(ast::Expr{
889 id: ast::DUMMY_NODE_ID,
890 node: ast::ExprKind::Path(None,
893 segments: vec![str2seg("b", 17, 18)],
896 attrs: ThinVec::new()})),
897 id: ast::DUMMY_NODE_ID,
899 id: ast::DUMMY_NODE_ID,
900 rules: ast::BlockCheckMode::Default, // no idea
903 vis: ast::Visibility::Inherited,
907 #[test] fn parse_use() {
908 let use_s = "use foo::bar::baz;";
909 let vitem = string_to_item(use_s.to_string()).unwrap();
910 let vitem_s = item_to_string(&vitem);
911 assert_eq!(&vitem_s[..], use_s);
913 let use_s = "use foo::bar as baz;";
914 let vitem = string_to_item(use_s.to_string()).unwrap();
915 let vitem_s = item_to_string(&vitem);
916 assert_eq!(&vitem_s[..], use_s);
919 #[test] fn parse_extern_crate() {
920 let ex_s = "extern crate foo;";
921 let vitem = string_to_item(ex_s.to_string()).unwrap();
922 let vitem_s = item_to_string(&vitem);
923 assert_eq!(&vitem_s[..], ex_s);
925 let ex_s = "extern crate foo as bar;";
926 let vitem = string_to_item(ex_s.to_string()).unwrap();
927 let vitem_s = item_to_string(&vitem);
928 assert_eq!(&vitem_s[..], ex_s);
931 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
932 let item = string_to_item(src.to_string()).unwrap();
934 struct PatIdentVisitor {
937 impl<'a> ::visit::Visitor<'a> for PatIdentVisitor {
938 fn visit_pat(&mut self, p: &'a ast::Pat) {
940 PatKind::Ident(_ , ref spannedident, _) => {
941 self.spans.push(spannedident.span.clone());
944 ::visit::walk_pat(self, p);
949 let mut v = PatIdentVisitor { spans: Vec::new() };
950 ::visit::walk_item(&mut v, &item);
954 #[test] fn span_of_self_arg_pat_idents_are_correct() {
956 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
957 "impl z { fn a (&mut self, &myarg: i32) {} }",
958 "impl z { fn a (&'a self, &myarg: i32) {} }",
959 "impl z { fn a (self, &myarg: i32) {} }",
960 "impl z { fn a (self: Foo, &myarg: i32) {} }",
964 let spans = get_spans_of_pat_idents(src);
965 let Span{ lo, hi, .. } = spans[0];
966 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
967 "\"{}\" != \"self\". src=\"{}\"",
968 &src[lo.to_usize()..hi.to_usize()], src)
972 #[test] fn parse_exprs () {
973 // just make sure that they parse....
974 string_to_expr("3 + 4".to_string());
975 string_to_expr("a::z.froob(b,&(987+3))".to_string());
978 #[test] fn attrs_fix_bug () {
979 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
980 -> Result<Box<Writer>, String> {
983 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
987 fn wb() -> c_int { O_WRONLY as c_int }
989 let mut fflags: c_int = wb();
993 #[test] fn crlf_doc_comments() {
994 let sess = ParseSess::new(FilePathMapping::empty());
996 let name = "<source>".to_string();
997 let source = "/// doc comment\r\nfn foo() {}".to_string();
998 let item = parse_item_from_source_str(name.clone(), source, &sess)
1000 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1001 assert_eq!(doc, "/// doc comment");
1003 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1004 let item = parse_item_from_source_str(name.clone(), source, &sess)
1006 let docs = item.attrs.iter().filter(|a| a.path == "doc")
1007 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1008 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1009 assert_eq!(&docs[..], b);
1011 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1012 let item = parse_item_from_source_str(name, source, &sess).unwrap().unwrap();
1013 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1014 assert_eq!(doc, "/** doc comment\n * with CRLF */");
1019 let sess = ParseSess::new(FilePathMapping::empty());
1020 let expr = parse::parse_expr_from_source_str("foo".to_string(),
1021 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
1023 let tts: Vec<_> = match expr.node {
1024 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
1025 _ => panic!("not a macro"),
1028 let span = tts.iter().rev().next().unwrap().span();
1030 match sess.codemap().span_to_snippet(span) {
1031 Ok(s) => assert_eq!(&s[..], "{ body }"),
1032 Err(_) => panic!("could not get snippet"),