1 //! The main parser interface
3 use rustc_data_structures::sync::{Lrc, Lock};
4 use ast::{self, CrateConfig, NodeId};
5 use early_buffered_lints::{BufferedEarlyLint, BufferedEarlyLintId};
6 use source_map::{SourceMap, FilePathMapping};
7 use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
8 use errors::{FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
9 use feature_gate::UnstableFeatures;
10 use parse::parser::Parser;
12 use tokenstream::{TokenStream, TokenTree};
13 use diagnostics::plugin::ErrorMap;
15 use rustc_data_structures::fx::FxHashSet;
18 use std::path::{Path, PathBuf};
21 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
32 /// Info about a parsing session.
33 pub struct ParseSess {
34 pub span_diagnostic: Handler,
35 pub unstable_features: UnstableFeatures,
36 pub config: CrateConfig,
37 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
38 /// Places where raw identifiers were used. This is used for feature gating
40 pub raw_identifier_spans: Lock<Vec<Span>>,
41 /// The registered diagnostics codes
42 crate registered_diagnostics: Lock<ErrorMap>,
43 /// Used to determine and report recursive mod inclusions
44 included_mod_stack: Lock<Vec<PathBuf>>,
45 source_map: Lrc<SourceMap>,
46 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
50 pub fn new(file_path_mapping: FilePathMapping) -> Self {
51 let cm = Lrc::new(SourceMap::new(file_path_mapping));
52 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
56 ParseSess::with_span_handler(handler, cm)
59 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
61 span_diagnostic: handler,
62 unstable_features: UnstableFeatures::from_environment(),
63 config: FxHashSet::default(),
64 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
65 raw_identifier_spans: Lock::new(Vec::new()),
66 registered_diagnostics: Lock::new(ErrorMap::new()),
67 included_mod_stack: Lock::new(vec![]),
69 buffered_lints: Lock::new(vec![]),
74 pub fn source_map(&self) -> &SourceMap {
78 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
79 lint_id: BufferedEarlyLintId,
84 self.buffered_lints.with_lock(|buffered_lints| {
85 buffered_lints.push(BufferedEarlyLint{
96 pub struct Directory<'a> {
97 pub path: Cow<'a, Path>,
98 pub ownership: DirectoryOwnership,
101 #[derive(Copy, Clone)]
102 pub enum DirectoryOwnership {
104 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
105 relative: Option<ast::Ident>,
108 UnownedViaMod(bool /* legacy warnings? */),
111 // a bunch of utility functions of the form parse_<thing>_from_<source>
112 // where <thing> includes crate, expr, item, stmt, tts, and one that
113 // uses a HOF to parse anything, and <source> includes file and
116 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
117 let mut parser = new_parser_from_file(sess, input);
118 parser.parse_crate_mod()
121 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
122 -> PResult<'a, Vec<ast::Attribute>> {
123 let mut parser = new_parser_from_file(sess, input);
124 parser.parse_inner_attributes()
127 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
128 -> PResult<ast::Crate> {
129 new_parser_from_source_str(sess, name, source).parse_crate_mod()
132 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
133 -> PResult<Vec<ast::Attribute>> {
134 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
137 pub fn parse_stream_from_source_str(name: FileName, source: String, sess: &ParseSess,
138 override_span: Option<Span>)
140 source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span)
143 /// Create a new parser from a source string
144 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
146 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
149 /// Create a new parser from a source string. Returns any buffered errors from lexing the initial
151 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
152 -> Result<Parser, Vec<Diagnostic>>
154 let mut parser = maybe_source_file_to_parser(sess,
155 sess.source_map().new_source_file(name, source))?;
156 parser.recurse_into_file_modules = false;
160 /// Create a new parser, handling errors as appropriate
161 /// if the file doesn't exist
162 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
163 source_file_to_parser(sess, file_to_source_file(sess, path, None))
166 /// Create a new parser, returning buffered diagnostics if the file doesn't
167 /// exist or from lexing the initial token stream.
168 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
169 -> Result<Parser<'a>, Vec<Diagnostic>> {
170 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
171 maybe_source_file_to_parser(sess, file)
174 /// Given a session, a crate config, a path, and a span, add
175 /// the file at the given path to the source_map, and return a parser.
176 /// On an error, use the given span as the source of the problem.
177 crate fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
179 directory_ownership: DirectoryOwnership,
180 module_name: Option<String>,
181 sp: Span) -> Parser<'a> {
182 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
183 p.directory.ownership = directory_ownership;
184 p.root_module_name = module_name;
188 /// Given a source_file and config, return a parser
189 fn source_file_to_parser(sess: & ParseSess, source_file: Lrc<SourceFile>) -> Parser {
190 panictry_buffer!(&sess.span_diagnostic,
191 maybe_source_file_to_parser(sess, source_file))
194 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
195 /// initial token stream.
196 fn maybe_source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>)
197 -> Result<Parser, Vec<Diagnostic>>
199 let end_pos = source_file.end_pos;
200 let mut parser = stream_to_parser(sess, maybe_file_to_stream(sess, source_file, None)?);
202 if parser.token == token::Eof && parser.span.is_dummy() {
203 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
209 // must preserve old name for now, because quote! from the *existing*
210 // compiler expands into it
211 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser {
212 stream_to_parser(sess, tts.into_iter().collect())
218 /// Given a session and a path and an optional span (for error reporting),
219 /// add the path to the session's source_map and return the new source_file or
220 /// error when a file can't be read.
221 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
222 -> Result<Lrc<SourceFile>, Diagnostic> {
223 sess.source_map().load_file(path)
225 let msg = format!("couldn't read {}: {}", path.display(), e);
226 let mut diag = Diagnostic::new(Level::Fatal, &msg);
227 if let Some(sp) = spanopt {
234 /// Given a session and a path and an optional span (for error reporting),
235 /// add the path to the session's source_map and return the new source_file.
236 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
238 match try_file_to_source_file(sess, path, spanopt) {
239 Ok(source_file) => source_file,
241 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
247 /// Given a source_file, produce a sequence of token-trees
248 pub fn source_file_to_stream(sess: &ParseSess,
249 source_file: Lrc<SourceFile>,
250 override_span: Option<Span>) -> TokenStream {
251 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
254 /// Given a source file, produce a sequence of token-trees. Returns any buffered errors from
255 /// parsing the token tream.
256 pub fn maybe_file_to_stream(sess: &ParseSess,
257 source_file: Lrc<SourceFile>,
258 override_span: Option<Span>) -> Result<TokenStream, Vec<Diagnostic>> {
259 let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
262 match srdr.parse_all_token_trees() {
263 Ok(stream) => Ok(stream),
265 let mut buffer = Vec::with_capacity(1);
266 err.buffer(&mut buffer);
272 /// Given stream and the `ParseSess`, produce a parser
273 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser {
274 Parser::new(sess, stream, None, true, false)
277 /// Parse a string representing a character literal into its final form.
278 /// Rather than just accepting/rejecting a given literal, unescapes it as
279 /// well. Can take any slice prefixed by a character escape. Returns the
280 /// character and the number of characters consumed.
281 fn char_lit(lit: &str, diag: Option<(Span, &Handler)>) -> (char, isize) {
284 // Handle non-escaped chars first.
285 if lit.as_bytes()[0] != b'\\' {
286 // If the first byte isn't '\\' it might part of a multi-byte char, so
287 // get the char with chars().
288 let c = lit.chars().next().unwrap();
292 // Handle escaped chars.
293 match lit.as_bytes()[1] as char {
302 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
303 let c = char::from_u32(v).unwrap();
307 assert_eq!(lit.as_bytes()[2], b'{');
308 let idx = lit.find('}').unwrap();
310 // All digits and '_' are ascii, so treat each byte as a char.
312 for c in lit[3..idx].bytes() {
313 let c = char::from(c);
315 let x = c.to_digit(16).unwrap();
316 v = v.checked_mul(16).unwrap().checked_add(x).unwrap();
319 let c = char::from_u32(v).unwrap_or_else(|| {
320 if let Some((span, diag)) = diag {
321 let mut diag = diag.struct_span_err(span, "invalid unicode character escape");
323 diag.help("unicode escape must be at most 10FFFF").emit();
325 diag.help("unicode escape must not be a surrogate").emit();
330 (c, (idx + 1) as isize)
332 _ => panic!("lexer should have rejected a bad character escape {}", lit)
336 /// Parse a string representing a string literal into its final form. Does
338 pub fn str_lit(lit: &str, diag: Option<(Span, &Handler)>) -> String {
339 debug!("str_lit: given {}", lit.escape_default());
340 let mut res = String::with_capacity(lit.len());
342 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
344 /// Eat everything up to a non-whitespace
345 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
347 match it.peek().map(|x| x.1) {
348 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
356 let mut chars = lit.char_indices().peekable();
357 while let Some((i, c)) = chars.next() {
360 let ch = chars.peek().unwrap_or_else(|| {
361 panic!("{}", error(i))
366 } else if ch == '\r' {
368 let ch = chars.peek().unwrap_or_else(|| {
369 panic!("{}", error(i))
373 panic!("lexer accepted bare CR");
377 // otherwise, a normal escape
378 let (c, n) = char_lit(&lit[i..], diag);
379 for _ in 0..n - 1 { // we don't need to move past the first \
386 let ch = chars.peek().unwrap_or_else(|| {
387 panic!("{}", error(i))
391 panic!("lexer accepted bare CR");
400 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
401 debug!("parse_str_lit: returning {}", res);
405 /// Parse a string representing a raw string literal into its final form. The
406 /// only operation this does is convert embedded CRLF into a single LF.
407 fn raw_str_lit(lit: &str) -> String {
408 debug!("raw_str_lit: given {}", lit.escape_default());
409 let mut res = String::with_capacity(lit.len());
411 let mut chars = lit.chars().peekable();
412 while let Some(c) = chars.next() {
414 if *chars.peek().unwrap() != '\n' {
415 panic!("lexer accepted bare CR");
428 // check if `s` looks like i32 or u1234 etc.
429 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
430 s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
434 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
436 Some(($span, $diag)) => { $($body)* }
442 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
443 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
447 token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
448 token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str(), diag).0))),
449 token::Err(i) => (true, Some(LitKind::Err(i))),
451 // There are some valid suffixes for integer and float literals,
452 // so all the handling is done internally.
453 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
454 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
456 token::Str_(mut sym) => {
457 // If there are no characters requiring special treatment we can
458 // reuse the symbol from the Token. Otherwise, we must generate a
459 // new symbol because the string in the LitKind is different to the
460 // string in the Token.
461 let s = &sym.as_str();
462 if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
463 sym = Symbol::intern(&str_lit(s, diag));
465 (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
467 token::StrRaw(mut sym, n) => {
469 let s = &sym.as_str();
470 if s.contains('\r') {
471 sym = Symbol::intern(&raw_str_lit(s));
473 (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
475 token::ByteStr(i) => {
476 (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
478 token::ByteStrRaw(i, _) => {
479 (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
484 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
485 -> Option<ast::LitKind> {
486 debug!("filtered_float_lit: {}, {:?}", data, suffix);
487 let suffix = match suffix {
488 Some(suffix) => suffix,
489 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
492 Some(match &*suffix.as_str() {
493 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
494 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
496 err!(diag, |span, diag| {
497 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
498 // if it looks like a width, lets try to be helpful.
499 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
500 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
502 let msg = format!("invalid suffix `{}` for float literal", suf);
503 diag.struct_span_err(span, &msg)
504 .span_label(span, format!("invalid suffix `{}`", suf))
505 .help("valid suffixes are `f32` and `f64`")
510 ast::LitKind::FloatUnsuffixed(data)
514 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
515 -> Option<ast::LitKind> {
516 debug!("float_lit: {:?}, {:?}", s, suffix);
517 // FIXME #2252: bounds checking float literals is deferred until trans
519 // Strip underscores without allocating a new String unless necessary.
521 let s = if s.chars().any(|c| c == '_') {
522 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
528 filtered_float_lit(Symbol::intern(s), suffix, diag)
531 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
532 fn byte_lit(lit: &str) -> (u8, usize) {
533 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
536 (lit.as_bytes()[0], 1)
538 assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
539 let b = match lit.as_bytes()[1] {
548 match u64::from_str_radix(&lit[2..4], 16).ok() {
555 None => panic!(err(3))
563 fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
564 let mut res = Vec::with_capacity(lit.len());
566 let error = |i| panic!("lexer should have rejected {} at {}", lit, i);
568 /// Eat everything up to a non-whitespace
569 fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
571 match it.peek().map(|x| x.1) {
572 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
580 // byte string literals *must* be ASCII, but the escapes don't have to be
581 let mut chars = lit.bytes().enumerate().peekable();
584 Some((i, b'\\')) => {
585 match chars.peek().unwrap_or_else(|| error(i)).1 {
586 b'\n' => eat(&mut chars),
589 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
590 panic!("lexer accepted bare CR");
595 // otherwise, a normal escape
596 let (c, n) = byte_lit(&lit[i..]);
597 // we don't need to move past the first \
605 Some((i, b'\r')) => {
606 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
607 panic!("lexer accepted bare CR");
612 Some((_, c)) => res.push(c),
620 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
621 -> Option<ast::LitKind> {
622 // s can only be ascii, byte indexing is fine
624 // Strip underscores without allocating a new String unless necessary.
626 let mut s = if s.chars().any(|c| c == '_') {
627 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
633 debug!("integer_lit: {}, {:?}", s, suffix);
637 let mut ty = ast::LitIntType::Unsuffixed;
639 if s.starts_with('0') && s.len() > 1 {
640 match s.as_bytes()[1] {
648 // 1f64 and 2f32 etc. are valid float literals.
649 if let Some(suf) = suffix {
650 if looks_like_width_suffix(&['f'], &suf.as_str()) {
651 let err = match base {
652 16 => Some("hexadecimal float literal is not supported"),
653 8 => Some("octal float literal is not supported"),
654 2 => Some("binary float literal is not supported"),
657 if let Some(err) = err {
658 err!(diag, |span, diag| {
659 diag.struct_span_err(span, err)
660 .span_label(span, "not supported")
664 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
672 if let Some(suf) = suffix {
673 if suf.as_str().is_empty() {
674 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
676 ty = match &*suf.as_str() {
677 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
678 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
679 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
680 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
681 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
682 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
683 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
684 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
685 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
686 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
687 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
688 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
690 // i<digits> and u<digits> look like widths, so lets
691 // give an error message along those lines
692 err!(diag, |span, diag| {
693 if looks_like_width_suffix(&['i', 'u'], suf) {
694 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
695 diag.struct_span_err(span, &msg)
696 .help("valid widths are 8, 16, 32, 64 and 128")
699 let msg = format!("invalid suffix `{}` for numeric literal", suf);
700 diag.struct_span_err(span, &msg)
701 .span_label(span, format!("invalid suffix `{}`", suf))
702 .help("the suffix must be one of the integral types \
703 (`u32`, `isize`, etc)")
713 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
714 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
716 Some(match u128::from_str_radix(s, base) {
717 Ok(r) => ast::LitKind::Int(r, ty),
719 // small bases are lexed as if they were base 10, e.g, the string
720 // might be `0b10201`. This will cause the conversion above to fail,
721 // but these cases have errors in the lexer: we don't want to emit
722 // two errors, and we especially don't want to emit this error since
723 // it isn't necessarily true.
724 let already_errored = base < 10 &&
725 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
727 if !already_errored {
728 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
730 ast::LitKind::Int(0, ty)
735 /// `SeqSep` : a sequence separator (token)
736 /// and whether a trailing separator is allowed.
738 pub sep: Option<token::Token>,
739 pub trailing_sep_allowed: bool,
743 pub fn trailing_allowed(t: token::Token) -> SeqSep {
746 trailing_sep_allowed: true,
750 pub fn none() -> SeqSep {
753 trailing_sep_allowed: false,
761 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
762 use ast::{self, Ident, PatKind};
763 use attr::first_attr_value_str_by_name;
765 use print::pprust::item_to_string;
766 use tokenstream::{DelimSpan, TokenTree};
767 use util::parser_testing::string_to_stream;
768 use util::parser_testing::{string_to_expr, string_to_item};
773 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
774 /// when a syntax error occurred.
775 fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
776 -> PResult<Option<P<ast::Item>>> {
777 new_parser_from_source_str(sess, name, source).parse_item()
780 // produce a syntax_pos::span
781 fn sp(a: u32, b: u32) -> Span {
782 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
786 #[test] fn bad_path_expr_1() {
788 string_to_expr("::abc::def::return".to_string());
792 // check the token-tree-ization of macros
794 fn string_to_tts_macro () {
797 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
798 let tts: &[TokenTree] = &tts[..];
800 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
803 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
804 Some(&TokenTree::Token(_, token::Not)),
805 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
806 Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
808 if name_macro_rules.name == "macro_rules"
809 && name_zip.name == "zip" => {
810 let tts = ¯o_tts.trees().collect::<Vec<_>>();
811 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
814 Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
815 Some(&TokenTree::Token(_, token::FatArrow)),
816 Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
818 if macro_delim == token::Paren => {
819 let tts = &first_tts.trees().collect::<Vec<_>>();
820 match (tts.len(), tts.get(0), tts.get(1)) {
823 Some(&TokenTree::Token(_, token::Dollar)),
824 Some(&TokenTree::Token(_, token::Ident(ident, false))),
826 if first_delim == token::Paren && ident.name == "a" => {},
827 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
829 let tts = &second_tts.trees().collect::<Vec<_>>();
830 match (tts.len(), tts.get(0), tts.get(1)) {
833 Some(&TokenTree::Token(_, token::Dollar)),
834 Some(&TokenTree::Token(_, token::Ident(ident, false))),
836 if second_delim == token::Paren && ident.name == "a" => {},
837 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
840 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
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::new(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 token::DelimToken::Paren,
859 TokenStream::new(vec![
860 TokenTree::Token(sp(6, 7),
861 token::Ident(Ident::from_str("b"), false)).into(),
862 TokenTree::Token(sp(8, 9), token::Colon).into(),
863 TokenTree::Token(sp(10, 13),
864 token::Ident(Ident::from_str("i32"), false)).into(),
867 TokenTree::Delimited(
868 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
869 token::DelimToken::Brace,
870 TokenStream::new(vec![
871 TokenTree::Token(sp(17, 18),
872 token::Ident(Ident::from_str("b"), false)).into(),
873 TokenTree::Token(sp(18, 19), token::Semi).into(),
878 assert_eq!(tts, expected);
882 #[test] fn parse_use() {
884 let use_s = "use foo::bar::baz;";
885 let vitem = string_to_item(use_s.to_string()).unwrap();
886 let vitem_s = item_to_string(&vitem);
887 assert_eq!(&vitem_s[..], use_s);
889 let use_s = "use foo::bar as baz;";
890 let vitem = string_to_item(use_s.to_string()).unwrap();
891 let vitem_s = item_to_string(&vitem);
892 assert_eq!(&vitem_s[..], use_s);
896 #[test] fn parse_extern_crate() {
898 let ex_s = "extern crate foo;";
899 let vitem = string_to_item(ex_s.to_string()).unwrap();
900 let vitem_s = item_to_string(&vitem);
901 assert_eq!(&vitem_s[..], ex_s);
903 let ex_s = "extern crate foo as bar;";
904 let vitem = string_to_item(ex_s.to_string()).unwrap();
905 let vitem_s = item_to_string(&vitem);
906 assert_eq!(&vitem_s[..], ex_s);
910 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
911 let item = string_to_item(src.to_string()).unwrap();
913 struct PatIdentVisitor {
916 impl<'a> ::visit::Visitor<'a> for PatIdentVisitor {
917 fn visit_pat(&mut self, p: &'a ast::Pat) {
919 PatKind::Ident(_ , ref spannedident, _) => {
920 self.spans.push(spannedident.span.clone());
923 ::visit::walk_pat(self, p);
928 let mut v = PatIdentVisitor { spans: Vec::new() };
929 ::visit::walk_item(&mut v, &item);
933 #[test] fn span_of_self_arg_pat_idents_are_correct() {
936 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
937 "impl z { fn a (&mut self, &myarg: i32) {} }",
938 "impl z { fn a (&'a self, &myarg: i32) {} }",
939 "impl z { fn a (self, &myarg: i32) {} }",
940 "impl z { fn a (self: Foo, &myarg: i32) {} }",
944 let spans = get_spans_of_pat_idents(src);
945 let (lo, hi) = (spans[0].lo(), spans[0].hi());
946 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
947 "\"{}\" != \"self\". src=\"{}\"",
948 &src[lo.to_usize()..hi.to_usize()], src)
953 #[test] fn parse_exprs () {
955 // just make sure that they parse....
956 string_to_expr("3 + 4".to_string());
957 string_to_expr("a::z.froob(b,&(987+3))".to_string());
961 #[test] fn attrs_fix_bug () {
963 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
964 -> Result<Box<Writer>, String> {
967 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
971 fn wb() -> c_int { O_WRONLY as c_int }
973 let mut fflags: c_int = wb();
978 #[test] fn crlf_doc_comments() {
980 let sess = ParseSess::new(FilePathMapping::empty());
982 let name_1 = FileName::Custom("crlf_source_1".to_string());
983 let source = "/// doc comment\r\nfn foo() {}".to_string();
984 let item = parse_item_from_source_str(name_1, source, &sess)
986 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
987 assert_eq!(doc, "/// doc comment");
989 let name_2 = FileName::Custom("crlf_source_2".to_string());
990 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
991 let item = parse_item_from_source_str(name_2, source, &sess)
993 let docs = item.attrs.iter().filter(|a| a.path == "doc")
994 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
995 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
996 assert_eq!(&docs[..], b);
998 let name_3 = FileName::Custom("clrf_source_3".to_string());
999 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1000 let item = parse_item_from_source_str(name_3, 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 */");
1008 fn parse_expr_from_source_str(
1009 name: FileName, source: String, sess: &ParseSess
1010 ) -> PResult<P<ast::Expr>> {
1011 new_parser_from_source_str(sess, name, source).parse_expr()
1015 let sess = ParseSess::new(FilePathMapping::empty());
1016 let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
1017 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
1019 let tts: Vec<_> = match expr.node {
1020 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
1021 _ => panic!("not a macro"),
1024 let span = tts.iter().rev().next().unwrap().span();
1026 match sess.source_map().span_to_snippet(span) {
1027 Ok(s) => assert_eq!(&s[..], "{ body }"),
1028 Err(_) => panic!("could not get snippet"),
1033 // This tests that when parsing a string (rather than a file) we don't try
1034 // and read in a file for a module declaration and just parse a stub.
1035 // See `recurse_into_file_modules` in the parser.
1037 fn out_of_line_mod() {
1039 let sess = ParseSess::new(FilePathMapping::empty());
1040 let item = parse_item_from_source_str(
1041 PathBuf::from("foo").into(),
1042 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
1044 ).unwrap().unwrap();
1046 if let ast::ItemKind::Mod(ref m) = item.node {
1047 assert!(m.items.len() == 2);