1 //! The main parser interface.
3 use crate::ast::{self, CrateConfig, LitKind, NodeId};
4 use crate::early_buffered_lints::{BufferedEarlyLint, BufferedEarlyLintId};
5 use crate::source_map::{SourceMap, FilePathMapping};
6 use crate::feature_gate::UnstableFeatures;
7 use crate::parse::parser::Parser;
8 use crate::symbol::{keywords, Symbol};
9 use crate::syntax::parse::parser::emit_unclosed_delims;
10 use crate::tokenstream::{TokenStream, TokenTree};
11 use crate::diagnostics::plugin::ErrorMap;
12 use crate::print::pprust::token_to_string;
14 use errors::{Applicability, FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
15 use rustc_data_structures::sync::{Lrc, Lock};
16 use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
19 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
21 use std::path::{Path, PathBuf};
24 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
36 pub(crate) mod unescape;
37 use unescape::{unescape_str, unescape_char, unescape_byte_str, unescape_byte};
39 pub(crate) mod unescape_error_reporting;
41 /// Info about a parsing session.
42 pub struct ParseSess {
43 pub span_diagnostic: Handler,
44 pub unstable_features: UnstableFeatures,
45 pub config: CrateConfig,
46 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
47 /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
48 pub raw_identifier_spans: Lock<Vec<Span>>,
49 /// The registered diagnostics codes.
50 crate registered_diagnostics: Lock<ErrorMap>,
51 /// Used to determine and report recursive module inclusions.
52 included_mod_stack: Lock<Vec<PathBuf>>,
53 source_map: Lrc<SourceMap>,
54 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
55 /// Contains the spans of block expressions that could have been incomplete based on the
56 /// operation token that followed it, but that the parser cannot identify without further
58 pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
62 pub fn new(file_path_mapping: FilePathMapping) -> Self {
63 let cm = Lrc::new(SourceMap::new(file_path_mapping));
64 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
68 ParseSess::with_span_handler(handler, cm)
71 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
73 span_diagnostic: handler,
74 unstable_features: UnstableFeatures::from_environment(),
75 config: FxHashSet::default(),
76 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
77 raw_identifier_spans: Lock::new(Vec::new()),
78 registered_diagnostics: Lock::new(ErrorMap::new()),
79 included_mod_stack: Lock::new(vec![]),
81 buffered_lints: Lock::new(vec![]),
82 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
87 pub fn source_map(&self) -> &SourceMap {
91 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
92 lint_id: BufferedEarlyLintId,
97 self.buffered_lints.with_lock(|buffered_lints| {
98 buffered_lints.push(BufferedEarlyLint{
107 /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
108 /// parser to continue parsing the following operation as part of the same expression.
109 pub fn expr_parentheses_needed(
111 err: &mut DiagnosticBuilder<'_>,
113 alt_snippet: Option<String>,
115 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
118 "parentheses are required to parse this as an expression",
119 format!("({})", snippet),
120 Applicability::MachineApplicable,
127 pub struct Directory<'a> {
128 pub path: Cow<'a, Path>,
129 pub ownership: DirectoryOwnership,
132 #[derive(Copy, Clone)]
133 pub enum DirectoryOwnership {
135 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
136 relative: Option<ast::Ident>,
139 UnownedViaMod(bool /* legacy warnings? */),
142 // a bunch of utility functions of the form parse_<thing>_from_<source>
143 // where <thing> includes crate, expr, item, stmt, tts, and one that
144 // uses a HOF to parse anything, and <source> includes file and
147 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
148 let mut parser = new_parser_from_file(sess, input);
149 parser.parse_crate_mod()
152 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
153 -> PResult<'a, Vec<ast::Attribute>> {
154 let mut parser = new_parser_from_file(sess, input);
155 parser.parse_inner_attributes()
158 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
159 -> PResult<'_, ast::Crate> {
160 new_parser_from_source_str(sess, name, source).parse_crate_mod()
163 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
164 -> PResult<'_, Vec<ast::Attribute>> {
165 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
168 pub fn parse_stream_from_source_str(
172 override_span: Option<Span>,
174 let (stream, mut errors) = source_file_to_stream(
176 sess.source_map().new_source_file(name, source),
179 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
183 /// Creates a new parser from a source string.
184 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
185 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
188 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
190 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
191 -> Result<Parser<'_>, Vec<Diagnostic>>
193 let mut parser = maybe_source_file_to_parser(sess,
194 sess.source_map().new_source_file(name, source))?;
195 parser.recurse_into_file_modules = false;
199 /// Creates a new parser, handling errors as appropriate
200 /// if the file doesn't exist
201 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
202 source_file_to_parser(sess, file_to_source_file(sess, path, None))
205 /// Creates a new parser, returning buffered diagnostics if the file doesn't
206 /// exist or from lexing the initial token stream.
207 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
208 -> Result<Parser<'a>, Vec<Diagnostic>> {
209 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
210 maybe_source_file_to_parser(sess, file)
213 /// Given a session, a crate config, a path, and a span, add
214 /// the file at the given path to the source_map, and return a parser.
215 /// On an error, use the given span as the source of the problem.
216 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
218 directory_ownership: DirectoryOwnership,
219 module_name: Option<String>,
220 sp: Span) -> Parser<'a> {
221 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
222 p.directory.ownership = directory_ownership;
223 p.root_module_name = module_name;
227 /// Given a source_file and config, return a parser
228 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
229 panictry_buffer!(&sess.span_diagnostic,
230 maybe_source_file_to_parser(sess, source_file))
233 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
234 /// initial token stream.
235 fn maybe_source_file_to_parser(
237 source_file: Lrc<SourceFile>,
238 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
239 let end_pos = source_file.end_pos;
240 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
241 let mut parser = stream_to_parser(sess, stream);
242 parser.unclosed_delims = unclosed_delims;
243 if parser.token == token::Eof && parser.span.is_dummy() {
244 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
250 // must preserve old name for now, because quote! from the *existing*
251 // compiler expands into it
252 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
253 stream_to_parser(sess, tts.into_iter().collect())
259 /// Given a session and a path and an optional span (for error reporting),
260 /// add the path to the session's source_map and return the new source_file or
261 /// error when a file can't be read.
262 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
263 -> Result<Lrc<SourceFile>, Diagnostic> {
264 sess.source_map().load_file(path)
266 let msg = format!("couldn't read {}: {}", path.display(), e);
267 let mut diag = Diagnostic::new(Level::Fatal, &msg);
268 if let Some(sp) = spanopt {
275 /// Given a session and a path and an optional span (for error reporting),
276 /// add the path to the session's `source_map` and return the new `source_file`.
277 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
279 match try_file_to_source_file(sess, path, spanopt) {
280 Ok(source_file) => source_file,
282 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
288 /// Given a source_file, produces a sequence of token trees.
289 pub fn source_file_to_stream(
291 source_file: Lrc<SourceFile>,
292 override_span: Option<Span>,
293 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
294 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
297 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
298 /// parsing the token tream.
299 pub fn maybe_file_to_stream(
301 source_file: Lrc<SourceFile>,
302 override_span: Option<Span>,
303 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
304 let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
307 match srdr.parse_all_token_trees() {
308 Ok(stream) => Ok((stream, srdr.unmatched_braces)),
310 let mut buffer = Vec::with_capacity(1);
311 err.buffer(&mut buffer);
312 // Not using `emit_unclosed_delims` to use `db.buffer`
313 for unmatched in srdr.unmatched_braces {
314 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
315 "incorrect close delimiter: `{}`",
316 token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
318 db.span_label(unmatched.found_span, "incorrect close delimiter");
319 if let Some(sp) = unmatched.candidate_span {
320 db.span_label(sp, "close delimiter possibly meant for this");
322 if let Some(sp) = unmatched.unclosed_span {
323 db.span_label(sp, "un-closed delimiter");
325 db.buffer(&mut buffer);
332 /// Given stream and the `ParseSess`, produces a parser.
333 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> {
334 Parser::new(sess, stream, None, true, false)
337 /// Parses a string representing a raw string literal into its final form. The
338 /// only operation this does is convert embedded CRLF into a single LF.
339 fn raw_str_lit(lit: &str) -> String {
340 debug!("raw_str_lit: given {}", lit.escape_default());
341 let mut res = String::with_capacity(lit.len());
343 let mut chars = lit.chars().peekable();
344 while let Some(c) = chars.next() {
346 if *chars.peek().unwrap() != '\n' {
347 panic!("lexer accepted bare CR");
360 // check if `s` looks like i32 or u1234 etc.
361 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
362 s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
366 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
368 Some(($span, $diag)) => { $($body)* }
374 crate fn expect_no_suffix(sp: Span, diag: &Handler, kind: &str, suffix: Option<ast::Name>) {
376 None => {/* everything ok */}
378 let text = suf.as_str();
380 diag.span_bug(sp, "found empty literal suffix in Some")
382 let mut err = if kind == "a tuple index" &&
383 ["i32", "u32", "isize", "usize"].contains(&text.to_string().as_str())
385 // #59553: warn instead of reject out of hand to allow the fix to percolate
386 // through the ecosystem when people fix their macros
387 let mut err = diag.struct_span_warn(
389 &format!("suffixes on {} are invalid", kind),
392 "`{}` is *temporarily* accepted on tuple index fields as it was \
393 incorrectly accepted on stable for a few releases",
397 "on proc macros, you'll want to use `syn::Index::from` or \
398 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
399 to tuple field access",
402 "for more context, see https://github.com/rust-lang/rust/issues/60210",
406 diag.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
408 err.span_label(sp, format!("invalid suffix `{}`", text));
415 /// Converts literal token with a suffix into a semantic literal.
416 /// Works speculatively and may return `None` is diagnostic handler is not passed.
417 /// If diagnostic handler is passed, always returns `Some`,
418 /// possibly after reporting non-fatal errors and recovery.
419 crate fn from_lit_token(
422 diag: Option<(Span, &Handler)>
423 ) -> Option<LitKind> {
424 if suf.is_some() && !lit.may_have_suffix() {
425 err!(diag, |span, diag| {
426 expect_no_suffix(span, diag, &format!("a {}", lit.literal_name()), suf)
432 assert!(i == keywords::True.name() || i == keywords::False.name());
433 LitKind::Bool(i == keywords::True.name())
436 match unescape_byte(&i.as_str()) {
437 Ok(c) => LitKind::Byte(c),
438 Err(_) => LitKind::Err(i),
442 match unescape_char(&i.as_str()) {
443 Ok(c) => LitKind::Char(c),
444 Err(_) => LitKind::Err(i),
447 token::Err(i) => LitKind::Err(i),
449 // There are some valid suffixes for integer and float literals,
450 // so all the handling is done internally.
451 token::Integer(s) => return integer_lit(&s.as_str(), suf, diag),
452 token::Float(s) => return float_lit(&s.as_str(), suf, diag),
454 token::Str_(mut sym) => {
455 // If there are no characters requiring special treatment we can
456 // reuse the symbol from the Token. Otherwise, we must generate a
457 // new symbol because the string in the LitKind is different to the
458 // string in the Token.
459 let mut has_error = false;
460 let s = &sym.as_str();
461 if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
462 let mut buf = String::with_capacity(s.len());
463 unescape_str(s, &mut |_, unescaped_char| {
464 match unescaped_char {
465 Ok(c) => buf.push(c),
466 Err(_) => has_error = true,
470 return Some(LitKind::Err(sym));
472 sym = Symbol::intern(&buf)
475 LitKind::Str(sym, ast::StrStyle::Cooked)
477 token::StrRaw(mut sym, n) => {
479 let s = &sym.as_str();
480 if s.contains('\r') {
481 sym = Symbol::intern(&raw_str_lit(s));
483 LitKind::Str(sym, ast::StrStyle::Raw(n))
485 token::ByteStr(i) => {
487 let mut buf = Vec::with_capacity(s.len());
488 let mut has_error = false;
489 unescape_byte_str(s, &mut |_, unescaped_byte| {
490 match unescaped_byte {
491 Ok(c) => buf.push(c),
492 Err(_) => has_error = true,
496 return Some(LitKind::Err(i));
499 LitKind::ByteStr(Lrc::new(buf))
501 token::ByteStrRaw(i, _) => {
502 LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))
508 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
510 debug!("filtered_float_lit: {}, {:?}", data, suffix);
511 let suffix = match suffix {
512 Some(suffix) => suffix,
513 None => return Some(LitKind::FloatUnsuffixed(data)),
516 Some(match &*suffix.as_str() {
517 "f32" => LitKind::Float(data, ast::FloatTy::F32),
518 "f64" => LitKind::Float(data, ast::FloatTy::F64),
520 err!(diag, |span, diag| {
521 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
522 // if it looks like a width, lets try to be helpful.
523 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
524 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
526 let msg = format!("invalid suffix `{}` for float literal", suf);
527 diag.struct_span_err(span, &msg)
528 .span_label(span, format!("invalid suffix `{}`", suf))
529 .help("valid suffixes are `f32` and `f64`")
534 LitKind::FloatUnsuffixed(data)
538 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
540 debug!("float_lit: {:?}, {:?}", s, suffix);
541 // FIXME #2252: bounds checking float literals is deferred until trans
543 // Strip underscores without allocating a new String unless necessary.
545 let s = if s.chars().any(|c| c == '_') {
546 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
552 filtered_float_lit(Symbol::intern(s), suffix, diag)
555 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
557 // s can only be ascii, byte indexing is fine
559 // Strip underscores without allocating a new String unless necessary.
561 let mut s = if s.chars().any(|c| c == '_') {
562 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
568 debug!("integer_lit: {}, {:?}", s, suffix);
572 let mut ty = ast::LitIntType::Unsuffixed;
574 if s.starts_with('0') && s.len() > 1 {
575 match s.as_bytes()[1] {
583 // 1f64 and 2f32 etc. are valid float literals.
584 if let Some(suf) = suffix {
585 if looks_like_width_suffix(&['f'], &suf.as_str()) {
586 let err = match base {
587 16 => Some("hexadecimal float literal is not supported"),
588 8 => Some("octal float literal is not supported"),
589 2 => Some("binary float literal is not supported"),
592 if let Some(err) = err {
593 err!(diag, |span, diag| {
594 diag.struct_span_err(span, err)
595 .span_label(span, "not supported")
599 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
607 if let Some(suf) = suffix {
608 if suf.as_str().is_empty() {
609 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
611 ty = match &*suf.as_str() {
612 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
613 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
614 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
615 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
616 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
617 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
618 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
619 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
620 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
621 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
622 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
623 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
625 // i<digits> and u<digits> look like widths, so lets
626 // give an error message along those lines
627 err!(diag, |span, diag| {
628 if looks_like_width_suffix(&['i', 'u'], suf) {
629 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
630 diag.struct_span_err(span, &msg)
631 .help("valid widths are 8, 16, 32, 64 and 128")
634 let msg = format!("invalid suffix `{}` for numeric literal", suf);
635 diag.struct_span_err(span, &msg)
636 .span_label(span, format!("invalid suffix `{}`", suf))
637 .help("the suffix must be one of the integral types \
638 (`u32`, `isize`, etc)")
648 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
649 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
651 Some(match u128::from_str_radix(s, base) {
652 Ok(r) => LitKind::Int(r, ty),
654 // small bases are lexed as if they were base 10, e.g, the string
655 // might be `0b10201`. This will cause the conversion above to fail,
656 // but these cases have errors in the lexer: we don't want to emit
657 // two errors, and we especially don't want to emit this error since
658 // it isn't necessarily true.
659 let already_errored = base < 10 &&
660 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
662 if !already_errored {
663 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
670 /// A sequence separator.
672 /// The seperator token.
673 pub sep: Option<token::Token>,
674 /// `true` if a trailing separator is allowed.
675 pub trailing_sep_allowed: bool,
679 pub fn trailing_allowed(t: token::Token) -> SeqSep {
682 trailing_sep_allowed: true,
686 pub fn none() -> SeqSep {
689 trailing_sep_allowed: false,
697 use crate::ast::{self, Ident, PatKind};
698 use crate::attr::first_attr_value_str_by_name;
700 use crate::print::pprust::item_to_string;
701 use crate::tokenstream::{DelimSpan, TokenTree};
702 use crate::util::parser_testing::string_to_stream;
703 use crate::util::parser_testing::{string_to_expr, string_to_item};
704 use crate::with_globals;
705 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
709 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
710 /// when a syntax error occurred.
711 fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
712 -> PResult<'_, Option<P<ast::Item>>> {
713 new_parser_from_source_str(sess, name, source).parse_item()
716 // produce a syntax_pos::span
717 fn sp(a: u32, b: u32) -> Span {
718 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
722 #[test] fn bad_path_expr_1() {
724 string_to_expr("::abc::def::return".to_string());
728 // check the token-tree-ization of macros
730 fn string_to_tts_macro () {
733 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
734 let tts: &[TokenTree] = &tts[..];
736 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
739 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
740 Some(&TokenTree::Token(_, token::Not)),
741 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
742 Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
744 if name_macro_rules.name == "macro_rules"
745 && name_zip.name == "zip" => {
746 let tts = ¯o_tts.trees().collect::<Vec<_>>();
747 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
750 Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
751 Some(&TokenTree::Token(_, token::FatArrow)),
752 Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
754 if macro_delim == token::Paren => {
755 let tts = &first_tts.trees().collect::<Vec<_>>();
756 match (tts.len(), tts.get(0), tts.get(1)) {
759 Some(&TokenTree::Token(_, token::Dollar)),
760 Some(&TokenTree::Token(_, token::Ident(ident, false))),
762 if first_delim == token::Paren && ident.name == "a" => {},
763 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
765 let tts = &second_tts.trees().collect::<Vec<_>>();
766 match (tts.len(), tts.get(0), tts.get(1)) {
769 Some(&TokenTree::Token(_, token::Dollar)),
770 Some(&TokenTree::Token(_, token::Ident(ident, false))),
772 if second_delim == token::Paren && ident.name == "a" => {},
773 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
776 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
779 _ => panic!("value: {:?}",tts),
785 fn string_to_tts_1() {
787 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
789 let expected = TokenStream::new(vec![
790 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
791 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
792 TokenTree::Delimited(
793 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
794 token::DelimToken::Paren,
795 TokenStream::new(vec![
796 TokenTree::Token(sp(6, 7),
797 token::Ident(Ident::from_str("b"), false)).into(),
798 TokenTree::Token(sp(8, 9), token::Colon).into(),
799 TokenTree::Token(sp(10, 13),
800 token::Ident(Ident::from_str("i32"), false)).into(),
803 TokenTree::Delimited(
804 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
805 token::DelimToken::Brace,
806 TokenStream::new(vec![
807 TokenTree::Token(sp(17, 18),
808 token::Ident(Ident::from_str("b"), false)).into(),
809 TokenTree::Token(sp(18, 19), token::Semi).into(),
814 assert_eq!(tts, expected);
818 #[test] fn parse_use() {
820 let use_s = "use foo::bar::baz;";
821 let vitem = string_to_item(use_s.to_string()).unwrap();
822 let vitem_s = item_to_string(&vitem);
823 assert_eq!(&vitem_s[..], use_s);
825 let use_s = "use foo::bar as baz;";
826 let vitem = string_to_item(use_s.to_string()).unwrap();
827 let vitem_s = item_to_string(&vitem);
828 assert_eq!(&vitem_s[..], use_s);
832 #[test] fn parse_extern_crate() {
834 let ex_s = "extern crate foo;";
835 let vitem = string_to_item(ex_s.to_string()).unwrap();
836 let vitem_s = item_to_string(&vitem);
837 assert_eq!(&vitem_s[..], ex_s);
839 let ex_s = "extern crate foo as bar;";
840 let vitem = string_to_item(ex_s.to_string()).unwrap();
841 let vitem_s = item_to_string(&vitem);
842 assert_eq!(&vitem_s[..], ex_s);
846 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
847 let item = string_to_item(src.to_string()).unwrap();
849 struct PatIdentVisitor {
852 impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
853 fn visit_pat(&mut self, p: &'a ast::Pat) {
855 PatKind::Ident(_ , ref spannedident, _) => {
856 self.spans.push(spannedident.span.clone());
859 crate::visit::walk_pat(self, p);
864 let mut v = PatIdentVisitor { spans: Vec::new() };
865 crate::visit::walk_item(&mut v, &item);
869 #[test] fn span_of_self_arg_pat_idents_are_correct() {
872 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
873 "impl z { fn a (&mut self, &myarg: i32) {} }",
874 "impl z { fn a (&'a self, &myarg: i32) {} }",
875 "impl z { fn a (self, &myarg: i32) {} }",
876 "impl z { fn a (self: Foo, &myarg: i32) {} }",
880 let spans = get_spans_of_pat_idents(src);
881 let (lo, hi) = (spans[0].lo(), spans[0].hi());
882 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
883 "\"{}\" != \"self\". src=\"{}\"",
884 &src[lo.to_usize()..hi.to_usize()], src)
889 #[test] fn parse_exprs () {
891 // just make sure that they parse....
892 string_to_expr("3 + 4".to_string());
893 string_to_expr("a::z.froob(b,&(987+3))".to_string());
897 #[test] fn attrs_fix_bug () {
899 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
900 -> Result<Box<Writer>, String> {
903 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
907 fn wb() -> c_int { O_WRONLY as c_int }
909 let mut fflags: c_int = wb();
914 #[test] fn crlf_doc_comments() {
916 let sess = ParseSess::new(FilePathMapping::empty());
918 let name_1 = FileName::Custom("crlf_source_1".to_string());
919 let source = "/// doc comment\r\nfn foo() {}".to_string();
920 let item = parse_item_from_source_str(name_1, source, &sess)
922 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
923 assert_eq!(doc, "/// doc comment");
925 let name_2 = FileName::Custom("crlf_source_2".to_string());
926 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
927 let item = parse_item_from_source_str(name_2, source, &sess)
929 let docs = item.attrs.iter().filter(|a| a.path == "doc")
930 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
931 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
932 assert_eq!(&docs[..], b);
934 let name_3 = FileName::Custom("clrf_source_3".to_string());
935 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
936 let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
937 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
938 assert_eq!(doc, "/** doc comment\n * with CRLF */");
944 fn parse_expr_from_source_str(
945 name: FileName, source: String, sess: &ParseSess
946 ) -> PResult<'_, P<ast::Expr>> {
947 new_parser_from_source_str(sess, name, source).parse_expr()
951 let sess = ParseSess::new(FilePathMapping::empty());
952 let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
953 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
955 let tts: Vec<_> = match expr.node {
956 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
957 _ => panic!("not a macro"),
960 let span = tts.iter().rev().next().unwrap().span();
962 match sess.source_map().span_to_snippet(span) {
963 Ok(s) => assert_eq!(&s[..], "{ body }"),
964 Err(_) => panic!("could not get snippet"),
969 // This tests that when parsing a string (rather than a file) we don't try
970 // and read in a file for a module declaration and just parse a stub.
971 // See `recurse_into_file_modules` in the parser.
973 fn out_of_line_mod() {
975 let sess = ParseSess::new(FilePathMapping::empty());
976 let item = parse_item_from_source_str(
977 PathBuf::from("foo").into(),
978 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
982 if let ast::ItemKind::Mod(ref m) = item.node {
983 assert!(m.items.len() == 2);