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::feature_gate::UnstableFeatures;
7 use crate::parse::parser::Parser;
8 use crate::symbol::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::{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};
22 use std::path::{Path, PathBuf};
25 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
36 /// Info about a parsing session.
37 pub struct ParseSess {
38 pub span_diagnostic: Handler,
39 pub unstable_features: UnstableFeatures,
40 pub config: CrateConfig,
41 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
42 /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
43 pub raw_identifier_spans: Lock<Vec<Span>>,
44 /// The registered diagnostics codes.
45 crate registered_diagnostics: Lock<ErrorMap>,
46 /// Used to determine and report recursive module inclusions.
47 included_mod_stack: Lock<Vec<PathBuf>>,
48 source_map: Lrc<SourceMap>,
49 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
50 pub abiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
54 pub fn new(file_path_mapping: FilePathMapping) -> Self {
55 let cm = Lrc::new(SourceMap::new(file_path_mapping));
56 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
60 ParseSess::with_span_handler(handler, cm)
63 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
65 span_diagnostic: handler,
66 unstable_features: UnstableFeatures::from_environment(),
67 config: FxHashSet::default(),
68 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
69 raw_identifier_spans: Lock::new(Vec::new()),
70 registered_diagnostics: Lock::new(ErrorMap::new()),
71 included_mod_stack: Lock::new(vec![]),
73 buffered_lints: Lock::new(vec![]),
74 abiguous_block_expr_parse: Lock::new(FxHashMap::default()),
79 pub fn source_map(&self) -> &SourceMap {
83 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
84 lint_id: BufferedEarlyLintId,
89 self.buffered_lints.with_lock(|buffered_lints| {
90 buffered_lints.push(BufferedEarlyLint{
101 pub struct Directory<'a> {
102 pub path: Cow<'a, Path>,
103 pub ownership: DirectoryOwnership,
106 #[derive(Copy, Clone)]
107 pub enum DirectoryOwnership {
109 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
110 relative: Option<ast::Ident>,
113 UnownedViaMod(bool /* legacy warnings? */),
116 // a bunch of utility functions of the form parse_<thing>_from_<source>
117 // where <thing> includes crate, expr, item, stmt, tts, and one that
118 // uses a HOF to parse anything, and <source> includes file and
121 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
122 let mut parser = new_parser_from_file(sess, input);
123 parser.parse_crate_mod()
126 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
127 -> PResult<'a, Vec<ast::Attribute>> {
128 let mut parser = new_parser_from_file(sess, input);
129 parser.parse_inner_attributes()
132 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
133 -> PResult<'_, ast::Crate> {
134 new_parser_from_source_str(sess, name, source).parse_crate_mod()
137 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
138 -> PResult<'_, Vec<ast::Attribute>> {
139 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
142 pub fn parse_stream_from_source_str(
146 override_span: Option<Span>,
148 let (stream, mut errors) = source_file_to_stream(
150 sess.source_map().new_source_file(name, source),
153 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
157 /// Creates a new parser from a source string.
158 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
159 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
162 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
164 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
165 -> Result<Parser<'_>, Vec<Diagnostic>>
167 let mut parser = maybe_source_file_to_parser(sess,
168 sess.source_map().new_source_file(name, source))?;
169 parser.recurse_into_file_modules = false;
173 /// Creates a new parser, handling errors as appropriate
174 /// if the file doesn't exist
175 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
176 source_file_to_parser(sess, file_to_source_file(sess, path, None))
179 /// Creates a new parser, returning buffered diagnostics if the file doesn't
180 /// exist or from lexing the initial token stream.
181 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
182 -> Result<Parser<'a>, Vec<Diagnostic>> {
183 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
184 maybe_source_file_to_parser(sess, file)
187 /// Given a session, a crate config, a path, and a span, add
188 /// the file at the given path to the source_map, and return a parser.
189 /// On an error, use the given span as the source of the problem.
190 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
192 directory_ownership: DirectoryOwnership,
193 module_name: Option<String>,
194 sp: Span) -> Parser<'a> {
195 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
196 p.directory.ownership = directory_ownership;
197 p.root_module_name = module_name;
201 /// Given a source_file and config, return a parser
202 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
203 panictry_buffer!(&sess.span_diagnostic,
204 maybe_source_file_to_parser(sess, source_file))
207 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
208 /// initial token stream.
209 fn maybe_source_file_to_parser(
211 source_file: Lrc<SourceFile>,
212 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
213 let end_pos = source_file.end_pos;
214 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
215 let mut parser = stream_to_parser(sess, stream);
216 parser.unclosed_delims = unclosed_delims;
217 if parser.token == token::Eof && parser.span.is_dummy() {
218 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
224 // must preserve old name for now, because quote! from the *existing*
225 // compiler expands into it
226 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
227 stream_to_parser(sess, tts.into_iter().collect())
233 /// Given a session and a path and an optional span (for error reporting),
234 /// add the path to the session's source_map and return the new source_file or
235 /// error when a file can't be read.
236 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
237 -> Result<Lrc<SourceFile>, Diagnostic> {
238 sess.source_map().load_file(path)
240 let msg = format!("couldn't read {}: {}", path.display(), e);
241 let mut diag = Diagnostic::new(Level::Fatal, &msg);
242 if let Some(sp) = spanopt {
249 /// Given a session and a path and an optional span (for error reporting),
250 /// add the path to the session's `source_map` and return the new `source_file`.
251 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
253 match try_file_to_source_file(sess, path, spanopt) {
254 Ok(source_file) => source_file,
256 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
262 /// Given a source_file, produces a sequence of token trees.
263 pub fn source_file_to_stream(
265 source_file: Lrc<SourceFile>,
266 override_span: Option<Span>,
267 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
268 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
271 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
272 /// parsing the token tream.
273 pub fn maybe_file_to_stream(
275 source_file: Lrc<SourceFile>,
276 override_span: Option<Span>,
277 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
278 let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
281 match srdr.parse_all_token_trees() {
282 Ok(stream) => Ok((stream, srdr.unmatched_braces)),
284 let mut buffer = Vec::with_capacity(1);
285 err.buffer(&mut buffer);
286 // Not using `emit_unclosed_delims` to use `db.buffer`
287 for unmatched in srdr.unmatched_braces {
288 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
289 "incorrect close delimiter: `{}`",
290 token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
292 db.span_label(unmatched.found_span, "incorrect close delimiter");
293 if let Some(sp) = unmatched.candidate_span {
294 db.span_label(sp, "close delimiter possibly meant for this");
296 if let Some(sp) = unmatched.unclosed_span {
297 db.span_label(sp, "un-closed delimiter");
299 db.buffer(&mut buffer);
306 /// Given stream and the `ParseSess`, produces a parser.
307 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> {
308 Parser::new(sess, stream, None, true, false)
311 /// Parses a string representing a character literal into its final form.
312 /// Rather than just accepting/rejecting a given literal, unescapes it as
313 /// well. Can take any slice prefixed by a character escape. Returns the
314 /// character and the number of characters consumed.
315 fn char_lit(lit: &str, diag: Option<(Span, &Handler)>) -> (char, isize) {
318 // Handle non-escaped chars first.
319 if lit.as_bytes()[0] != b'\\' {
320 // If the first byte isn't '\\' it might part of a multi-byte char, so
321 // get the char with chars().
322 let c = lit.chars().next().unwrap();
326 // Handle escaped chars.
327 match lit.as_bytes()[1] as char {
336 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
337 let c = char::from_u32(v).unwrap();
341 assert_eq!(lit.as_bytes()[2], b'{');
342 let idx = lit.find('}').unwrap();
344 // All digits and '_' are ascii, so treat each byte as a char.
346 for c in lit[3..idx].bytes() {
347 let c = char::from(c);
349 let x = c.to_digit(16).unwrap();
350 v = v.checked_mul(16).unwrap().checked_add(x).unwrap();
353 let c = char::from_u32(v).unwrap_or_else(|| {
354 if let Some((span, diag)) = diag {
355 let mut diag = diag.struct_span_err(span, "invalid unicode character escape");
357 diag.help("unicode escape must be at most 10FFFF").emit();
359 diag.help("unicode escape must not be a surrogate").emit();
364 (c, (idx + 1) as isize)
366 _ => panic!("lexer should have rejected a bad character escape {}", lit)
370 /// Parses a string representing a string literal into its final form. Does unescaping.
371 fn str_lit(lit: &str, diag: Option<(Span, &Handler)>) -> String {
372 debug!("str_lit: given {}", lit.escape_default());
373 let mut res = String::with_capacity(lit.len());
375 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
377 /// Eat everything up to a non-whitespace.
378 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
380 match it.peek().map(|x| x.1) {
381 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
389 let mut chars = lit.char_indices().peekable();
390 while let Some((i, c)) = chars.next() {
393 let ch = chars.peek().unwrap_or_else(|| {
394 panic!("{}", error(i))
399 } else if ch == '\r' {
401 let ch = chars.peek().unwrap_or_else(|| {
402 panic!("{}", error(i))
406 panic!("lexer accepted bare CR");
410 // otherwise, a normal escape
411 let (c, n) = char_lit(&lit[i..], diag);
412 for _ in 0..n - 1 { // we don't need to move past the first \
419 let ch = chars.peek().unwrap_or_else(|| {
420 panic!("{}", error(i))
424 panic!("lexer accepted bare CR");
433 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
434 debug!("parse_str_lit: returning {}", res);
438 /// Parses a string representing a raw string literal into its final form. The
439 /// only operation this does is convert embedded CRLF into a single LF.
440 fn raw_str_lit(lit: &str) -> String {
441 debug!("raw_str_lit: given {}", lit.escape_default());
442 let mut res = String::with_capacity(lit.len());
444 let mut chars = lit.chars().peekable();
445 while let Some(c) = chars.next() {
447 if *chars.peek().unwrap() != '\n' {
448 panic!("lexer accepted bare CR");
461 // check if `s` looks like i32 or u1234 etc.
462 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
463 s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
467 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
469 Some(($span, $diag)) => { $($body)* }
475 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
476 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
480 token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
481 token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str(), diag).0))),
482 token::Err(i) => (true, Some(LitKind::Err(i))),
484 // There are some valid suffixes for integer and float literals,
485 // so all the handling is done internally.
486 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
487 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
489 token::Str_(mut sym) => {
490 // If there are no characters requiring special treatment we can
491 // reuse the symbol from the Token. Otherwise, we must generate a
492 // new symbol because the string in the LitKind is different to the
493 // string in the Token.
494 let s = &sym.as_str();
495 if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
496 sym = Symbol::intern(&str_lit(s, diag));
498 (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
500 token::StrRaw(mut sym, n) => {
502 let s = &sym.as_str();
503 if s.contains('\r') {
504 sym = Symbol::intern(&raw_str_lit(s));
506 (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
508 token::ByteStr(i) => {
509 (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
511 token::ByteStrRaw(i, _) => {
512 (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
517 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
518 -> Option<ast::LitKind> {
519 debug!("filtered_float_lit: {}, {:?}", data, suffix);
520 let suffix = match suffix {
521 Some(suffix) => suffix,
522 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
525 Some(match &*suffix.as_str() {
526 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
527 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
529 err!(diag, |span, diag| {
530 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
531 // if it looks like a width, lets try to be helpful.
532 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
533 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
535 let msg = format!("invalid suffix `{}` for float literal", suf);
536 diag.struct_span_err(span, &msg)
537 .span_label(span, format!("invalid suffix `{}`", suf))
538 .help("valid suffixes are `f32` and `f64`")
543 ast::LitKind::FloatUnsuffixed(data)
547 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
548 -> Option<ast::LitKind> {
549 debug!("float_lit: {:?}, {:?}", s, suffix);
550 // FIXME #2252: bounds checking float literals is deferred until trans
552 // Strip underscores without allocating a new String unless necessary.
554 let s = if s.chars().any(|c| c == '_') {
555 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
561 filtered_float_lit(Symbol::intern(s), suffix, diag)
564 /// Parses a string representing a byte literal into its final form. Similar to `char_lit`.
565 fn byte_lit(lit: &str) -> (u8, usize) {
566 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
569 (lit.as_bytes()[0], 1)
571 assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
572 let b = match lit.as_bytes()[1] {
581 match u64::from_str_radix(&lit[2..4], 16).ok() {
588 None => panic!(err(3))
596 fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
597 let mut res = Vec::with_capacity(lit.len());
599 let error = |i| panic!("lexer should have rejected {} at {}", lit, i);
601 /// Eat everything up to a non-whitespace.
602 fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
604 match it.peek().map(|x| x.1) {
605 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
613 // byte string literals *must* be ASCII, but the escapes don't have to be
614 let mut chars = lit.bytes().enumerate().peekable();
617 Some((i, b'\\')) => {
618 match chars.peek().unwrap_or_else(|| error(i)).1 {
619 b'\n' => eat(&mut chars),
622 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
623 panic!("lexer accepted bare CR");
628 // otherwise, a normal escape
629 let (c, n) = byte_lit(&lit[i..]);
630 // we don't need to move past the first \
638 Some((i, b'\r')) => {
639 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
640 panic!("lexer accepted bare CR");
645 Some((_, c)) => res.push(c),
653 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
654 -> Option<ast::LitKind> {
655 // s can only be ascii, byte indexing is fine
657 // Strip underscores without allocating a new String unless necessary.
659 let mut s = if s.chars().any(|c| c == '_') {
660 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
666 debug!("integer_lit: {}, {:?}", s, suffix);
670 let mut ty = ast::LitIntType::Unsuffixed;
672 if s.starts_with('0') && s.len() > 1 {
673 match s.as_bytes()[1] {
681 // 1f64 and 2f32 etc. are valid float literals.
682 if let Some(suf) = suffix {
683 if looks_like_width_suffix(&['f'], &suf.as_str()) {
684 let err = match base {
685 16 => Some("hexadecimal float literal is not supported"),
686 8 => Some("octal float literal is not supported"),
687 2 => Some("binary float literal is not supported"),
690 if let Some(err) = err {
691 err!(diag, |span, diag| {
692 diag.struct_span_err(span, err)
693 .span_label(span, "not supported")
697 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
705 if let Some(suf) = suffix {
706 if suf.as_str().is_empty() {
707 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
709 ty = match &*suf.as_str() {
710 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
711 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
712 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
713 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
714 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
715 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
716 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
717 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
718 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
719 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
720 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
721 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
723 // i<digits> and u<digits> look like widths, so lets
724 // give an error message along those lines
725 err!(diag, |span, diag| {
726 if looks_like_width_suffix(&['i', 'u'], suf) {
727 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
728 diag.struct_span_err(span, &msg)
729 .help("valid widths are 8, 16, 32, 64 and 128")
732 let msg = format!("invalid suffix `{}` for numeric literal", suf);
733 diag.struct_span_err(span, &msg)
734 .span_label(span, format!("invalid suffix `{}`", suf))
735 .help("the suffix must be one of the integral types \
736 (`u32`, `isize`, etc)")
746 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
747 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
749 Some(match u128::from_str_radix(s, base) {
750 Ok(r) => ast::LitKind::Int(r, ty),
752 // small bases are lexed as if they were base 10, e.g, the string
753 // might be `0b10201`. This will cause the conversion above to fail,
754 // but these cases have errors in the lexer: we don't want to emit
755 // two errors, and we especially don't want to emit this error since
756 // it isn't necessarily true.
757 let already_errored = base < 10 &&
758 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
760 if !already_errored {
761 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
763 ast::LitKind::Int(0, ty)
768 /// A sequence separator.
770 /// The seperator token.
771 pub sep: Option<token::Token>,
772 /// `true` if a trailing separator is allowed.
773 pub trailing_sep_allowed: bool,
777 pub fn trailing_allowed(t: token::Token) -> SeqSep {
780 trailing_sep_allowed: true,
784 pub fn none() -> SeqSep {
787 trailing_sep_allowed: false,
795 use crate::ast::{self, Ident, PatKind};
796 use crate::attr::first_attr_value_str_by_name;
798 use crate::print::pprust::item_to_string;
799 use crate::tokenstream::{DelimSpan, TokenTree};
800 use crate::util::parser_testing::string_to_stream;
801 use crate::util::parser_testing::{string_to_expr, string_to_item};
802 use crate::with_globals;
803 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
807 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
808 /// when a syntax error occurred.
809 fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
810 -> PResult<'_, Option<P<ast::Item>>> {
811 new_parser_from_source_str(sess, name, source).parse_item()
814 // produce a syntax_pos::span
815 fn sp(a: u32, b: u32) -> Span {
816 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
820 #[test] fn bad_path_expr_1() {
822 string_to_expr("::abc::def::return".to_string());
826 // check the token-tree-ization of macros
828 fn string_to_tts_macro () {
831 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
832 let tts: &[TokenTree] = &tts[..];
834 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
837 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
838 Some(&TokenTree::Token(_, token::Not)),
839 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
840 Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
842 if name_macro_rules.name == "macro_rules"
843 && name_zip.name == "zip" => {
844 let tts = ¯o_tts.trees().collect::<Vec<_>>();
845 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
848 Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
849 Some(&TokenTree::Token(_, token::FatArrow)),
850 Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
852 if macro_delim == token::Paren => {
853 let tts = &first_tts.trees().collect::<Vec<_>>();
854 match (tts.len(), tts.get(0), tts.get(1)) {
857 Some(&TokenTree::Token(_, token::Dollar)),
858 Some(&TokenTree::Token(_, token::Ident(ident, false))),
860 if first_delim == token::Paren && ident.name == "a" => {},
861 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
863 let tts = &second_tts.trees().collect::<Vec<_>>();
864 match (tts.len(), tts.get(0), tts.get(1)) {
867 Some(&TokenTree::Token(_, token::Dollar)),
868 Some(&TokenTree::Token(_, token::Ident(ident, false))),
870 if second_delim == token::Paren && ident.name == "a" => {},
871 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
874 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
877 _ => panic!("value: {:?}",tts),
883 fn string_to_tts_1() {
885 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
887 let expected = TokenStream::new(vec![
888 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
889 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
890 TokenTree::Delimited(
891 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
892 token::DelimToken::Paren,
893 TokenStream::new(vec![
894 TokenTree::Token(sp(6, 7),
895 token::Ident(Ident::from_str("b"), false)).into(),
896 TokenTree::Token(sp(8, 9), token::Colon).into(),
897 TokenTree::Token(sp(10, 13),
898 token::Ident(Ident::from_str("i32"), false)).into(),
901 TokenTree::Delimited(
902 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
903 token::DelimToken::Brace,
904 TokenStream::new(vec![
905 TokenTree::Token(sp(17, 18),
906 token::Ident(Ident::from_str("b"), false)).into(),
907 TokenTree::Token(sp(18, 19), token::Semi).into(),
912 assert_eq!(tts, expected);
916 #[test] fn parse_use() {
918 let use_s = "use foo::bar::baz;";
919 let vitem = string_to_item(use_s.to_string()).unwrap();
920 let vitem_s = item_to_string(&vitem);
921 assert_eq!(&vitem_s[..], use_s);
923 let use_s = "use foo::bar as baz;";
924 let vitem = string_to_item(use_s.to_string()).unwrap();
925 let vitem_s = item_to_string(&vitem);
926 assert_eq!(&vitem_s[..], use_s);
930 #[test] fn parse_extern_crate() {
932 let ex_s = "extern crate foo;";
933 let vitem = string_to_item(ex_s.to_string()).unwrap();
934 let vitem_s = item_to_string(&vitem);
935 assert_eq!(&vitem_s[..], ex_s);
937 let ex_s = "extern crate foo as bar;";
938 let vitem = string_to_item(ex_s.to_string()).unwrap();
939 let vitem_s = item_to_string(&vitem);
940 assert_eq!(&vitem_s[..], ex_s);
944 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
945 let item = string_to_item(src.to_string()).unwrap();
947 struct PatIdentVisitor {
950 impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
951 fn visit_pat(&mut self, p: &'a ast::Pat) {
953 PatKind::Ident(_ , ref spannedident, _) => {
954 self.spans.push(spannedident.span.clone());
957 crate::visit::walk_pat(self, p);
962 let mut v = PatIdentVisitor { spans: Vec::new() };
963 crate::visit::walk_item(&mut v, &item);
967 #[test] fn span_of_self_arg_pat_idents_are_correct() {
970 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
971 "impl z { fn a (&mut self, &myarg: i32) {} }",
972 "impl z { fn a (&'a self, &myarg: i32) {} }",
973 "impl z { fn a (self, &myarg: i32) {} }",
974 "impl z { fn a (self: Foo, &myarg: i32) {} }",
978 let spans = get_spans_of_pat_idents(src);
979 let (lo, hi) = (spans[0].lo(), spans[0].hi());
980 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
981 "\"{}\" != \"self\". src=\"{}\"",
982 &src[lo.to_usize()..hi.to_usize()], src)
987 #[test] fn parse_exprs () {
989 // just make sure that they parse....
990 string_to_expr("3 + 4".to_string());
991 string_to_expr("a::z.froob(b,&(987+3))".to_string());
995 #[test] fn attrs_fix_bug () {
997 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
998 -> Result<Box<Writer>, String> {
1001 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1005 fn wb() -> c_int { O_WRONLY as c_int }
1007 let mut fflags: c_int = wb();
1012 #[test] fn crlf_doc_comments() {
1014 let sess = ParseSess::new(FilePathMapping::empty());
1016 let name_1 = FileName::Custom("crlf_source_1".to_string());
1017 let source = "/// doc comment\r\nfn foo() {}".to_string();
1018 let item = parse_item_from_source_str(name_1, source, &sess)
1020 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1021 assert_eq!(doc, "/// doc comment");
1023 let name_2 = FileName::Custom("crlf_source_2".to_string());
1024 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1025 let item = parse_item_from_source_str(name_2, source, &sess)
1027 let docs = item.attrs.iter().filter(|a| a.path == "doc")
1028 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1029 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1030 assert_eq!(&docs[..], b);
1032 let name_3 = FileName::Custom("clrf_source_3".to_string());
1033 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1034 let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
1035 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1036 assert_eq!(doc, "/** doc comment\n * with CRLF */");
1042 fn parse_expr_from_source_str(
1043 name: FileName, source: String, sess: &ParseSess
1044 ) -> PResult<'_, P<ast::Expr>> {
1045 new_parser_from_source_str(sess, name, source).parse_expr()
1049 let sess = ParseSess::new(FilePathMapping::empty());
1050 let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
1051 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
1053 let tts: Vec<_> = match expr.node {
1054 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
1055 _ => panic!("not a macro"),
1058 let span = tts.iter().rev().next().unwrap().span();
1060 match sess.source_map().span_to_snippet(span) {
1061 Ok(s) => assert_eq!(&s[..], "{ body }"),
1062 Err(_) => panic!("could not get snippet"),
1067 // This tests that when parsing a string (rather than a file) we don't try
1068 // and read in a file for a module declaration and just parse a stub.
1069 // See `recurse_into_file_modules` in the parser.
1071 fn out_of_line_mod() {
1073 let sess = ParseSess::new(FilePathMapping::empty());
1074 let item = parse_item_from_source_str(
1075 PathBuf::from("foo").into(),
1076 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
1078 ).unwrap().unwrap();
1080 if let ast::ItemKind::Mod(ref m) = item.node {
1081 assert!(m.items.len() == 2);