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::{self, Span, FileMap, NO_EXPANSION, 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;
26 use std::collections::HashSet;
28 use std::path::{Path, PathBuf};
31 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 pub 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 {
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 pub 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 pub 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 pub fn parse_meta_from_source_str(name: FileName, source: String, sess: &ParseSess)
148 -> PResult<ast::MetaItem> {
149 new_parser_from_source_str(sess, name, source).parse_meta_item()
152 pub fn parse_stmt_from_source_str(name: FileName, source: String, sess: &ParseSess)
153 -> PResult<Option<ast::Stmt>> {
154 new_parser_from_source_str(sess, name, source).parse_stmt()
157 pub fn parse_stream_from_source_str(name: FileName, source: String, sess: &ParseSess,
158 override_span: Option<Span>)
160 filemap_to_stream(sess, sess.codemap().new_filemap(name, source), override_span)
163 // Create a new parser from a source string
164 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
166 let mut parser = filemap_to_parser(sess, sess.codemap().new_filemap(name, source));
167 parser.recurse_into_file_modules = false;
171 /// Create a new parser, handling errors as appropriate
172 /// if the file doesn't exist
173 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
174 filemap_to_parser(sess, file_to_filemap(sess, path, None))
177 /// Given a session, a crate config, a path, and a span, add
178 /// the file at the given path to the codemap, and return a parser.
179 /// On an error, use the given span as the source of the problem.
180 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
182 directory_ownership: DirectoryOwnership,
183 module_name: Option<String>,
184 sp: Span) -> Parser<'a> {
185 let mut p = filemap_to_parser(sess, file_to_filemap(sess, path, Some(sp)));
186 p.directory.ownership = directory_ownership;
187 p.root_module_name = module_name;
191 /// Given a filemap and config, return a parser
192 pub fn filemap_to_parser(sess: & ParseSess, filemap: Lrc<FileMap>) -> Parser {
193 let end_pos = filemap.end_pos;
194 let mut parser = stream_to_parser(sess, filemap_to_stream(sess, filemap, None));
196 if parser.token == token::Eof && parser.span == syntax_pos::DUMMY_SP {
197 parser.span = Span::new(end_pos, end_pos, NO_EXPANSION);
203 // must preserve old name for now, because quote! from the *existing*
204 // compiler expands into it
205 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser {
206 stream_to_parser(sess, tts.into_iter().collect())
212 /// Given a session and a path and an optional span (for error reporting),
213 /// add the path to the session's codemap and return the new filemap.
214 fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
216 match sess.codemap().load_file(path) {
217 Ok(filemap) => filemap,
219 let msg = format!("couldn't read {:?}: {}", path.display(), e);
221 Some(sp) => sess.span_diagnostic.span_fatal(sp, &msg).raise(),
222 None => sess.span_diagnostic.fatal(&msg).raise()
228 /// Given a filemap, produce a sequence of token-trees
229 pub fn filemap_to_stream(sess: &ParseSess, filemap: Lrc<FileMap>, override_span: Option<Span>)
231 let mut srdr = lexer::StringReader::new(sess, filemap);
232 srdr.override_span = override_span;
234 panictry!(srdr.parse_all_token_trees())
237 /// Given stream and the `ParseSess`, produce a parser
238 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser {
239 Parser::new(sess, stream, None, true, false)
242 /// Parse a string representing a character literal into its final form.
243 /// Rather than just accepting/rejecting a given literal, unescapes it as
244 /// well. Can take any slice prefixed by a character escape. Returns the
245 /// character and the number of characters consumed.
246 pub fn char_lit(lit: &str, diag: Option<(Span, &Handler)>) -> (char, isize) {
249 // Handle non-escaped chars first.
250 if lit.as_bytes()[0] != b'\\' {
251 // If the first byte isn't '\\' it might part of a multi-byte char, so
252 // get the char with chars().
253 let c = lit.chars().next().unwrap();
257 // Handle escaped chars.
258 match lit.as_bytes()[1] as char {
267 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
268 let c = char::from_u32(v).unwrap();
272 assert_eq!(lit.as_bytes()[2], b'{');
273 let idx = lit.find('}').unwrap();
275 // All digits and '_' are ascii, so treat each byte as a char.
277 for c in lit[3..idx].bytes() {
278 let c = char::from(c);
280 let x = c.to_digit(16).unwrap();
281 v = v.checked_mul(16).unwrap().checked_add(x).unwrap();
284 let c = char::from_u32(v).unwrap_or_else(|| {
285 if let Some((span, diag)) = diag {
286 let mut diag = diag.struct_span_err(span, "invalid unicode character escape");
288 diag.help("unicode escape must be at most 10FFFF").emit();
290 diag.help("unicode escape must not be a surrogate").emit();
295 (c, (idx + 1) as isize)
297 _ => panic!("lexer should have rejected a bad character escape {}", lit)
301 pub fn escape_default(s: &str) -> String {
302 s.chars().map(char::escape_default).flat_map(|x| x).collect()
305 /// Parse a string representing a string literal into its final form. Does
307 pub fn str_lit(lit: &str, diag: Option<(Span, &Handler)>) -> String {
308 debug!("parse_str_lit: given {}", escape_default(lit));
309 let mut res = String::with_capacity(lit.len());
311 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
313 /// Eat everything up to a non-whitespace
314 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
316 match it.peek().map(|x| x.1) {
317 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
325 let mut chars = lit.char_indices().peekable();
326 while let Some((i, c)) = chars.next() {
329 let ch = chars.peek().unwrap_or_else(|| {
330 panic!("{}", error(i))
335 } else if ch == '\r' {
337 let ch = chars.peek().unwrap_or_else(|| {
338 panic!("{}", error(i))
342 panic!("lexer accepted bare CR");
346 // otherwise, a normal escape
347 let (c, n) = char_lit(&lit[i..], diag);
348 for _ in 0..n - 1 { // we don't need to move past the first \
355 let ch = chars.peek().unwrap_or_else(|| {
356 panic!("{}", error(i))
360 panic!("lexer accepted bare CR");
369 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
370 debug!("parse_str_lit: returning {}", res);
374 /// Parse a string representing a raw string literal into its final form. The
375 /// only operation this does is convert embedded CRLF into a single LF.
376 pub fn raw_str_lit(lit: &str) -> String {
377 debug!("raw_str_lit: given {}", escape_default(lit));
378 let mut res = String::with_capacity(lit.len());
380 let mut chars = lit.chars().peekable();
381 while let Some(c) = chars.next() {
383 if *chars.peek().unwrap() != '\n' {
384 panic!("lexer accepted bare CR");
397 // check if `s` looks like i32 or u1234 etc.
398 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
400 first_chars.contains(&char_at(s, 0)) &&
401 s[1..].chars().all(|c| '0' <= c && c <= '9')
405 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
407 Some(($span, $diag)) => { $($body)* }
413 pub fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
414 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
418 token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
419 token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str(), diag).0))),
421 // There are some valid suffixes for integer and float literals,
422 // so all the handling is done internally.
423 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
424 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
427 let s = Symbol::intern(&str_lit(&s.as_str(), diag));
428 (true, Some(LitKind::Str(s, ast::StrStyle::Cooked)))
430 token::StrRaw(s, n) => {
431 let s = Symbol::intern(&raw_str_lit(&s.as_str()));
432 (true, Some(LitKind::Str(s, ast::StrStyle::Raw(n))))
434 token::ByteStr(i) => {
435 (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
437 token::ByteStrRaw(i, _) => {
438 (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
443 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
444 -> Option<ast::LitKind> {
445 debug!("filtered_float_lit: {}, {:?}", data, suffix);
446 let suffix = match suffix {
447 Some(suffix) => suffix,
448 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
451 Some(match &*suffix.as_str() {
452 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
453 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
455 err!(diag, |span, diag| {
456 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
457 // if it looks like a width, lets try to be helpful.
458 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
459 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
461 let msg = format!("invalid suffix `{}` for float literal", suf);
462 diag.struct_span_err(span, &msg)
463 .help("valid suffixes are `f32` and `f64`")
468 ast::LitKind::FloatUnsuffixed(data)
472 pub fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
473 -> Option<ast::LitKind> {
474 debug!("float_lit: {:?}, {:?}", s, suffix);
475 // FIXME #2252: bounds checking float literals is deferred until trans
476 let s = s.chars().filter(|&c| c != '_').collect::<String>();
477 filtered_float_lit(Symbol::intern(&s), suffix, diag)
480 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
481 pub fn byte_lit(lit: &str) -> (u8, usize) {
482 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
485 (lit.as_bytes()[0], 1)
487 assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
488 let b = match lit.as_bytes()[1] {
497 match u64::from_str_radix(&lit[2..4], 16).ok() {
504 None => panic!(err(3))
512 pub fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
513 let mut res = Vec::with_capacity(lit.len());
515 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
517 /// Eat everything up to a non-whitespace
518 fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
520 match it.peek().map(|x| x.1) {
521 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
529 // byte string literals *must* be ASCII, but the escapes don't have to be
530 let mut chars = lit.bytes().enumerate().peekable();
533 Some((i, b'\\')) => {
535 match chars.peek().expect(&em).1 {
536 b'\n' => eat(&mut chars),
539 if chars.peek().expect(&em).1 != b'\n' {
540 panic!("lexer accepted bare CR");
545 // otherwise, a normal escape
546 let (c, n) = byte_lit(&lit[i..]);
547 // we don't need to move past the first \
555 Some((i, b'\r')) => {
557 if chars.peek().expect(&em).1 != b'\n' {
558 panic!("lexer accepted bare CR");
563 Some((_, c)) => res.push(c),
571 pub fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
572 -> Option<ast::LitKind> {
573 // s can only be ascii, byte indexing is fine
575 let s2 = s.chars().filter(|&c| c != '_').collect::<String>();
578 debug!("integer_lit: {}, {:?}", s, suffix);
582 let mut ty = ast::LitIntType::Unsuffixed;
584 if char_at(s, 0) == '0' && s.len() > 1 {
585 match char_at(s, 1) {
593 // 1f64 and 2f32 etc. are valid float literals.
594 if let Some(suf) = suffix {
595 if looks_like_width_suffix(&['f'], &suf.as_str()) {
596 let err = match base {
597 16 => Some("hexadecimal float literal is not supported"),
598 8 => Some("octal float literal is not supported"),
599 2 => Some("binary float literal is not supported"),
602 if let Some(err) = err {
603 err!(diag, |span, diag| diag.span_err(span, err));
605 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
613 if let Some(suf) = suffix {
614 if suf.as_str().is_empty() {
615 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
617 ty = match &*suf.as_str() {
618 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
619 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
620 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
621 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
622 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
623 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
624 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
625 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
626 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
627 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
628 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
629 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
631 // i<digits> and u<digits> look like widths, so lets
632 // give an error message along those lines
633 err!(diag, |span, diag| {
634 if looks_like_width_suffix(&['i', 'u'], suf) {
635 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
636 diag.struct_span_err(span, &msg)
637 .help("valid widths are 8, 16, 32, 64 and 128")
640 let msg = format!("invalid suffix `{}` for numeric literal", suf);
641 diag.struct_span_err(span, &msg)
642 .help("the suffix must be one of the integral types \
643 (`u32`, `isize`, etc)")
653 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
654 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
656 Some(match u128::from_str_radix(s, base) {
657 Ok(r) => ast::LitKind::Int(r, ty),
659 // small bases are lexed as if they were base 10, e.g, the string
660 // might be `0b10201`. This will cause the conversion above to fail,
661 // but these cases have errors in the lexer: we don't want to emit
662 // two errors, and we especially don't want to emit this error since
663 // it isn't necessarily true.
664 let already_errored = base < 10 &&
665 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
667 if !already_errored {
668 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
670 ast::LitKind::Int(0, ty)
678 use syntax_pos::{self, Span, BytePos, Pos, NO_EXPANSION};
679 use codemap::{respan, Spanned};
680 use ast::{self, Ident, PatKind};
681 use rustc_target::spec::abi::Abi;
682 use attr::first_attr_value_str_by_name;
684 use parse::parser::Parser;
685 use print::pprust::item_to_string;
687 use tokenstream::{self, TokenTree};
688 use util::parser_testing::{string_to_stream, string_to_parser};
689 use util::parser_testing::{string_to_expr, string_to_item, string_to_stmt};
693 // produce a syntax_pos::span
694 fn sp(a: u32, b: u32) -> Span {
695 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
698 fn str2seg(s: &str, lo: u32, hi: u32) -> ast::PathSegment {
699 ast::PathSegment::from_ident(Ident::new(Symbol::intern(s), sp(lo, hi)))
702 #[test] fn path_exprs_1() {
704 assert!(string_to_expr("a".to_string()) ==
706 id: ast::DUMMY_NODE_ID,
707 node: ast::ExprKind::Path(None, ast::Path {
709 segments: vec![str2seg("a", 0, 1)],
712 attrs: ThinVec::new(),
717 #[test] fn path_exprs_2 () {
719 assert!(string_to_expr("::a::b".to_string()) ==
721 id: ast::DUMMY_NODE_ID,
722 node: ast::ExprKind::Path(None, ast::Path {
724 segments: vec![ast::PathSegment::crate_root(sp(0, 0)),
729 attrs: ThinVec::new(),
735 #[test] fn bad_path_expr_1() {
737 string_to_expr("::abc::def::return".to_string());
741 // check the token-tree-ization of macros
743 fn string_to_tts_macro () {
746 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
747 let tts: &[TokenTree] = &tts[..];
749 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
752 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
753 Some(&TokenTree::Token(_, token::Not)),
754 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
755 Some(&TokenTree::Delimited(_, ref macro_delimed)),
757 if name_macro_rules.name == "macro_rules"
758 && name_zip.name == "zip" => {
759 let tts = ¯o_delimed.stream().trees().collect::<Vec<_>>();
760 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
763 Some(&TokenTree::Delimited(_, ref first_delimed)),
764 Some(&TokenTree::Token(_, token::FatArrow)),
765 Some(&TokenTree::Delimited(_, ref second_delimed)),
767 if macro_delimed.delim == token::Paren => {
768 let tts = &first_delimed.stream().trees().collect::<Vec<_>>();
769 match (tts.len(), tts.get(0), tts.get(1)) {
772 Some(&TokenTree::Token(_, token::Dollar)),
773 Some(&TokenTree::Token(_, token::Ident(ident, false))),
775 if first_delimed.delim == token::Paren && ident.name == "a" => {},
776 _ => panic!("value 3: {:?}", *first_delimed),
778 let tts = &second_delimed.stream().trees().collect::<Vec<_>>();
779 match (tts.len(), tts.get(0), tts.get(1)) {
782 Some(&TokenTree::Token(_, token::Dollar)),
783 Some(&TokenTree::Token(_, token::Ident(ident, false))),
785 if second_delimed.delim == token::Paren
786 && ident.name == "a" => {},
787 _ => panic!("value 4: {:?}", *second_delimed),
790 _ => panic!("value 2: {:?}", *macro_delimed),
793 _ => panic!("value: {:?}",tts),
799 fn string_to_tts_1() {
801 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
803 let expected = TokenStream::concat(vec![
804 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
805 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
806 TokenTree::Delimited(
808 tokenstream::Delimited {
809 delim: token::DelimToken::Paren,
810 tts: TokenStream::concat(vec![
811 TokenTree::Token(sp(6, 7),
812 token::Ident(Ident::from_str("b"), false)).into(),
813 TokenTree::Token(sp(8, 9), token::Colon).into(),
814 TokenTree::Token(sp(10, 13),
815 token::Ident(Ident::from_str("i32"), false)).into(),
818 TokenTree::Delimited(
820 tokenstream::Delimited {
821 delim: token::DelimToken::Brace,
822 tts: TokenStream::concat(vec![
823 TokenTree::Token(sp(17, 18),
824 token::Ident(Ident::from_str("b"), false)).into(),
825 TokenTree::Token(sp(18, 19), token::Semi).into(),
830 assert_eq!(tts, expected);
834 #[test] fn ret_expr() {
836 assert!(string_to_expr("return d".to_string()) ==
838 id: ast::DUMMY_NODE_ID,
839 node:ast::ExprKind::Ret(Some(P(ast::Expr{
840 id: ast::DUMMY_NODE_ID,
841 node:ast::ExprKind::Path(None, ast::Path{
843 segments: vec![str2seg("d", 7, 8)],
846 attrs: ThinVec::new(),
849 attrs: ThinVec::new(),
854 #[test] fn parse_stmt_1 () {
856 assert!(string_to_stmt("b;".to_string()) ==
858 node: ast::StmtKind::Expr(P(ast::Expr {
859 id: ast::DUMMY_NODE_ID,
860 node: ast::ExprKind::Path(None, ast::Path {
862 segments: vec![str2seg("b", 0, 1)],
865 attrs: ThinVec::new()})),
866 id: ast::DUMMY_NODE_ID,
871 fn parser_done(p: Parser){
872 assert_eq!(p.token.clone(), token::Eof);
875 #[test] fn parse_ident_pat () {
877 let sess = ParseSess::new(FilePathMapping::empty());
878 let mut parser = string_to_parser(&sess, "b".to_string());
879 assert!(panictry!(parser.parse_pat())
881 id: ast::DUMMY_NODE_ID,
882 node: PatKind::Ident(ast::BindingMode::ByValue(ast::Mutability::Immutable),
883 Ident::new(Symbol::intern("b"), sp(0, 1)),
890 // check the contents of the tt manually:
891 #[test] fn parse_fundecl () {
893 // this test depends on the intern order of "fn" and "i32"
894 let item = string_to_item("fn a (b : i32) { b; }".to_string()).map(|m| {
902 P(ast::Item{ident:Ident::from_str("a"),
904 id: ast::DUMMY_NODE_ID,
906 node: ast::ItemKind::Fn(P(ast::FnDecl {
907 inputs: vec![ast::Arg{
908 ty: P(ast::Ty{id: ast::DUMMY_NODE_ID,
909 node: ast::TyKind::Path(None, ast::Path{
911 segments: vec![str2seg("i32", 10, 13)],
916 id: ast::DUMMY_NODE_ID,
917 node: PatKind::Ident(
918 ast::BindingMode::ByValue(
919 ast::Mutability::Immutable),
920 Ident::new(Symbol::intern("b"), sp(6, 7)),
925 id: ast::DUMMY_NODE_ID
927 output: ast::FunctionRetTy::Default(sp(15, 15)),
930 ast::Unsafety::Normal,
933 node: ast::Constness::NotConst,
938 where_clause: ast::WhereClause {
939 id: ast::DUMMY_NODE_ID,
940 predicates: Vec::new(),
941 span: syntax_pos::DUMMY_SP,
943 span: syntax_pos::DUMMY_SP,
946 stmts: vec![ast::Stmt {
947 node: ast::StmtKind::Semi(P(ast::Expr{
948 id: ast::DUMMY_NODE_ID,
949 node: ast::ExprKind::Path(None,
952 segments: vec![str2seg("b", 17, 18)],
955 attrs: ThinVec::new()})),
956 id: ast::DUMMY_NODE_ID,
958 id: ast::DUMMY_NODE_ID,
959 rules: ast::BlockCheckMode::Default, // no idea
963 vis: respan(sp(0, 0), ast::VisibilityKind::Inherited),
968 #[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);
982 #[test] fn parse_extern_crate() {
984 let ex_s = "extern crate foo;";
985 let vitem = string_to_item(ex_s.to_string()).unwrap();
986 let vitem_s = item_to_string(&vitem);
987 assert_eq!(&vitem_s[..], ex_s);
989 let ex_s = "extern crate foo as bar;";
990 let vitem = string_to_item(ex_s.to_string()).unwrap();
991 let vitem_s = item_to_string(&vitem);
992 assert_eq!(&vitem_s[..], ex_s);
996 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
997 let item = string_to_item(src.to_string()).unwrap();
999 struct PatIdentVisitor {
1002 impl<'a> ::visit::Visitor<'a> for PatIdentVisitor {
1003 fn visit_pat(&mut self, p: &'a ast::Pat) {
1005 PatKind::Ident(_ , ref spannedident, _) => {
1006 self.spans.push(spannedident.span.clone());
1009 ::visit::walk_pat(self, p);
1014 let mut v = PatIdentVisitor { spans: Vec::new() };
1015 ::visit::walk_item(&mut v, &item);
1019 #[test] fn span_of_self_arg_pat_idents_are_correct() {
1022 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
1023 "impl z { fn a (&mut self, &myarg: i32) {} }",
1024 "impl z { fn a (&'a self, &myarg: i32) {} }",
1025 "impl z { fn a (self, &myarg: i32) {} }",
1026 "impl z { fn a (self: Foo, &myarg: i32) {} }",
1030 let spans = get_spans_of_pat_idents(src);
1031 let (lo, hi) = (spans[0].lo(), spans[0].hi());
1032 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
1033 "\"{}\" != \"self\". src=\"{}\"",
1034 &src[lo.to_usize()..hi.to_usize()], src)
1039 #[test] fn parse_exprs () {
1041 // just make sure that they parse....
1042 string_to_expr("3 + 4".to_string());
1043 string_to_expr("a::z.froob(b,&(987+3))".to_string());
1047 #[test] fn attrs_fix_bug () {
1049 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
1050 -> Result<Box<Writer>, String> {
1053 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1057 fn wb() -> c_int { O_WRONLY as c_int }
1059 let mut fflags: c_int = wb();
1064 #[test] fn crlf_doc_comments() {
1066 let sess = ParseSess::new(FilePathMapping::empty());
1068 let name = FileName::Custom("source".to_string());
1069 let source = "/// doc comment\r\nfn foo() {}".to_string();
1070 let item = parse_item_from_source_str(name.clone(), source, &sess)
1072 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1073 assert_eq!(doc, "/// doc comment");
1075 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1076 let item = parse_item_from_source_str(name.clone(), source, &sess)
1078 let docs = item.attrs.iter().filter(|a| a.path == "doc")
1079 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1080 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1081 assert_eq!(&docs[..], b);
1083 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1084 let item = parse_item_from_source_str(name, source, &sess).unwrap().unwrap();
1085 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1086 assert_eq!(doc, "/** doc comment\n * with CRLF */");
1093 let sess = ParseSess::new(FilePathMapping::empty());
1094 let expr = parse::parse_expr_from_source_str(PathBuf::from("foo").into(),
1095 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
1097 let tts: Vec<_> = match expr.node {
1098 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
1099 _ => panic!("not a macro"),
1102 let span = tts.iter().rev().next().unwrap().span();
1104 match sess.codemap().span_to_snippet(span) {
1105 Ok(s) => assert_eq!(&s[..], "{ body }"),
1106 Err(_) => panic!("could not get snippet"),
1111 // This tests that when parsing a string (rather than a file) we don't try
1112 // and read in a file for a module declaration and just parse a stub.
1113 // See `recurse_into_file_modules` in the parser.
1115 fn out_of_line_mod() {
1117 let sess = ParseSess::new(FilePathMapping::empty());
1118 let item = parse_item_from_source_str(
1119 PathBuf::from("foo").into(),
1120 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
1122 ).unwrap().unwrap();
1124 if let ast::ItemKind::Mod(ref m) = item.node {
1125 assert!(m.items.len() == 2);