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, NodeId};
15 use early_buffered_lints::{BufferedEarlyLint, BufferedEarlyLintId};
16 use source_map::{SourceMap, FilePathMapping};
17 use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
18 use errors::{Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
19 use feature_gate::UnstableFeatures;
20 use parse::parser::Parser;
24 use tokenstream::{TokenStream, TokenTree};
25 use diagnostics::plugin::ErrorMap;
27 use rustc_data_structures::fx::FxHashSet;
30 use std::path::{Path, PathBuf};
33 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: Lock<FxHashSet<Span>>,
50 /// Places where raw identifiers were used. This is used for feature gating
52 pub raw_identifier_spans: Lock<Vec<Span>>,
53 /// The registered diagnostics codes
54 crate registered_diagnostics: Lock<ErrorMap>,
55 // Spans where a `mod foo;` statement was included in a non-mod.rs file.
56 // These are used to issue errors if the non_modrs_mods feature is not enabled.
57 pub non_modrs_mods: Lock<Vec<(ast::Ident, Span)>>,
58 /// Used to determine and report recursive mod inclusions
59 included_mod_stack: Lock<Vec<PathBuf>>,
60 source_map: Lrc<SourceMap>,
61 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
65 pub fn new(file_path_mapping: FilePathMapping) -> Self {
66 let cm = Lrc::new(SourceMap::new(file_path_mapping));
67 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
71 ParseSess::with_span_handler(handler, cm)
74 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
76 span_diagnostic: handler,
77 unstable_features: UnstableFeatures::from_environment(),
78 config: FxHashSet::default(),
79 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
80 raw_identifier_spans: Lock::new(Vec::new()),
81 registered_diagnostics: Lock::new(ErrorMap::new()),
82 included_mod_stack: Lock::new(vec![]),
84 non_modrs_mods: Lock::new(vec![]),
85 buffered_lints: Lock::new(vec![]),
89 pub fn source_map(&self) -> &SourceMap {
93 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
94 lint_id: BufferedEarlyLintId,
99 self.buffered_lints.with_lock(|buffered_lints| {
100 buffered_lints.push(BufferedEarlyLint{
111 pub struct Directory<'a> {
112 pub path: Cow<'a, Path>,
113 pub ownership: DirectoryOwnership,
116 #[derive(Copy, Clone)]
117 pub enum DirectoryOwnership {
119 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
120 relative: Option<ast::Ident>,
123 UnownedViaMod(bool /* legacy warnings? */),
126 // a bunch of utility functions of the form parse_<thing>_from_<source>
127 // where <thing> includes crate, expr, item, stmt, tts, and one that
128 // uses a HOF to parse anything, and <source> includes file and
131 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
132 let mut parser = new_parser_from_file(sess, input);
133 parser.parse_crate_mod()
136 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
137 -> PResult<'a, Vec<ast::Attribute>> {
138 let mut parser = new_parser_from_file(sess, input);
139 parser.parse_inner_attributes()
142 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
143 -> PResult<ast::Crate> {
144 new_parser_from_source_str(sess, name, source).parse_crate_mod()
147 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
148 -> PResult<Vec<ast::Attribute>> {
149 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
152 crate fn parse_expr_from_source_str(name: FileName, source: String, sess: &ParseSess)
153 -> PResult<P<ast::Expr>> {
154 new_parser_from_source_str(sess, name, source).parse_expr()
159 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
160 /// when a syntax error occurred.
161 crate fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
162 -> PResult<Option<P<ast::Item>>> {
163 new_parser_from_source_str(sess, name, source).parse_item()
166 crate fn parse_stmt_from_source_str(name: FileName, source: String, sess: &ParseSess)
167 -> PResult<Option<ast::Stmt>> {
168 new_parser_from_source_str(sess, name, source).parse_stmt()
171 pub fn parse_stream_from_source_str(name: FileName, source: String, sess: &ParseSess,
172 override_span: Option<Span>)
174 source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span)
177 /// Create a new parser from a source string
178 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
180 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
183 /// Create a new parser from a source string. Returns any buffered errors from lexing the initial
185 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
186 -> Result<Parser, Vec<Diagnostic>>
188 let mut parser = maybe_source_file_to_parser(sess,
189 sess.source_map().new_source_file(name, source))?;
190 parser.recurse_into_file_modules = false;
194 /// Create a new parser, handling errors as appropriate
195 /// if the file doesn't exist
196 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
197 source_file_to_parser(sess, file_to_source_file(sess, path, None))
200 /// Given a session, a crate config, a path, and a span, add
201 /// the file at the given path to the source_map, and return a parser.
202 /// On an error, use the given span as the source of the problem.
203 crate fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
205 directory_ownership: DirectoryOwnership,
206 module_name: Option<String>,
207 sp: Span) -> Parser<'a> {
208 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
209 p.directory.ownership = directory_ownership;
210 p.root_module_name = module_name;
214 /// Given a source_file and config, return a parser
215 fn source_file_to_parser(sess: & ParseSess, source_file: Lrc<SourceFile>) -> Parser {
216 panictry_buffer!(&sess.span_diagnostic,
217 maybe_source_file_to_parser(sess, source_file))
220 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
221 /// initial token stream.
222 fn maybe_source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>)
223 -> Result<Parser, Vec<Diagnostic>>
225 let end_pos = source_file.end_pos;
226 let mut parser = stream_to_parser(sess, maybe_file_to_stream(sess, source_file, None)?);
228 if parser.token == token::Eof && parser.span.is_dummy() {
229 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
235 // must preserve old name for now, because quote! from the *existing*
236 // compiler expands into it
237 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser {
238 stream_to_parser(sess, tts.into_iter().collect())
244 /// Given a session and a path and an optional span (for error reporting),
245 /// add the path to the session's source_map and return the new source_file.
246 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
248 match sess.source_map().load_file(path) {
249 Ok(source_file) => source_file,
251 let msg = format!("couldn't read {}: {}", path.display(), e);
253 Some(sp) => sess.span_diagnostic.span_fatal(sp, &msg).raise(),
254 None => sess.span_diagnostic.fatal(&msg).raise()
260 /// Given a source_file, produce a sequence of token-trees
261 pub fn source_file_to_stream(sess: &ParseSess,
262 source_file: Lrc<SourceFile>,
263 override_span: Option<Span>) -> TokenStream {
264 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
267 /// Given a source file, produce a sequence of token-trees. Returns any buffered errors from
268 /// parsing the token tream.
269 pub fn maybe_file_to_stream(sess: &ParseSess,
270 source_file: Lrc<SourceFile>,
271 override_span: Option<Span>) -> Result<TokenStream, Vec<Diagnostic>> {
272 let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
275 match srdr.parse_all_token_trees() {
276 Ok(stream) => Ok(stream),
278 let mut buffer = Vec::with_capacity(1);
279 err.buffer(&mut buffer);
285 /// Given stream and the `ParseSess`, produce a parser
286 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser {
287 Parser::new(sess, stream, None, true, false)
290 /// Parse a string representing a character literal into its final form.
291 /// Rather than just accepting/rejecting a given literal, unescapes it as
292 /// well. Can take any slice prefixed by a character escape. Returns the
293 /// character and the number of characters consumed.
294 fn char_lit(lit: &str, diag: Option<(Span, &Handler)>) -> (char, isize) {
297 // Handle non-escaped chars first.
298 if lit.as_bytes()[0] != b'\\' {
299 // If the first byte isn't '\\' it might part of a multi-byte char, so
300 // get the char with chars().
301 let c = lit.chars().next().unwrap();
305 // Handle escaped chars.
306 match lit.as_bytes()[1] as char {
315 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
316 let c = char::from_u32(v).unwrap();
320 assert_eq!(lit.as_bytes()[2], b'{');
321 let idx = lit.find('}').unwrap();
323 // All digits and '_' are ascii, so treat each byte as a char.
325 for c in lit[3..idx].bytes() {
326 let c = char::from(c);
328 let x = c.to_digit(16).unwrap();
329 v = v.checked_mul(16).unwrap().checked_add(x).unwrap();
332 let c = char::from_u32(v).unwrap_or_else(|| {
333 if let Some((span, diag)) = diag {
334 let mut diag = diag.struct_span_err(span, "invalid unicode character escape");
336 diag.help("unicode escape must be at most 10FFFF").emit();
338 diag.help("unicode escape must not be a surrogate").emit();
343 (c, (idx + 1) as isize)
345 _ => panic!("lexer should have rejected a bad character escape {}", lit)
349 /// Parse a string representing a string literal into its final form. Does
351 pub fn str_lit(lit: &str, diag: Option<(Span, &Handler)>) -> String {
352 debug!("str_lit: given {}", lit.escape_default());
353 let mut res = String::with_capacity(lit.len());
355 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
357 /// Eat everything up to a non-whitespace
358 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
360 match it.peek().map(|x| x.1) {
361 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
369 let mut chars = lit.char_indices().peekable();
370 while let Some((i, c)) = chars.next() {
373 let ch = chars.peek().unwrap_or_else(|| {
374 panic!("{}", error(i))
379 } else if ch == '\r' {
381 let ch = chars.peek().unwrap_or_else(|| {
382 panic!("{}", error(i))
386 panic!("lexer accepted bare CR");
390 // otherwise, a normal escape
391 let (c, n) = char_lit(&lit[i..], diag);
392 for _ in 0..n - 1 { // we don't need to move past the first \
399 let ch = chars.peek().unwrap_or_else(|| {
400 panic!("{}", error(i))
404 panic!("lexer accepted bare CR");
413 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
414 debug!("parse_str_lit: returning {}", res);
418 /// Parse a string representing a raw string literal into its final form. The
419 /// only operation this does is convert embedded CRLF into a single LF.
420 fn raw_str_lit(lit: &str) -> String {
421 debug!("raw_str_lit: given {}", lit.escape_default());
422 let mut res = String::with_capacity(lit.len());
424 let mut chars = lit.chars().peekable();
425 while let Some(c) = chars.next() {
427 if *chars.peek().unwrap() != '\n' {
428 panic!("lexer accepted bare CR");
441 // check if `s` looks like i32 or u1234 etc.
442 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
444 first_chars.contains(&char_at(s, 0)) &&
445 s[1..].chars().all(|c| '0' <= c && c <= '9')
449 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
451 Some(($span, $diag)) => { $($body)* }
457 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
458 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
462 token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
463 token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str(), diag).0))),
465 // There are some valid suffixes for integer and float literals,
466 // so all the handling is done internally.
467 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
468 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
470 token::Str_(mut sym) => {
471 // If there are no characters requiring special treatment we can
472 // reuse the symbol from the Token. Otherwise, we must generate a
473 // new symbol because the string in the LitKind is different to the
474 // string in the Token.
475 let s = &sym.as_str();
476 if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
477 sym = Symbol::intern(&str_lit(s, diag));
479 (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
481 token::StrRaw(mut sym, n) => {
483 let s = &sym.as_str();
484 if s.contains('\r') {
485 sym = Symbol::intern(&raw_str_lit(s));
487 (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
489 token::ByteStr(i) => {
490 (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
492 token::ByteStrRaw(i, _) => {
493 (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
498 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
499 -> Option<ast::LitKind> {
500 debug!("filtered_float_lit: {}, {:?}", data, suffix);
501 let suffix = match suffix {
502 Some(suffix) => suffix,
503 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
506 Some(match &*suffix.as_str() {
507 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
508 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
510 err!(diag, |span, diag| {
511 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
512 // if it looks like a width, lets try to be helpful.
513 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
514 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
516 let msg = format!("invalid suffix `{}` for float literal", suf);
517 diag.struct_span_err(span, &msg)
518 .help("valid suffixes are `f32` and `f64`")
523 ast::LitKind::FloatUnsuffixed(data)
527 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
528 -> Option<ast::LitKind> {
529 debug!("float_lit: {:?}, {:?}", s, suffix);
530 // FIXME #2252: bounds checking float literals is deferred until trans
532 // Strip underscores without allocating a new String unless necessary.
534 let s = if s.chars().any(|c| c == '_') {
535 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
541 filtered_float_lit(Symbol::intern(s), suffix, diag)
544 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
545 fn byte_lit(lit: &str) -> (u8, usize) {
546 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
549 (lit.as_bytes()[0], 1)
551 assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
552 let b = match lit.as_bytes()[1] {
561 match u64::from_str_radix(&lit[2..4], 16).ok() {
568 None => panic!(err(3))
576 fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
577 let mut res = Vec::with_capacity(lit.len());
579 let error = |i| panic!("lexer should have rejected {} at {}", lit, i);
581 /// Eat everything up to a non-whitespace
582 fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
584 match it.peek().map(|x| x.1) {
585 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
593 // byte string literals *must* be ASCII, but the escapes don't have to be
594 let mut chars = lit.bytes().enumerate().peekable();
597 Some((i, b'\\')) => {
598 match chars.peek().unwrap_or_else(|| error(i)).1 {
599 b'\n' => eat(&mut chars),
602 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
603 panic!("lexer accepted bare CR");
608 // otherwise, a normal escape
609 let (c, n) = byte_lit(&lit[i..]);
610 // we don't need to move past the first \
618 Some((i, b'\r')) => {
619 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
620 panic!("lexer accepted bare CR");
625 Some((_, c)) => res.push(c),
633 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
634 -> Option<ast::LitKind> {
635 // s can only be ascii, byte indexing is fine
637 // Strip underscores without allocating a new String unless necessary.
639 let mut s = if s.chars().any(|c| c == '_') {
640 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
646 debug!("integer_lit: {}, {:?}", s, suffix);
650 let mut ty = ast::LitIntType::Unsuffixed;
652 if char_at(s, 0) == '0' && s.len() > 1 {
653 match char_at(s, 1) {
661 // 1f64 and 2f32 etc. are valid float literals.
662 if let Some(suf) = suffix {
663 if looks_like_width_suffix(&['f'], &suf.as_str()) {
664 let err = match base {
665 16 => Some("hexadecimal float literal is not supported"),
666 8 => Some("octal float literal is not supported"),
667 2 => Some("binary float literal is not supported"),
670 if let Some(err) = err {
671 err!(diag, |span, diag| diag.span_err(span, err));
673 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
681 if let Some(suf) = suffix {
682 if suf.as_str().is_empty() {
683 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
685 ty = match &*suf.as_str() {
686 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
687 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
688 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
689 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
690 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
691 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
692 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
693 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
694 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
695 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
696 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
697 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
699 // i<digits> and u<digits> look like widths, so lets
700 // give an error message along those lines
701 err!(diag, |span, diag| {
702 if looks_like_width_suffix(&['i', 'u'], suf) {
703 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
704 diag.struct_span_err(span, &msg)
705 .help("valid widths are 8, 16, 32, 64 and 128")
708 let msg = format!("invalid suffix `{}` for numeric literal", suf);
709 diag.struct_span_err(span, &msg)
710 .help("the suffix must be one of the integral types \
711 (`u32`, `isize`, etc)")
721 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
722 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
724 Some(match u128::from_str_radix(s, base) {
725 Ok(r) => ast::LitKind::Int(r, ty),
727 // small bases are lexed as if they were base 10, e.g, the string
728 // might be `0b10201`. This will cause the conversion above to fail,
729 // but these cases have errors in the lexer: we don't want to emit
730 // two errors, and we especially don't want to emit this error since
731 // it isn't necessarily true.
732 let already_errored = base < 10 &&
733 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
735 if !already_errored {
736 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
738 ast::LitKind::Int(0, ty)
743 /// `SeqSep` : a sequence separator (token)
744 /// and whether a trailing separator is allowed.
746 pub sep: Option<token::Token>,
747 pub trailing_sep_allowed: bool,
751 pub fn trailing_allowed(t: token::Token) -> SeqSep {
754 trailing_sep_allowed: true,
758 pub fn none() -> SeqSep {
761 trailing_sep_allowed: false,
769 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
770 use ast::{self, Ident, PatKind};
771 use attr::first_attr_value_str_by_name;
773 use print::pprust::item_to_string;
774 use tokenstream::{self, DelimSpan, TokenTree};
775 use util::parser_testing::string_to_stream;
776 use util::parser_testing::{string_to_expr, string_to_item};
779 // produce a syntax_pos::span
780 fn sp(a: u32, b: u32) -> Span {
781 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
785 #[test] fn bad_path_expr_1() {
787 string_to_expr("::abc::def::return".to_string());
791 // check the token-tree-ization of macros
793 fn string_to_tts_macro () {
796 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
797 let tts: &[TokenTree] = &tts[..];
799 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
802 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
803 Some(&TokenTree::Token(_, token::Not)),
804 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
805 Some(&TokenTree::Delimited(_, ref macro_delimed)),
807 if name_macro_rules.name == "macro_rules"
808 && name_zip.name == "zip" => {
809 let tts = ¯o_delimed.stream().trees().collect::<Vec<_>>();
810 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
813 Some(&TokenTree::Delimited(_, ref first_delimed)),
814 Some(&TokenTree::Token(_, token::FatArrow)),
815 Some(&TokenTree::Delimited(_, ref second_delimed)),
817 if macro_delimed.delim == token::Paren => {
818 let tts = &first_delimed.stream().trees().collect::<Vec<_>>();
819 match (tts.len(), tts.get(0), tts.get(1)) {
822 Some(&TokenTree::Token(_, token::Dollar)),
823 Some(&TokenTree::Token(_, token::Ident(ident, false))),
825 if first_delimed.delim == token::Paren && ident.name == "a" => {},
826 _ => panic!("value 3: {:?}", *first_delimed),
828 let tts = &second_delimed.stream().trees().collect::<Vec<_>>();
829 match (tts.len(), tts.get(0), tts.get(1)) {
832 Some(&TokenTree::Token(_, token::Dollar)),
833 Some(&TokenTree::Token(_, token::Ident(ident, false))),
835 if second_delimed.delim == token::Paren
836 && ident.name == "a" => {},
837 _ => panic!("value 4: {:?}", *second_delimed),
840 _ => panic!("value 2: {:?}", *macro_delimed),
843 _ => panic!("value: {:?}",tts),
849 fn string_to_tts_1() {
851 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
853 let expected = TokenStream::concat(vec![
854 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
855 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
856 TokenTree::Delimited(
857 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
858 tokenstream::Delimited {
859 delim: token::DelimToken::Paren,
860 tts: TokenStream::concat(vec![
861 TokenTree::Token(sp(6, 7),
862 token::Ident(Ident::from_str("b"), false)).into(),
863 TokenTree::Token(sp(8, 9), token::Colon).into(),
864 TokenTree::Token(sp(10, 13),
865 token::Ident(Ident::from_str("i32"), false)).into(),
868 TokenTree::Delimited(
869 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
870 tokenstream::Delimited {
871 delim: token::DelimToken::Brace,
872 tts: TokenStream::concat(vec![
873 TokenTree::Token(sp(17, 18),
874 token::Ident(Ident::from_str("b"), false)).into(),
875 TokenTree::Token(sp(18, 19), token::Semi).into(),
880 assert_eq!(tts, expected);
884 #[test] fn parse_use() {
886 let use_s = "use foo::bar::baz;";
887 let vitem = string_to_item(use_s.to_string()).unwrap();
888 let vitem_s = item_to_string(&vitem);
889 assert_eq!(&vitem_s[..], use_s);
891 let use_s = "use foo::bar as baz;";
892 let vitem = string_to_item(use_s.to_string()).unwrap();
893 let vitem_s = item_to_string(&vitem);
894 assert_eq!(&vitem_s[..], use_s);
898 #[test] fn parse_extern_crate() {
900 let ex_s = "extern crate foo;";
901 let vitem = string_to_item(ex_s.to_string()).unwrap();
902 let vitem_s = item_to_string(&vitem);
903 assert_eq!(&vitem_s[..], ex_s);
905 let ex_s = "extern crate foo as bar;";
906 let vitem = string_to_item(ex_s.to_string()).unwrap();
907 let vitem_s = item_to_string(&vitem);
908 assert_eq!(&vitem_s[..], ex_s);
912 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
913 let item = string_to_item(src.to_string()).unwrap();
915 struct PatIdentVisitor {
918 impl<'a> ::visit::Visitor<'a> for PatIdentVisitor {
919 fn visit_pat(&mut self, p: &'a ast::Pat) {
921 PatKind::Ident(_ , ref spannedident, _) => {
922 self.spans.push(spannedident.span.clone());
925 ::visit::walk_pat(self, p);
930 let mut v = PatIdentVisitor { spans: Vec::new() };
931 ::visit::walk_item(&mut v, &item);
935 #[test] fn span_of_self_arg_pat_idents_are_correct() {
938 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
939 "impl z { fn a (&mut self, &myarg: i32) {} }",
940 "impl z { fn a (&'a self, &myarg: i32) {} }",
941 "impl z { fn a (self, &myarg: i32) {} }",
942 "impl z { fn a (self: Foo, &myarg: i32) {} }",
946 let spans = get_spans_of_pat_idents(src);
947 let (lo, hi) = (spans[0].lo(), spans[0].hi());
948 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
949 "\"{}\" != \"self\". src=\"{}\"",
950 &src[lo.to_usize()..hi.to_usize()], src)
955 #[test] fn parse_exprs () {
957 // just make sure that they parse....
958 string_to_expr("3 + 4".to_string());
959 string_to_expr("a::z.froob(b,&(987+3))".to_string());
963 #[test] fn attrs_fix_bug () {
965 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
966 -> Result<Box<Writer>, String> {
969 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
973 fn wb() -> c_int { O_WRONLY as c_int }
975 let mut fflags: c_int = wb();
980 #[test] fn crlf_doc_comments() {
982 let sess = ParseSess::new(FilePathMapping::empty());
984 let name = FileName::Custom("source".to_string());
985 let source = "/// doc comment\r\nfn foo() {}".to_string();
986 let item = parse_item_from_source_str(name.clone(), source, &sess)
988 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
989 assert_eq!(doc, "/// doc comment");
991 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
992 let item = parse_item_from_source_str(name.clone(), source, &sess)
994 let docs = item.attrs.iter().filter(|a| a.path == "doc")
995 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
996 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
997 assert_eq!(&docs[..], b);
999 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1000 let item = parse_item_from_source_str(name, source, &sess).unwrap().unwrap();
1001 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1002 assert_eq!(doc, "/** doc comment\n * with CRLF */");
1009 let sess = ParseSess::new(FilePathMapping::empty());
1010 let expr = parse::parse_expr_from_source_str(PathBuf::from("foo").into(),
1011 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
1013 let tts: Vec<_> = match expr.node {
1014 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
1015 _ => panic!("not a macro"),
1018 let span = tts.iter().rev().next().unwrap().span();
1020 match sess.source_map().span_to_snippet(span) {
1021 Ok(s) => assert_eq!(&s[..], "{ body }"),
1022 Err(_) => panic!("could not get snippet"),
1027 // This tests that when parsing a string (rather than a file) we don't try
1028 // and read in a file for a module declaration and just parse a stub.
1029 // See `recurse_into_file_modules` in the parser.
1031 fn out_of_line_mod() {
1033 let sess = ParseSess::new(FilePathMapping::empty());
1034 let item = parse_item_from_source_str(
1035 PathBuf::from("foo").into(),
1036 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
1038 ).unwrap().unwrap();
1040 if let ast::ItemKind::Mod(ref m) = item.node {
1041 assert!(m.items.len() == 2);