1 //! The main parser interface
3 use crate::ast::{self, CrateConfig, NodeId};
4 use crate::early_buffered_lints::{BufferedEarlyLint, BufferedEarlyLintId};
5 use crate::source_map::{SourceMap, FilePathMapping};
6 use crate::errors::{FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
7 use crate::feature_gate::UnstableFeatures;
8 use crate::parse::parser::Parser;
9 use crate::symbol::Symbol;
10 use crate::tokenstream::{TokenStream, TokenTree};
11 use crate::diagnostics::plugin::ErrorMap;
13 use rustc_data_structures::sync::{Lrc, Lock};
14 use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
17 use rustc_data_structures::fx::FxHashSet;
20 use std::path::{Path, PathBuf};
23 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
34 /// Info about a parsing session.
35 pub struct ParseSess {
36 pub span_diagnostic: Handler,
37 pub unstable_features: UnstableFeatures,
38 pub config: CrateConfig,
39 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
40 /// Places where raw identifiers were used. This is used for feature gating
42 pub raw_identifier_spans: Lock<Vec<Span>>,
43 /// The registered diagnostics codes
44 crate registered_diagnostics: Lock<ErrorMap>,
45 /// Used to determine and report recursive mod inclusions
46 included_mod_stack: Lock<Vec<PathBuf>>,
47 source_map: Lrc<SourceMap>,
48 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
52 pub fn new(file_path_mapping: FilePathMapping) -> Self {
53 let cm = Lrc::new(SourceMap::new(file_path_mapping));
54 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
58 ParseSess::with_span_handler(handler, cm)
61 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
63 span_diagnostic: handler,
64 unstable_features: UnstableFeatures::from_environment(),
65 config: FxHashSet::default(),
66 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
67 raw_identifier_spans: Lock::new(Vec::new()),
68 registered_diagnostics: Lock::new(ErrorMap::new()),
69 included_mod_stack: Lock::new(vec![]),
71 buffered_lints: Lock::new(vec![]),
76 pub fn source_map(&self) -> &SourceMap {
80 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
81 lint_id: BufferedEarlyLintId,
86 self.buffered_lints.with_lock(|buffered_lints| {
87 buffered_lints.push(BufferedEarlyLint{
98 pub struct Directory<'a> {
99 pub path: Cow<'a, Path>,
100 pub ownership: DirectoryOwnership,
103 #[derive(Copy, Clone)]
104 pub enum DirectoryOwnership {
106 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
107 relative: Option<ast::Ident>,
110 UnownedViaMod(bool /* legacy warnings? */),
113 // a bunch of utility functions of the form parse_<thing>_from_<source>
114 // where <thing> includes crate, expr, item, stmt, tts, and one that
115 // uses a HOF to parse anything, and <source> includes file and
118 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
119 let mut parser = new_parser_from_file(sess, input);
120 parser.parse_crate_mod()
123 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
124 -> PResult<'a, Vec<ast::Attribute>> {
125 let mut parser = new_parser_from_file(sess, input);
126 parser.parse_inner_attributes()
129 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
130 -> PResult<'_, ast::Crate> {
131 new_parser_from_source_str(sess, name, source).parse_crate_mod()
134 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
135 -> PResult<'_, Vec<ast::Attribute>> {
136 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
139 pub fn parse_stream_from_source_str(name: FileName, source: String, sess: &ParseSess,
140 override_span: Option<Span>)
142 source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span)
145 /// Create a new parser from a source string
146 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
148 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
151 /// Create a new parser from a source string. Returns any buffered errors from lexing the initial
153 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
154 -> Result<Parser<'_>, Vec<Diagnostic>>
156 let mut parser = maybe_source_file_to_parser(sess,
157 sess.source_map().new_source_file(name, source))?;
158 parser.recurse_into_file_modules = false;
162 /// Create a new parser, handling errors as appropriate
163 /// if the file doesn't exist
164 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
165 source_file_to_parser(sess, file_to_source_file(sess, path, None))
168 /// Create a new parser, returning buffered diagnostics if the file doesn't
169 /// exist or from lexing the initial token stream.
170 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
171 -> Result<Parser<'a>, Vec<Diagnostic>> {
172 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
173 maybe_source_file_to_parser(sess, file)
176 /// Given a session, a crate config, a path, and a span, add
177 /// the file at the given path to the source_map, and return a parser.
178 /// On an error, use the given span as the source of the problem.
179 crate fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
181 directory_ownership: DirectoryOwnership,
182 module_name: Option<String>,
183 sp: Span) -> Parser<'a> {
184 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
185 p.directory.ownership = directory_ownership;
186 p.root_module_name = module_name;
190 /// Given a source_file and config, return a parser
191 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
192 panictry_buffer!(&sess.span_diagnostic,
193 maybe_source_file_to_parser(sess, source_file))
196 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
197 /// initial token stream.
198 fn maybe_source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>)
199 -> Result<Parser<'_>, Vec<Diagnostic>>
201 let end_pos = source_file.end_pos;
202 let mut parser = stream_to_parser(sess, maybe_file_to_stream(sess, source_file, None)?);
204 if parser.token == token::Eof && parser.span.is_dummy() {
205 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
211 // must preserve old name for now, because quote! from the *existing*
212 // compiler expands into it
213 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
214 stream_to_parser(sess, tts.into_iter().collect())
220 /// Given a session and a path and an optional span (for error reporting),
221 /// add the path to the session's source_map and return the new source_file or
222 /// error when a file can't be read.
223 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
224 -> Result<Lrc<SourceFile>, Diagnostic> {
225 sess.source_map().load_file(path)
227 let msg = format!("couldn't read {}: {}", path.display(), e);
228 let mut diag = Diagnostic::new(Level::Fatal, &msg);
229 if let Some(sp) = spanopt {
236 /// Given a session and a path and an optional span (for error reporting),
237 /// add the path to the session's source_map and return the new source_file.
238 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
240 match try_file_to_source_file(sess, path, spanopt) {
241 Ok(source_file) => source_file,
243 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
249 /// Given a source_file, produce a sequence of token-trees
250 pub fn source_file_to_stream(sess: &ParseSess,
251 source_file: Lrc<SourceFile>,
252 override_span: Option<Span>) -> TokenStream {
253 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
256 /// Given a source file, produce a sequence of token-trees. Returns any buffered errors from
257 /// parsing the token tream.
258 pub fn maybe_file_to_stream(sess: &ParseSess,
259 source_file: Lrc<SourceFile>,
260 override_span: Option<Span>) -> Result<TokenStream, Vec<Diagnostic>> {
261 let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
264 match srdr.parse_all_token_trees() {
265 Ok(stream) => Ok(stream),
267 let mut buffer = Vec::with_capacity(1);
268 err.buffer(&mut buffer);
274 /// Given stream and the `ParseSess`, produce a parser
275 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> {
276 Parser::new(sess, stream, None, true, false)
279 /// Parse a string representing a character literal into its final form.
280 /// Rather than just accepting/rejecting a given literal, unescapes it as
281 /// well. Can take any slice prefixed by a character escape. Returns the
282 /// character and the number of characters consumed.
283 fn char_lit(lit: &str, diag: Option<(Span, &Handler)>) -> (char, isize) {
286 // Handle non-escaped chars first.
287 if lit.as_bytes()[0] != b'\\' {
288 // If the first byte isn't '\\' it might part of a multi-byte char, so
289 // get the char with chars().
290 let c = lit.chars().next().unwrap();
294 // Handle escaped chars.
295 match lit.as_bytes()[1] as char {
304 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
305 let c = char::from_u32(v).unwrap();
309 assert_eq!(lit.as_bytes()[2], b'{');
310 let idx = lit.find('}').unwrap();
312 // All digits and '_' are ascii, so treat each byte as a char.
314 for c in lit[3..idx].bytes() {
315 let c = char::from(c);
317 let x = c.to_digit(16).unwrap();
318 v = v.checked_mul(16).unwrap().checked_add(x).unwrap();
321 let c = char::from_u32(v).unwrap_or_else(|| {
322 if let Some((span, diag)) = diag {
323 let mut diag = diag.struct_span_err(span, "invalid unicode character escape");
325 diag.help("unicode escape must be at most 10FFFF").emit();
327 diag.help("unicode escape must not be a surrogate").emit();
332 (c, (idx + 1) as isize)
334 _ => panic!("lexer should have rejected a bad character escape {}", lit)
338 /// Parse a string representing a string literal into its final form. Does
340 pub fn str_lit(lit: &str, diag: Option<(Span, &Handler)>) -> String {
341 debug!("str_lit: given {}", lit.escape_default());
342 let mut res = String::with_capacity(lit.len());
344 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
346 /// Eat everything up to a non-whitespace
347 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
349 match it.peek().map(|x| x.1) {
350 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
358 let mut chars = lit.char_indices().peekable();
359 while let Some((i, c)) = chars.next() {
362 let ch = chars.peek().unwrap_or_else(|| {
363 panic!("{}", error(i))
368 } else if ch == '\r' {
370 let ch = chars.peek().unwrap_or_else(|| {
371 panic!("{}", error(i))
375 panic!("lexer accepted bare CR");
379 // otherwise, a normal escape
380 let (c, n) = char_lit(&lit[i..], diag);
381 for _ in 0..n - 1 { // we don't need to move past the first \
388 let ch = chars.peek().unwrap_or_else(|| {
389 panic!("{}", error(i))
393 panic!("lexer accepted bare CR");
402 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
403 debug!("parse_str_lit: returning {}", res);
407 /// Parse a string representing a raw string literal into its final form. The
408 /// only operation this does is convert embedded CRLF into a single LF.
409 fn raw_str_lit(lit: &str) -> String {
410 debug!("raw_str_lit: given {}", lit.escape_default());
411 let mut res = String::with_capacity(lit.len());
413 let mut chars = lit.chars().peekable();
414 while let Some(c) = chars.next() {
416 if *chars.peek().unwrap() != '\n' {
417 panic!("lexer accepted bare CR");
430 // check if `s` looks like i32 or u1234 etc.
431 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
432 s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
436 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
438 Some(($span, $diag)) => { $($body)* }
444 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
445 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
449 token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
450 token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str(), diag).0))),
451 token::Err(i) => (true, Some(LitKind::Err(i))),
453 // There are some valid suffixes for integer and float literals,
454 // so all the handling is done internally.
455 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
456 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
458 token::Str_(mut sym) => {
459 // If there are no characters requiring special treatment we can
460 // reuse the symbol from the Token. Otherwise, we must generate a
461 // new symbol because the string in the LitKind is different to the
462 // string in the Token.
463 let s = &sym.as_str();
464 if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
465 sym = Symbol::intern(&str_lit(s, diag));
467 (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
469 token::StrRaw(mut sym, n) => {
471 let s = &sym.as_str();
472 if s.contains('\r') {
473 sym = Symbol::intern(&raw_str_lit(s));
475 (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
477 token::ByteStr(i) => {
478 (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
480 token::ByteStrRaw(i, _) => {
481 (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
486 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
487 -> Option<ast::LitKind> {
488 debug!("filtered_float_lit: {}, {:?}", data, suffix);
489 let suffix = match suffix {
490 Some(suffix) => suffix,
491 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
494 Some(match &*suffix.as_str() {
495 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
496 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
498 err!(diag, |span, diag| {
499 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
500 // if it looks like a width, lets try to be helpful.
501 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
502 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
504 let msg = format!("invalid suffix `{}` for float literal", suf);
505 diag.struct_span_err(span, &msg)
506 .span_label(span, format!("invalid suffix `{}`", suf))
507 .help("valid suffixes are `f32` and `f64`")
512 ast::LitKind::FloatUnsuffixed(data)
516 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
517 -> Option<ast::LitKind> {
518 debug!("float_lit: {:?}, {:?}", s, suffix);
519 // FIXME #2252: bounds checking float literals is deferred until trans
521 // Strip underscores without allocating a new String unless necessary.
523 let s = if s.chars().any(|c| c == '_') {
524 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
530 filtered_float_lit(Symbol::intern(s), suffix, diag)
533 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
534 fn byte_lit(lit: &str) -> (u8, usize) {
535 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
538 (lit.as_bytes()[0], 1)
540 assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
541 let b = match lit.as_bytes()[1] {
550 match u64::from_str_radix(&lit[2..4], 16).ok() {
557 None => panic!(err(3))
565 fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
566 let mut res = Vec::with_capacity(lit.len());
568 let error = |i| panic!("lexer should have rejected {} at {}", lit, i);
570 /// Eat everything up to a non-whitespace
571 fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
573 match it.peek().map(|x| x.1) {
574 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
582 // byte string literals *must* be ASCII, but the escapes don't have to be
583 let mut chars = lit.bytes().enumerate().peekable();
586 Some((i, b'\\')) => {
587 match chars.peek().unwrap_or_else(|| error(i)).1 {
588 b'\n' => eat(&mut chars),
591 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
592 panic!("lexer accepted bare CR");
597 // otherwise, a normal escape
598 let (c, n) = byte_lit(&lit[i..]);
599 // we don't need to move past the first \
607 Some((i, b'\r')) => {
608 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
609 panic!("lexer accepted bare CR");
614 Some((_, c)) => res.push(c),
622 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
623 -> Option<ast::LitKind> {
624 // s can only be ascii, byte indexing is fine
626 // Strip underscores without allocating a new String unless necessary.
628 let mut s = if s.chars().any(|c| c == '_') {
629 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
635 debug!("integer_lit: {}, {:?}", s, suffix);
639 let mut ty = ast::LitIntType::Unsuffixed;
641 if s.starts_with('0') && s.len() > 1 {
642 match s.as_bytes()[1] {
650 // 1f64 and 2f32 etc. are valid float literals.
651 if let Some(suf) = suffix {
652 if looks_like_width_suffix(&['f'], &suf.as_str()) {
653 let err = match base {
654 16 => Some("hexadecimal float literal is not supported"),
655 8 => Some("octal float literal is not supported"),
656 2 => Some("binary float literal is not supported"),
659 if let Some(err) = err {
660 err!(diag, |span, diag| {
661 diag.struct_span_err(span, err)
662 .span_label(span, "not supported")
666 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
674 if let Some(suf) = suffix {
675 if suf.as_str().is_empty() {
676 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
678 ty = match &*suf.as_str() {
679 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
680 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
681 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
682 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
683 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
684 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
685 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
686 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
687 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
688 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
689 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
690 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
692 // i<digits> and u<digits> look like widths, so lets
693 // give an error message along those lines
694 err!(diag, |span, diag| {
695 if looks_like_width_suffix(&['i', 'u'], suf) {
696 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
697 diag.struct_span_err(span, &msg)
698 .help("valid widths are 8, 16, 32, 64 and 128")
701 let msg = format!("invalid suffix `{}` for numeric literal", suf);
702 diag.struct_span_err(span, &msg)
703 .span_label(span, format!("invalid suffix `{}`", suf))
704 .help("the suffix must be one of the integral types \
705 (`u32`, `isize`, etc)")
715 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
716 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
718 Some(match u128::from_str_radix(s, base) {
719 Ok(r) => ast::LitKind::Int(r, ty),
721 // small bases are lexed as if they were base 10, e.g, the string
722 // might be `0b10201`. This will cause the conversion above to fail,
723 // but these cases have errors in the lexer: we don't want to emit
724 // two errors, and we especially don't want to emit this error since
725 // it isn't necessarily true.
726 let already_errored = base < 10 &&
727 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
729 if !already_errored {
730 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
732 ast::LitKind::Int(0, ty)
737 /// `SeqSep` : a sequence separator (token)
738 /// and whether a trailing separator is allowed.
740 pub sep: Option<token::Token>,
741 pub trailing_sep_allowed: bool,
745 pub fn trailing_allowed(t: token::Token) -> SeqSep {
748 trailing_sep_allowed: true,
752 pub fn none() -> SeqSep {
755 trailing_sep_allowed: false,
763 use crate::ast::{self, Ident, PatKind};
764 use crate::attr::first_attr_value_str_by_name;
766 use crate::print::pprust::item_to_string;
767 use crate::tokenstream::{DelimSpan, TokenTree};
768 use crate::util::parser_testing::string_to_stream;
769 use crate::util::parser_testing::{string_to_expr, string_to_item};
770 use crate::with_globals;
771 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
775 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
776 /// when a syntax error occurred.
777 fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
778 -> PResult<'_, Option<P<ast::Item>>> {
779 new_parser_from_source_str(sess, name, source).parse_item()
782 // produce a syntax_pos::span
783 fn sp(a: u32, b: u32) -> Span {
784 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
788 #[test] fn bad_path_expr_1() {
790 string_to_expr("::abc::def::return".to_string());
794 // check the token-tree-ization of macros
796 fn string_to_tts_macro () {
799 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
800 let tts: &[TokenTree] = &tts[..];
802 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
805 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
806 Some(&TokenTree::Token(_, token::Not)),
807 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
808 Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
810 if name_macro_rules.name == "macro_rules"
811 && name_zip.name == "zip" => {
812 let tts = ¯o_tts.trees().collect::<Vec<_>>();
813 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
816 Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
817 Some(&TokenTree::Token(_, token::FatArrow)),
818 Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
820 if macro_delim == token::Paren => {
821 let tts = &first_tts.trees().collect::<Vec<_>>();
822 match (tts.len(), tts.get(0), tts.get(1)) {
825 Some(&TokenTree::Token(_, token::Dollar)),
826 Some(&TokenTree::Token(_, token::Ident(ident, false))),
828 if first_delim == token::Paren && ident.name == "a" => {},
829 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
831 let tts = &second_tts.trees().collect::<Vec<_>>();
832 match (tts.len(), tts.get(0), tts.get(1)) {
835 Some(&TokenTree::Token(_, token::Dollar)),
836 Some(&TokenTree::Token(_, token::Ident(ident, false))),
838 if second_delim == token::Paren && ident.name == "a" => {},
839 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
842 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
845 _ => panic!("value: {:?}",tts),
851 fn string_to_tts_1() {
853 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
855 let expected = TokenStream::new(vec![
856 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
857 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
858 TokenTree::Delimited(
859 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
860 token::DelimToken::Paren,
861 TokenStream::new(vec![
862 TokenTree::Token(sp(6, 7),
863 token::Ident(Ident::from_str("b"), false)).into(),
864 TokenTree::Token(sp(8, 9), token::Colon).into(),
865 TokenTree::Token(sp(10, 13),
866 token::Ident(Ident::from_str("i32"), false)).into(),
869 TokenTree::Delimited(
870 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
871 token::DelimToken::Brace,
872 TokenStream::new(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> crate::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 crate::visit::walk_pat(self, p);
930 let mut v = PatIdentVisitor { spans: Vec::new() };
931 crate::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_1 = FileName::Custom("crlf_source_1".to_string());
985 let source = "/// doc comment\r\nfn foo() {}".to_string();
986 let item = parse_item_from_source_str(name_1, source, &sess)
988 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
989 assert_eq!(doc, "/// doc comment");
991 let name_2 = FileName::Custom("crlf_source_2".to_string());
992 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
993 let item = parse_item_from_source_str(name_2, source, &sess)
995 let docs = item.attrs.iter().filter(|a| a.path == "doc")
996 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
997 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
998 assert_eq!(&docs[..], b);
1000 let name_3 = FileName::Custom("clrf_source_3".to_string());
1001 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1002 let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
1003 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1004 assert_eq!(doc, "/** doc comment\n * with CRLF */");
1010 fn parse_expr_from_source_str(
1011 name: FileName, source: String, sess: &ParseSess
1012 ) -> PResult<'_, P<ast::Expr>> {
1013 new_parser_from_source_str(sess, name, source).parse_expr()
1017 let sess = ParseSess::new(FilePathMapping::empty());
1018 let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
1019 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
1021 let tts: Vec<_> = match expr.node {
1022 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
1023 _ => panic!("not a macro"),
1026 let span = tts.iter().rev().next().unwrap().span();
1028 match sess.source_map().span_to_snippet(span) {
1029 Ok(s) => assert_eq!(&s[..], "{ body }"),
1030 Err(_) => panic!("could not get snippet"),
1035 // This tests that when parsing a string (rather than a file) we don't try
1036 // and read in a file for a module declaration and just parse a stub.
1037 // See `recurse_into_file_modules` in the parser.
1039 fn out_of_line_mod() {
1041 let sess = ParseSess::new(FilePathMapping::empty());
1042 let item = parse_item_from_source_str(
1043 PathBuf::from("foo").into(),
1044 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
1046 ).unwrap().unwrap();
1048 if let ast::ItemKind::Mod(ref m) = item.node {
1049 assert!(m.items.len() == 2);