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::{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};
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 /// Contains the spans of block expressions that could have been incomplete based on the
51 /// operation token that followed it, but that the parser cannot identify without further
53 pub abiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
57 pub fn new(file_path_mapping: FilePathMapping) -> Self {
58 let cm = Lrc::new(SourceMap::new(file_path_mapping));
59 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
63 ParseSess::with_span_handler(handler, cm)
66 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
68 span_diagnostic: handler,
69 unstable_features: UnstableFeatures::from_environment(),
70 config: FxHashSet::default(),
71 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
72 raw_identifier_spans: Lock::new(Vec::new()),
73 registered_diagnostics: Lock::new(ErrorMap::new()),
74 included_mod_stack: Lock::new(vec![]),
76 buffered_lints: Lock::new(vec![]),
77 abiguous_block_expr_parse: Lock::new(FxHashMap::default()),
82 pub fn source_map(&self) -> &SourceMap {
86 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
87 lint_id: BufferedEarlyLintId,
92 self.buffered_lints.with_lock(|buffered_lints| {
93 buffered_lints.push(BufferedEarlyLint{
102 /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
103 /// parser to continue parsing the following operation as part of the same expression.
104 pub fn expr_parentheses_needed(
106 err: &mut DiagnosticBuilder<'_>,
108 alt_snippet: Option<String>,
110 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
113 "parentheses are required to parse this as an expression",
114 format!("({})", snippet),
115 Applicability::MachineApplicable,
122 pub struct Directory<'a> {
123 pub path: Cow<'a, Path>,
124 pub ownership: DirectoryOwnership,
127 #[derive(Copy, Clone)]
128 pub enum DirectoryOwnership {
130 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
131 relative: Option<ast::Ident>,
134 UnownedViaMod(bool /* legacy warnings? */),
137 // a bunch of utility functions of the form parse_<thing>_from_<source>
138 // where <thing> includes crate, expr, item, stmt, tts, and one that
139 // uses a HOF to parse anything, and <source> includes file and
142 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
143 let mut parser = new_parser_from_file(sess, input);
144 parser.parse_crate_mod()
147 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
148 -> PResult<'a, Vec<ast::Attribute>> {
149 let mut parser = new_parser_from_file(sess, input);
150 parser.parse_inner_attributes()
153 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
154 -> PResult<'_, ast::Crate> {
155 new_parser_from_source_str(sess, name, source).parse_crate_mod()
158 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
159 -> PResult<'_, Vec<ast::Attribute>> {
160 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
163 pub fn parse_stream_from_source_str(
167 override_span: Option<Span>,
169 let (stream, mut errors) = source_file_to_stream(
171 sess.source_map().new_source_file(name, source),
174 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
178 /// Creates a new parser from a source string.
179 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
180 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
183 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
185 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
186 -> Result<Parser<'_>, Vec<Diagnostic>>
188 let mut parser = maybe_source_file_to_parser(sess,
189 sess.source_map().new_source_file(name, source))?;
190 parser.recurse_into_file_modules = false;
194 /// Creates a new parser, handling errors as appropriate
195 /// if the file doesn't exist
196 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
197 source_file_to_parser(sess, file_to_source_file(sess, path, None))
200 /// Creates a new parser, returning buffered diagnostics if the file doesn't
201 /// exist or from lexing the initial token stream.
202 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
203 -> Result<Parser<'a>, Vec<Diagnostic>> {
204 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
205 maybe_source_file_to_parser(sess, file)
208 /// Given a session, a crate config, a path, and a span, add
209 /// the file at the given path to the source_map, and return a parser.
210 /// On an error, use the given span as the source of the problem.
211 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
213 directory_ownership: DirectoryOwnership,
214 module_name: Option<String>,
215 sp: Span) -> Parser<'a> {
216 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
217 p.directory.ownership = directory_ownership;
218 p.root_module_name = module_name;
222 /// Given a source_file and config, return a parser
223 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
224 panictry_buffer!(&sess.span_diagnostic,
225 maybe_source_file_to_parser(sess, source_file))
228 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
229 /// initial token stream.
230 fn maybe_source_file_to_parser(
232 source_file: Lrc<SourceFile>,
233 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
234 let end_pos = source_file.end_pos;
235 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
236 let mut parser = stream_to_parser(sess, stream);
237 parser.unclosed_delims = unclosed_delims;
238 if parser.token == token::Eof && parser.span.is_dummy() {
239 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
245 // must preserve old name for now, because quote! from the *existing*
246 // compiler expands into it
247 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
248 stream_to_parser(sess, tts.into_iter().collect())
254 /// Given a session and a path and an optional span (for error reporting),
255 /// add the path to the session's source_map and return the new source_file or
256 /// error when a file can't be read.
257 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
258 -> Result<Lrc<SourceFile>, Diagnostic> {
259 sess.source_map().load_file(path)
261 let msg = format!("couldn't read {}: {}", path.display(), e);
262 let mut diag = Diagnostic::new(Level::Fatal, &msg);
263 if let Some(sp) = spanopt {
270 /// Given a session and a path and an optional span (for error reporting),
271 /// add the path to the session's `source_map` and return the new `source_file`.
272 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
274 match try_file_to_source_file(sess, path, spanopt) {
275 Ok(source_file) => source_file,
277 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
283 /// Given a source_file, produces a sequence of token trees.
284 pub fn source_file_to_stream(
286 source_file: Lrc<SourceFile>,
287 override_span: Option<Span>,
288 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
289 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
292 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
293 /// parsing the token tream.
294 pub fn maybe_file_to_stream(
296 source_file: Lrc<SourceFile>,
297 override_span: Option<Span>,
298 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
299 let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
302 match srdr.parse_all_token_trees() {
303 Ok(stream) => Ok((stream, srdr.unmatched_braces)),
305 let mut buffer = Vec::with_capacity(1);
306 err.buffer(&mut buffer);
307 // Not using `emit_unclosed_delims` to use `db.buffer`
308 for unmatched in srdr.unmatched_braces {
309 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
310 "incorrect close delimiter: `{}`",
311 token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
313 db.span_label(unmatched.found_span, "incorrect close delimiter");
314 if let Some(sp) = unmatched.candidate_span {
315 db.span_label(sp, "close delimiter possibly meant for this");
317 if let Some(sp) = unmatched.unclosed_span {
318 db.span_label(sp, "un-closed delimiter");
320 db.buffer(&mut buffer);
327 /// Given stream and the `ParseSess`, produces a parser.
328 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> {
329 Parser::new(sess, stream, None, true, false)
332 /// Parses a string representing a character literal into its final form.
333 /// Rather than just accepting/rejecting a given literal, unescapes it as
334 /// well. Can take any slice prefixed by a character escape. Returns the
335 /// character and the number of characters consumed.
336 fn char_lit(lit: &str, diag: Option<(Span, &Handler)>) -> (char, isize) {
339 // Handle non-escaped chars first.
340 if lit.as_bytes()[0] != b'\\' {
341 // If the first byte isn't '\\' it might part of a multi-byte char, so
342 // get the char with chars().
343 let c = lit.chars().next().unwrap();
347 // Handle escaped chars.
348 match lit.as_bytes()[1] as char {
357 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
358 let c = char::from_u32(v).unwrap();
362 assert_eq!(lit.as_bytes()[2], b'{');
363 let idx = lit.find('}').unwrap();
365 // All digits and '_' are ascii, so treat each byte as a char.
367 for c in lit[3..idx].bytes() {
368 let c = char::from(c);
370 let x = c.to_digit(16).unwrap();
371 v = v.checked_mul(16).unwrap().checked_add(x).unwrap();
374 let c = char::from_u32(v).unwrap_or_else(|| {
375 if let Some((span, diag)) = diag {
376 let mut diag = diag.struct_span_err(span, "invalid unicode character escape");
378 diag.help("unicode escape must be at most 10FFFF").emit();
380 diag.help("unicode escape must not be a surrogate").emit();
385 (c, (idx + 1) as isize)
387 _ => panic!("lexer should have rejected a bad character escape {}", lit)
391 /// Parses a string representing a string literal into its final form. Does unescaping.
392 fn str_lit(lit: &str, diag: Option<(Span, &Handler)>) -> String {
393 debug!("str_lit: given {}", lit.escape_default());
394 let mut res = String::with_capacity(lit.len());
396 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
398 /// Eat everything up to a non-whitespace.
399 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
401 match it.peek().map(|x| x.1) {
402 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
410 let mut chars = lit.char_indices().peekable();
411 while let Some((i, c)) = chars.next() {
414 let ch = chars.peek().unwrap_or_else(|| {
415 panic!("{}", error(i))
420 } else if ch == '\r' {
422 let ch = chars.peek().unwrap_or_else(|| {
423 panic!("{}", error(i))
427 panic!("lexer accepted bare CR");
431 // otherwise, a normal escape
432 let (c, n) = char_lit(&lit[i..], diag);
433 for _ in 0..n - 1 { // we don't need to move past the first \
440 let ch = chars.peek().unwrap_or_else(|| {
441 panic!("{}", error(i))
445 panic!("lexer accepted bare CR");
454 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
455 debug!("parse_str_lit: returning {}", res);
459 /// Parses a string representing a raw string literal into its final form. The
460 /// only operation this does is convert embedded CRLF into a single LF.
461 fn raw_str_lit(lit: &str) -> String {
462 debug!("raw_str_lit: given {}", lit.escape_default());
463 let mut res = String::with_capacity(lit.len());
465 let mut chars = lit.chars().peekable();
466 while let Some(c) = chars.next() {
468 if *chars.peek().unwrap() != '\n' {
469 panic!("lexer accepted bare CR");
482 // check if `s` looks like i32 or u1234 etc.
483 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
484 s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
488 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
490 Some(($span, $diag)) => { $($body)* }
496 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
497 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
501 token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
502 token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str(), diag).0))),
503 token::Err(i) => (true, Some(LitKind::Err(i))),
505 // There are some valid suffixes for integer and float literals,
506 // so all the handling is done internally.
507 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
508 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
510 token::Str_(mut sym) => {
511 // If there are no characters requiring special treatment we can
512 // reuse the symbol from the Token. Otherwise, we must generate a
513 // new symbol because the string in the LitKind is different to the
514 // string in the Token.
515 let s = &sym.as_str();
516 if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
517 sym = Symbol::intern(&str_lit(s, diag));
519 (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
521 token::StrRaw(mut sym, n) => {
523 let s = &sym.as_str();
524 if s.contains('\r') {
525 sym = Symbol::intern(&raw_str_lit(s));
527 (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
529 token::ByteStr(i) => {
530 (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
532 token::ByteStrRaw(i, _) => {
533 (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
538 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
539 -> Option<ast::LitKind> {
540 debug!("filtered_float_lit: {}, {:?}", data, suffix);
541 let suffix = match suffix {
542 Some(suffix) => suffix,
543 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
546 Some(match &*suffix.as_str() {
547 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
548 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
550 err!(diag, |span, diag| {
551 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
552 // if it looks like a width, lets try to be helpful.
553 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
554 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
556 let msg = format!("invalid suffix `{}` for float literal", suf);
557 diag.struct_span_err(span, &msg)
558 .span_label(span, format!("invalid suffix `{}`", suf))
559 .help("valid suffixes are `f32` and `f64`")
564 ast::LitKind::FloatUnsuffixed(data)
568 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
569 -> Option<ast::LitKind> {
570 debug!("float_lit: {:?}, {:?}", s, suffix);
571 // FIXME #2252: bounds checking float literals is deferred until trans
573 // Strip underscores without allocating a new String unless necessary.
575 let s = if s.chars().any(|c| c == '_') {
576 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
582 filtered_float_lit(Symbol::intern(s), suffix, diag)
585 /// Parses a string representing a byte literal into its final form. Similar to `char_lit`.
586 fn byte_lit(lit: &str) -> (u8, usize) {
587 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
590 (lit.as_bytes()[0], 1)
592 assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
593 let b = match lit.as_bytes()[1] {
602 match u64::from_str_radix(&lit[2..4], 16).ok() {
609 None => panic!(err(3))
617 fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
618 let mut res = Vec::with_capacity(lit.len());
620 let error = |i| panic!("lexer should have rejected {} at {}", lit, i);
622 /// Eat everything up to a non-whitespace.
623 fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
625 match it.peek().map(|x| x.1) {
626 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
634 // byte string literals *must* be ASCII, but the escapes don't have to be
635 let mut chars = lit.bytes().enumerate().peekable();
638 Some((i, b'\\')) => {
639 match chars.peek().unwrap_or_else(|| error(i)).1 {
640 b'\n' => eat(&mut chars),
643 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
644 panic!("lexer accepted bare CR");
649 // otherwise, a normal escape
650 let (c, n) = byte_lit(&lit[i..]);
651 // we don't need to move past the first \
659 Some((i, b'\r')) => {
660 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
661 panic!("lexer accepted bare CR");
666 Some((_, c)) => res.push(c),
674 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
675 -> Option<ast::LitKind> {
676 // s can only be ascii, byte indexing is fine
678 // Strip underscores without allocating a new String unless necessary.
680 let mut s = if s.chars().any(|c| c == '_') {
681 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
687 debug!("integer_lit: {}, {:?}", s, suffix);
691 let mut ty = ast::LitIntType::Unsuffixed;
693 if s.starts_with('0') && s.len() > 1 {
694 match s.as_bytes()[1] {
702 // 1f64 and 2f32 etc. are valid float literals.
703 if let Some(suf) = suffix {
704 if looks_like_width_suffix(&['f'], &suf.as_str()) {
705 let err = match base {
706 16 => Some("hexadecimal float literal is not supported"),
707 8 => Some("octal float literal is not supported"),
708 2 => Some("binary float literal is not supported"),
711 if let Some(err) = err {
712 err!(diag, |span, diag| {
713 diag.struct_span_err(span, err)
714 .span_label(span, "not supported")
718 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
726 if let Some(suf) = suffix {
727 if suf.as_str().is_empty() {
728 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
730 ty = match &*suf.as_str() {
731 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
732 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
733 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
734 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
735 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
736 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
737 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
738 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
739 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
740 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
741 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
742 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
744 // i<digits> and u<digits> look like widths, so lets
745 // give an error message along those lines
746 err!(diag, |span, diag| {
747 if looks_like_width_suffix(&['i', 'u'], suf) {
748 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
749 diag.struct_span_err(span, &msg)
750 .help("valid widths are 8, 16, 32, 64 and 128")
753 let msg = format!("invalid suffix `{}` for numeric literal", suf);
754 diag.struct_span_err(span, &msg)
755 .span_label(span, format!("invalid suffix `{}`", suf))
756 .help("the suffix must be one of the integral types \
757 (`u32`, `isize`, etc)")
767 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
768 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
770 Some(match u128::from_str_radix(s, base) {
771 Ok(r) => ast::LitKind::Int(r, ty),
773 // small bases are lexed as if they were base 10, e.g, the string
774 // might be `0b10201`. This will cause the conversion above to fail,
775 // but these cases have errors in the lexer: we don't want to emit
776 // two errors, and we especially don't want to emit this error since
777 // it isn't necessarily true.
778 let already_errored = base < 10 &&
779 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
781 if !already_errored {
782 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
784 ast::LitKind::Int(0, ty)
789 /// A sequence separator.
791 /// The seperator token.
792 pub sep: Option<token::Token>,
793 /// `true` if a trailing separator is allowed.
794 pub trailing_sep_allowed: bool,
798 pub fn trailing_allowed(t: token::Token) -> SeqSep {
801 trailing_sep_allowed: true,
805 pub fn none() -> SeqSep {
808 trailing_sep_allowed: false,
816 use crate::ast::{self, Ident, PatKind};
817 use crate::attr::first_attr_value_str_by_name;
819 use crate::print::pprust::item_to_string;
820 use crate::tokenstream::{DelimSpan, TokenTree};
821 use crate::util::parser_testing::string_to_stream;
822 use crate::util::parser_testing::{string_to_expr, string_to_item};
823 use crate::with_globals;
824 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
828 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
829 /// when a syntax error occurred.
830 fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
831 -> PResult<'_, Option<P<ast::Item>>> {
832 new_parser_from_source_str(sess, name, source).parse_item()
835 // produce a syntax_pos::span
836 fn sp(a: u32, b: u32) -> Span {
837 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
841 #[test] fn bad_path_expr_1() {
843 string_to_expr("::abc::def::return".to_string());
847 // check the token-tree-ization of macros
849 fn string_to_tts_macro () {
852 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
853 let tts: &[TokenTree] = &tts[..];
855 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
858 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
859 Some(&TokenTree::Token(_, token::Not)),
860 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
861 Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
863 if name_macro_rules.name == "macro_rules"
864 && name_zip.name == "zip" => {
865 let tts = ¯o_tts.trees().collect::<Vec<_>>();
866 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
869 Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
870 Some(&TokenTree::Token(_, token::FatArrow)),
871 Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
873 if macro_delim == token::Paren => {
874 let tts = &first_tts.trees().collect::<Vec<_>>();
875 match (tts.len(), tts.get(0), tts.get(1)) {
878 Some(&TokenTree::Token(_, token::Dollar)),
879 Some(&TokenTree::Token(_, token::Ident(ident, false))),
881 if first_delim == token::Paren && ident.name == "a" => {},
882 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
884 let tts = &second_tts.trees().collect::<Vec<_>>();
885 match (tts.len(), tts.get(0), tts.get(1)) {
888 Some(&TokenTree::Token(_, token::Dollar)),
889 Some(&TokenTree::Token(_, token::Ident(ident, false))),
891 if second_delim == token::Paren && ident.name == "a" => {},
892 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
895 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
898 _ => panic!("value: {:?}",tts),
904 fn string_to_tts_1() {
906 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
908 let expected = TokenStream::new(vec![
909 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
910 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
911 TokenTree::Delimited(
912 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
913 token::DelimToken::Paren,
914 TokenStream::new(vec![
915 TokenTree::Token(sp(6, 7),
916 token::Ident(Ident::from_str("b"), false)).into(),
917 TokenTree::Token(sp(8, 9), token::Colon).into(),
918 TokenTree::Token(sp(10, 13),
919 token::Ident(Ident::from_str("i32"), false)).into(),
922 TokenTree::Delimited(
923 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
924 token::DelimToken::Brace,
925 TokenStream::new(vec![
926 TokenTree::Token(sp(17, 18),
927 token::Ident(Ident::from_str("b"), false)).into(),
928 TokenTree::Token(sp(18, 19), token::Semi).into(),
933 assert_eq!(tts, expected);
937 #[test] fn parse_use() {
939 let use_s = "use foo::bar::baz;";
940 let vitem = string_to_item(use_s.to_string()).unwrap();
941 let vitem_s = item_to_string(&vitem);
942 assert_eq!(&vitem_s[..], use_s);
944 let use_s = "use foo::bar as baz;";
945 let vitem = string_to_item(use_s.to_string()).unwrap();
946 let vitem_s = item_to_string(&vitem);
947 assert_eq!(&vitem_s[..], use_s);
951 #[test] fn parse_extern_crate() {
953 let ex_s = "extern crate foo;";
954 let vitem = string_to_item(ex_s.to_string()).unwrap();
955 let vitem_s = item_to_string(&vitem);
956 assert_eq!(&vitem_s[..], ex_s);
958 let ex_s = "extern crate foo as bar;";
959 let vitem = string_to_item(ex_s.to_string()).unwrap();
960 let vitem_s = item_to_string(&vitem);
961 assert_eq!(&vitem_s[..], ex_s);
965 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
966 let item = string_to_item(src.to_string()).unwrap();
968 struct PatIdentVisitor {
971 impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
972 fn visit_pat(&mut self, p: &'a ast::Pat) {
974 PatKind::Ident(_ , ref spannedident, _) => {
975 self.spans.push(spannedident.span.clone());
978 crate::visit::walk_pat(self, p);
983 let mut v = PatIdentVisitor { spans: Vec::new() };
984 crate::visit::walk_item(&mut v, &item);
988 #[test] fn span_of_self_arg_pat_idents_are_correct() {
991 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
992 "impl z { fn a (&mut self, &myarg: i32) {} }",
993 "impl z { fn a (&'a self, &myarg: i32) {} }",
994 "impl z { fn a (self, &myarg: i32) {} }",
995 "impl z { fn a (self: Foo, &myarg: i32) {} }",
999 let spans = get_spans_of_pat_idents(src);
1000 let (lo, hi) = (spans[0].lo(), spans[0].hi());
1001 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
1002 "\"{}\" != \"self\". src=\"{}\"",
1003 &src[lo.to_usize()..hi.to_usize()], src)
1008 #[test] fn parse_exprs () {
1010 // just make sure that they parse....
1011 string_to_expr("3 + 4".to_string());
1012 string_to_expr("a::z.froob(b,&(987+3))".to_string());
1016 #[test] fn attrs_fix_bug () {
1018 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
1019 -> Result<Box<Writer>, String> {
1022 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1026 fn wb() -> c_int { O_WRONLY as c_int }
1028 let mut fflags: c_int = wb();
1033 #[test] fn crlf_doc_comments() {
1035 let sess = ParseSess::new(FilePathMapping::empty());
1037 let name_1 = FileName::Custom("crlf_source_1".to_string());
1038 let source = "/// doc comment\r\nfn foo() {}".to_string();
1039 let item = parse_item_from_source_str(name_1, source, &sess)
1041 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1042 assert_eq!(doc, "/// doc comment");
1044 let name_2 = FileName::Custom("crlf_source_2".to_string());
1045 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1046 let item = parse_item_from_source_str(name_2, source, &sess)
1048 let docs = item.attrs.iter().filter(|a| a.path == "doc")
1049 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1050 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1051 assert_eq!(&docs[..], b);
1053 let name_3 = FileName::Custom("clrf_source_3".to_string());
1054 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1055 let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
1056 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1057 assert_eq!(doc, "/** doc comment\n * with CRLF */");
1063 fn parse_expr_from_source_str(
1064 name: FileName, source: String, sess: &ParseSess
1065 ) -> PResult<'_, P<ast::Expr>> {
1066 new_parser_from_source_str(sess, name, source).parse_expr()
1070 let sess = ParseSess::new(FilePathMapping::empty());
1071 let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
1072 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
1074 let tts: Vec<_> = match expr.node {
1075 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
1076 _ => panic!("not a macro"),
1079 let span = tts.iter().rev().next().unwrap().span();
1081 match sess.source_map().span_to_snippet(span) {
1082 Ok(s) => assert_eq!(&s[..], "{ body }"),
1083 Err(_) => panic!("could not get snippet"),
1088 // This tests that when parsing a string (rather than a file) we don't try
1089 // and read in a file for a module declaration and just parse a stub.
1090 // See `recurse_into_file_modules` in the parser.
1092 fn out_of_line_mod() {
1094 let sess = ParseSess::new(FilePathMapping::empty());
1095 let item = parse_item_from_source_str(
1096 PathBuf::from("foo").into(),
1097 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
1099 ).unwrap().unwrap();
1101 if let ast::ItemKind::Mod(ref m) = item.node {
1102 assert!(m.items.len() == 2);