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 rustc_data_structures::sync::{Lrc, Lock};
14 use ast::{self, CrateConfig};
15 use codemap::{CodeMap, FilePathMapping};
16 use syntax_pos::{Span, FileMap, FileName};
17 use errors::{Handler, ColorConfig, DiagnosticBuilder};
18 use feature_gate::UnstableFeatures;
19 use parse::parser::Parser;
23 use tokenstream::{TokenStream, TokenTree};
24 use diagnostics::plugin::ErrorMap;
27 use std::collections::HashSet;
29 use std::path::{Path, PathBuf};
32 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
43 /// Info about a parsing session.
44 pub struct ParseSess {
45 pub span_diagnostic: Handler,
46 pub unstable_features: UnstableFeatures,
47 pub config: CrateConfig,
48 pub missing_fragment_specifiers: Lock<HashSet<Span>>,
49 /// Places where raw identifiers were used. This is used for feature gating
51 pub raw_identifier_spans: Lock<Vec<Span>>,
52 /// The registered diagnostics codes
53 crate registered_diagnostics: Lock<ErrorMap>,
54 // Spans where a `mod foo;` statement was included in a non-mod.rs file.
55 // These are used to issue errors if the non_modrs_mods feature is not enabled.
56 pub non_modrs_mods: Lock<Vec<(ast::Ident, Span)>>,
57 /// Used to determine and report recursive mod inclusions
58 included_mod_stack: Lock<Vec<PathBuf>>,
59 code_map: Lrc<CodeMap>,
63 pub fn new(file_path_mapping: FilePathMapping) -> Self {
64 let cm = Lrc::new(CodeMap::new(file_path_mapping));
65 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
69 ParseSess::with_span_handler(handler, cm)
72 pub fn with_span_handler(handler: Handler, code_map: Lrc<CodeMap>) -> ParseSess {
74 span_diagnostic: handler,
75 unstable_features: UnstableFeatures::from_environment(),
76 config: HashSet::new(),
77 missing_fragment_specifiers: Lock::new(HashSet::new()),
78 raw_identifier_spans: Lock::new(Vec::new()),
79 registered_diagnostics: Lock::new(ErrorMap::new()),
80 included_mod_stack: Lock::new(vec![]),
82 non_modrs_mods: Lock::new(vec![]),
86 pub fn codemap(&self) -> &CodeMap {
92 pub struct Directory<'a> {
93 pub path: Cow<'a, Path>,
94 pub ownership: DirectoryOwnership,
97 #[derive(Copy, Clone)]
98 pub enum DirectoryOwnership {
100 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
101 relative: Option<ast::Ident>,
104 UnownedViaMod(bool /* legacy warnings? */),
107 // a bunch of utility functions of the form parse_<thing>_from_<source>
108 // where <thing> includes crate, expr, item, stmt, tts, and one that
109 // uses a HOF to parse anything, and <source> includes file and
112 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
113 let mut parser = new_parser_from_file(sess, input);
114 parser.parse_crate_mod()
117 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
118 -> PResult<'a, Vec<ast::Attribute>> {
119 let mut parser = new_parser_from_file(sess, input);
120 parser.parse_inner_attributes()
123 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
124 -> PResult<ast::Crate> {
125 new_parser_from_source_str(sess, name, source).parse_crate_mod()
128 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
129 -> PResult<Vec<ast::Attribute>> {
130 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
133 crate fn parse_expr_from_source_str(name: FileName, source: String, sess: &ParseSess)
134 -> PResult<P<ast::Expr>> {
135 new_parser_from_source_str(sess, name, source).parse_expr()
140 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
141 /// when a syntax error occurred.
142 crate fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
143 -> PResult<Option<P<ast::Item>>> {
144 new_parser_from_source_str(sess, name, source).parse_item()
147 crate fn parse_stmt_from_source_str(name: FileName, source: String, sess: &ParseSess)
148 -> PResult<Option<ast::Stmt>> {
149 new_parser_from_source_str(sess, name, source).parse_stmt()
152 pub fn parse_stream_from_source_str(name: FileName, source: String, sess: &ParseSess,
153 override_span: Option<Span>)
155 filemap_to_stream(sess, sess.codemap().new_filemap(name, source), override_span)
158 // Create a new parser from a source string
159 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
161 let mut parser = filemap_to_parser(sess, sess.codemap().new_filemap(name, source));
162 parser.recurse_into_file_modules = false;
166 /// Create a new parser, handling errors as appropriate
167 /// if the file doesn't exist
168 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
169 filemap_to_parser(sess, file_to_filemap(sess, path, None))
172 /// Given a session, a crate config, a path, and a span, add
173 /// the file at the given path to the codemap, and return a parser.
174 /// On an error, use the given span as the source of the problem.
175 crate fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
177 directory_ownership: DirectoryOwnership,
178 module_name: Option<String>,
179 sp: Span) -> Parser<'a> {
180 let mut p = filemap_to_parser(sess, file_to_filemap(sess, path, Some(sp)));
181 p.directory.ownership = directory_ownership;
182 p.root_module_name = module_name;
186 /// Given a filemap and config, return a parser
187 fn filemap_to_parser(sess: & ParseSess, filemap: Lrc<FileMap>) -> Parser {
188 let end_pos = filemap.end_pos;
189 let mut parser = stream_to_parser(sess, filemap_to_stream(sess, filemap, None));
191 if parser.token == token::Eof && parser.span.is_dummy() {
192 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
198 // must preserve old name for now, because quote! from the *existing*
199 // compiler expands into it
200 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser {
201 stream_to_parser(sess, tts.into_iter().collect())
207 /// Given a session and a path and an optional span (for error reporting),
208 /// add the path to the session's codemap and return the new filemap.
209 fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
211 match sess.codemap().load_file(path) {
212 Ok(filemap) => filemap,
214 let msg = format!("couldn't read {:?}: {}", path.display(), e);
216 Some(sp) => sess.span_diagnostic.span_fatal(sp, &msg).raise(),
217 None => sess.span_diagnostic.fatal(&msg).raise()
223 /// Given a filemap, produce a sequence of token-trees
224 pub fn filemap_to_stream(sess: &ParseSess, filemap: Lrc<FileMap>, override_span: Option<Span>)
226 let mut srdr = lexer::StringReader::new(sess, filemap, override_span);
228 panictry!(srdr.parse_all_token_trees())
231 /// Given stream and the `ParseSess`, produce a parser
232 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser {
233 Parser::new(sess, stream, None, true, false)
236 /// Parse a string representing a character literal into its final form.
237 /// Rather than just accepting/rejecting a given literal, unescapes it as
238 /// well. Can take any slice prefixed by a character escape. Returns the
239 /// character and the number of characters consumed.
240 fn char_lit(lit: &str, diag: Option<(Span, &Handler)>) -> (char, isize) {
243 // Handle non-escaped chars first.
244 if lit.as_bytes()[0] != b'\\' {
245 // If the first byte isn't '\\' it might part of a multi-byte char, so
246 // get the char with chars().
247 let c = lit.chars().next().unwrap();
251 // Handle escaped chars.
252 match lit.as_bytes()[1] as char {
261 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
262 let c = char::from_u32(v).unwrap();
266 assert_eq!(lit.as_bytes()[2], b'{');
267 let idx = lit.find('}').unwrap();
269 // All digits and '_' are ascii, so treat each byte as a char.
271 for c in lit[3..idx].bytes() {
272 let c = char::from(c);
274 let x = c.to_digit(16).unwrap();
275 v = v.checked_mul(16).unwrap().checked_add(x).unwrap();
278 let c = char::from_u32(v).unwrap_or_else(|| {
279 if let Some((span, diag)) = diag {
280 let mut diag = diag.struct_span_err(span, "invalid unicode character escape");
282 diag.help("unicode escape must be at most 10FFFF").emit();
284 diag.help("unicode escape must not be a surrogate").emit();
289 (c, (idx + 1) as isize)
291 _ => panic!("lexer should have rejected a bad character escape {}", lit)
295 /// Parse a string representing a string literal into its final form. Does
297 pub fn str_lit(lit: &str, diag: Option<(Span, &Handler)>) -> String {
298 debug!("str_lit: given {}", lit.escape_default());
299 let mut res = String::with_capacity(lit.len());
301 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
303 /// Eat everything up to a non-whitespace
304 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
306 match it.peek().map(|x| x.1) {
307 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
315 let mut chars = lit.char_indices().peekable();
316 while let Some((i, c)) = chars.next() {
319 let ch = chars.peek().unwrap_or_else(|| {
320 panic!("{}", error(i))
325 } else if ch == '\r' {
327 let ch = chars.peek().unwrap_or_else(|| {
328 panic!("{}", error(i))
332 panic!("lexer accepted bare CR");
336 // otherwise, a normal escape
337 let (c, n) = char_lit(&lit[i..], diag);
338 for _ in 0..n - 1 { // we don't need to move past the first \
345 let ch = chars.peek().unwrap_or_else(|| {
346 panic!("{}", error(i))
350 panic!("lexer accepted bare CR");
359 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
360 debug!("parse_str_lit: returning {}", res);
364 /// Parse a string representing a raw string literal into its final form. The
365 /// only operation this does is convert embedded CRLF into a single LF.
366 fn raw_str_lit(lit: &str) -> String {
367 debug!("raw_str_lit: given {}", lit.escape_default());
368 let mut res = String::with_capacity(lit.len());
370 let mut chars = lit.chars().peekable();
371 while let Some(c) = chars.next() {
373 if *chars.peek().unwrap() != '\n' {
374 panic!("lexer accepted bare CR");
387 // check if `s` looks like i32 or u1234 etc.
388 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
390 first_chars.contains(&char_at(s, 0)) &&
391 s[1..].chars().all(|c| '0' <= c && c <= '9')
395 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
397 Some(($span, $diag)) => { $($body)* }
403 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
404 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
408 token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
409 token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str(), diag).0))),
411 // There are some valid suffixes for integer and float literals,
412 // so all the handling is done internally.
413 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
414 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
416 token::Str_(mut sym) => {
417 // If there are no characters requiring special treatment we can
418 // reuse the symbol from the Token. Otherwise, we must generate a
419 // new symbol because the string in the LitKind is different to the
420 // string in the Token.
421 let s = &sym.as_str();
422 if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
423 sym = Symbol::intern(&str_lit(s, diag));
425 (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
427 token::StrRaw(mut sym, n) => {
429 let s = &sym.as_str();
430 if s.contains('\r') {
431 sym = Symbol::intern(&raw_str_lit(s));
433 (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
435 token::ByteStr(i) => {
436 (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
438 token::ByteStrRaw(i, _) => {
439 (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
444 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
445 -> Option<ast::LitKind> {
446 debug!("filtered_float_lit: {}, {:?}", data, suffix);
447 let suffix = match suffix {
448 Some(suffix) => suffix,
449 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
452 Some(match &*suffix.as_str() {
453 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
454 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
456 err!(diag, |span, diag| {
457 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
458 // if it looks like a width, lets try to be helpful.
459 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
460 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
462 let msg = format!("invalid suffix `{}` for float literal", suf);
463 diag.struct_span_err(span, &msg)
464 .help("valid suffixes are `f32` and `f64`")
469 ast::LitKind::FloatUnsuffixed(data)
473 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
474 -> Option<ast::LitKind> {
475 debug!("float_lit: {:?}, {:?}", s, suffix);
476 // FIXME #2252: bounds checking float literals is deferred until trans
477 let s = s.chars().filter(|&c| c != '_').collect::<String>();
478 filtered_float_lit(Symbol::intern(&s), suffix, diag)
481 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
482 fn byte_lit(lit: &str) -> (u8, usize) {
483 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
486 (lit.as_bytes()[0], 1)
488 assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
489 let b = match lit.as_bytes()[1] {
498 match u64::from_str_radix(&lit[2..4], 16).ok() {
505 None => panic!(err(3))
513 fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
514 let mut res = Vec::with_capacity(lit.len());
516 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
518 /// Eat everything up to a non-whitespace
519 fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
521 match it.peek().map(|x| x.1) {
522 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
530 // byte string literals *must* be ASCII, but the escapes don't have to be
531 let mut chars = lit.bytes().enumerate().peekable();
534 Some((i, b'\\')) => {
536 match chars.peek().expect(&em).1 {
537 b'\n' => eat(&mut chars),
540 if chars.peek().expect(&em).1 != b'\n' {
541 panic!("lexer accepted bare CR");
546 // otherwise, a normal escape
547 let (c, n) = byte_lit(&lit[i..]);
548 // we don't need to move past the first \
556 Some((i, b'\r')) => {
558 if chars.peek().expect(&em).1 != b'\n' {
559 panic!("lexer accepted bare CR");
564 Some((_, c)) => res.push(c),
572 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
573 -> Option<ast::LitKind> {
574 // s can only be ascii, byte indexing is fine
576 let s2 = s.chars().filter(|&c| c != '_').collect::<String>();
579 debug!("integer_lit: {}, {:?}", s, suffix);
583 let mut ty = ast::LitIntType::Unsuffixed;
585 if char_at(s, 0) == '0' && s.len() > 1 {
586 match char_at(s, 1) {
594 // 1f64 and 2f32 etc. are valid float literals.
595 if let Some(suf) = suffix {
596 if looks_like_width_suffix(&['f'], &suf.as_str()) {
597 let err = match base {
598 16 => Some("hexadecimal float literal is not supported"),
599 8 => Some("octal float literal is not supported"),
600 2 => Some("binary float literal is not supported"),
603 if let Some(err) = err {
604 err!(diag, |span, diag| diag.span_err(span, err));
606 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
614 if let Some(suf) = suffix {
615 if suf.as_str().is_empty() {
616 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
618 ty = match &*suf.as_str() {
619 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
620 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
621 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
622 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
623 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
624 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
625 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
626 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
627 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
628 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
629 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
630 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
632 // i<digits> and u<digits> look like widths, so lets
633 // give an error message along those lines
634 err!(diag, |span, diag| {
635 if looks_like_width_suffix(&['i', 'u'], suf) {
636 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
637 diag.struct_span_err(span, &msg)
638 .help("valid widths are 8, 16, 32, 64 and 128")
641 let msg = format!("invalid suffix `{}` for numeric literal", suf);
642 diag.struct_span_err(span, &msg)
643 .help("the suffix must be one of the integral types \
644 (`u32`, `isize`, etc)")
654 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
655 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
657 Some(match u128::from_str_radix(s, base) {
658 Ok(r) => ast::LitKind::Int(r, ty),
660 // small bases are lexed as if they were base 10, e.g, the string
661 // might be `0b10201`. This will cause the conversion above to fail,
662 // but these cases have errors in the lexer: we don't want to emit
663 // two errors, and we especially don't want to emit this error since
664 // it isn't necessarily true.
665 let already_errored = base < 10 &&
666 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
668 if !already_errored {
669 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
671 ast::LitKind::Int(0, ty)
676 /// `SeqSep` : a sequence separator (token)
677 /// and whether a trailing separator is allowed.
679 pub sep: Option<token::Token>,
680 pub trailing_sep_allowed: bool,
684 pub fn trailing_allowed(t: token::Token) -> SeqSep {
687 trailing_sep_allowed: true,
691 pub fn none() -> SeqSep {
694 trailing_sep_allowed: false,
702 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
703 use ast::{self, Ident, PatKind};
704 use attr::first_attr_value_str_by_name;
706 use print::pprust::item_to_string;
707 use tokenstream::{self, TokenTree};
708 use util::parser_testing::string_to_stream;
709 use util::parser_testing::{string_to_expr, string_to_item};
712 // produce a syntax_pos::span
713 fn sp(a: u32, b: u32) -> Span {
714 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
718 #[test] fn bad_path_expr_1() {
720 string_to_expr("::abc::def::return".to_string());
724 // check the token-tree-ization of macros
726 fn string_to_tts_macro () {
729 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
730 let tts: &[TokenTree] = &tts[..];
732 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
735 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
736 Some(&TokenTree::Token(_, token::Not)),
737 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
738 Some(&TokenTree::Delimited(_, ref macro_delimed)),
740 if name_macro_rules.name == "macro_rules"
741 && name_zip.name == "zip" => {
742 let tts = ¯o_delimed.stream().trees().collect::<Vec<_>>();
743 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
746 Some(&TokenTree::Delimited(_, ref first_delimed)),
747 Some(&TokenTree::Token(_, token::FatArrow)),
748 Some(&TokenTree::Delimited(_, ref second_delimed)),
750 if macro_delimed.delim == token::Paren => {
751 let tts = &first_delimed.stream().trees().collect::<Vec<_>>();
752 match (tts.len(), tts.get(0), tts.get(1)) {
755 Some(&TokenTree::Token(_, token::Dollar)),
756 Some(&TokenTree::Token(_, token::Ident(ident, false))),
758 if first_delimed.delim == token::Paren && ident.name == "a" => {},
759 _ => panic!("value 3: {:?}", *first_delimed),
761 let tts = &second_delimed.stream().trees().collect::<Vec<_>>();
762 match (tts.len(), tts.get(0), tts.get(1)) {
765 Some(&TokenTree::Token(_, token::Dollar)),
766 Some(&TokenTree::Token(_, token::Ident(ident, false))),
768 if second_delimed.delim == token::Paren
769 && ident.name == "a" => {},
770 _ => panic!("value 4: {:?}", *second_delimed),
773 _ => panic!("value 2: {:?}", *macro_delimed),
776 _ => panic!("value: {:?}",tts),
782 fn string_to_tts_1() {
784 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
786 let expected = TokenStream::concat(vec![
787 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
788 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
789 TokenTree::Delimited(
791 tokenstream::Delimited {
792 delim: token::DelimToken::Paren,
793 tts: TokenStream::concat(vec![
794 TokenTree::Token(sp(6, 7),
795 token::Ident(Ident::from_str("b"), false)).into(),
796 TokenTree::Token(sp(8, 9), token::Colon).into(),
797 TokenTree::Token(sp(10, 13),
798 token::Ident(Ident::from_str("i32"), false)).into(),
801 TokenTree::Delimited(
803 tokenstream::Delimited {
804 delim: token::DelimToken::Brace,
805 tts: TokenStream::concat(vec![
806 TokenTree::Token(sp(17, 18),
807 token::Ident(Ident::from_str("b"), false)).into(),
808 TokenTree::Token(sp(18, 19), token::Semi).into(),
813 assert_eq!(tts, expected);
817 #[test] fn parse_use() {
819 let use_s = "use foo::bar::baz;";
820 let vitem = string_to_item(use_s.to_string()).unwrap();
821 let vitem_s = item_to_string(&vitem);
822 assert_eq!(&vitem_s[..], use_s);
824 let use_s = "use foo::bar as baz;";
825 let vitem = string_to_item(use_s.to_string()).unwrap();
826 let vitem_s = item_to_string(&vitem);
827 assert_eq!(&vitem_s[..], use_s);
831 #[test] fn parse_extern_crate() {
833 let ex_s = "extern crate foo;";
834 let vitem = string_to_item(ex_s.to_string()).unwrap();
835 let vitem_s = item_to_string(&vitem);
836 assert_eq!(&vitem_s[..], ex_s);
838 let ex_s = "extern crate foo as bar;";
839 let vitem = string_to_item(ex_s.to_string()).unwrap();
840 let vitem_s = item_to_string(&vitem);
841 assert_eq!(&vitem_s[..], ex_s);
845 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
846 let item = string_to_item(src.to_string()).unwrap();
848 struct PatIdentVisitor {
851 impl<'a> ::visit::Visitor<'a> for PatIdentVisitor {
852 fn visit_pat(&mut self, p: &'a ast::Pat) {
854 PatKind::Ident(_ , ref spannedident, _) => {
855 self.spans.push(spannedident.span.clone());
858 ::visit::walk_pat(self, p);
863 let mut v = PatIdentVisitor { spans: Vec::new() };
864 ::visit::walk_item(&mut v, &item);
868 #[test] fn span_of_self_arg_pat_idents_are_correct() {
871 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
872 "impl z { fn a (&mut self, &myarg: i32) {} }",
873 "impl z { fn a (&'a self, &myarg: i32) {} }",
874 "impl z { fn a (self, &myarg: i32) {} }",
875 "impl z { fn a (self: Foo, &myarg: i32) {} }",
879 let spans = get_spans_of_pat_idents(src);
880 let (lo, hi) = (spans[0].lo(), spans[0].hi());
881 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
882 "\"{}\" != \"self\". src=\"{}\"",
883 &src[lo.to_usize()..hi.to_usize()], src)
888 #[test] fn parse_exprs () {
890 // just make sure that they parse....
891 string_to_expr("3 + 4".to_string());
892 string_to_expr("a::z.froob(b,&(987+3))".to_string());
896 #[test] fn attrs_fix_bug () {
898 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
899 -> Result<Box<Writer>, String> {
902 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
906 fn wb() -> c_int { O_WRONLY as c_int }
908 let mut fflags: c_int = wb();
913 #[test] fn crlf_doc_comments() {
915 let sess = ParseSess::new(FilePathMapping::empty());
917 let name = FileName::Custom("source".to_string());
918 let source = "/// doc comment\r\nfn foo() {}".to_string();
919 let item = parse_item_from_source_str(name.clone(), source, &sess)
921 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
922 assert_eq!(doc, "/// doc comment");
924 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
925 let item = parse_item_from_source_str(name.clone(), source, &sess)
927 let docs = item.attrs.iter().filter(|a| a.path == "doc")
928 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
929 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
930 assert_eq!(&docs[..], b);
932 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
933 let item = parse_item_from_source_str(name, source, &sess).unwrap().unwrap();
934 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
935 assert_eq!(doc, "/** doc comment\n * with CRLF */");
942 let sess = ParseSess::new(FilePathMapping::empty());
943 let expr = parse::parse_expr_from_source_str(PathBuf::from("foo").into(),
944 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
946 let tts: Vec<_> = match expr.node {
947 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
948 _ => panic!("not a macro"),
951 let span = tts.iter().rev().next().unwrap().span();
953 match sess.codemap().span_to_snippet(span) {
954 Ok(s) => assert_eq!(&s[..], "{ body }"),
955 Err(_) => panic!("could not get snippet"),
960 // This tests that when parsing a string (rather than a file) we don't try
961 // and read in a file for a module declaration and just parse a stub.
962 // See `recurse_into_file_modules` in the parser.
964 fn out_of_line_mod() {
966 let sess = ParseSess::new(FilePathMapping::empty());
967 let item = parse_item_from_source_str(
968 PathBuf::from("foo").into(),
969 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
973 if let ast::ItemKind::Mod(ref m) = item.node {
974 assert!(m.items.len() == 2);