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;
22 use std::path::{Path, PathBuf};
25 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
37 /// Info about a parsing session.
38 pub struct ParseSess {
39 pub span_diagnostic: Handler,
40 pub unstable_features: UnstableFeatures,
41 pub config: CrateConfig,
42 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
43 /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
44 pub raw_identifier_spans: Lock<Vec<Span>>,
45 /// The registered diagnostics codes.
46 crate registered_diagnostics: Lock<ErrorMap>,
47 /// Used to determine and report recursive module inclusions.
48 included_mod_stack: Lock<Vec<PathBuf>>,
49 source_map: Lrc<SourceMap>,
50 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
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![]),
78 pub fn source_map(&self) -> &SourceMap {
82 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
83 lint_id: BufferedEarlyLintId,
88 self.buffered_lints.with_lock(|buffered_lints| {
89 buffered_lints.push(BufferedEarlyLint{
100 pub struct Directory<'a> {
101 pub path: Cow<'a, Path>,
102 pub ownership: DirectoryOwnership,
105 #[derive(Copy, Clone)]
106 pub enum DirectoryOwnership {
108 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
109 relative: Option<ast::Ident>,
112 UnownedViaMod(bool /* legacy warnings? */),
115 // a bunch of utility functions of the form parse_<thing>_from_<source>
116 // where <thing> includes crate, expr, item, stmt, tts, and one that
117 // uses a HOF to parse anything, and <source> includes file and
120 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
121 let mut parser = new_parser_from_file(sess, input);
122 parser.parse_crate_mod()
125 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
126 -> PResult<'a, Vec<ast::Attribute>> {
127 let mut parser = new_parser_from_file(sess, input);
128 parser.parse_inner_attributes()
131 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
132 -> PResult<'_, ast::Crate> {
133 new_parser_from_source_str(sess, name, source).parse_crate_mod()
136 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
137 -> PResult<'_, Vec<ast::Attribute>> {
138 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
141 pub fn parse_stream_from_source_str(
145 override_span: Option<Span>,
147 let (stream, mut errors) = source_file_to_stream(
149 sess.source_map().new_source_file(name, source),
152 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
156 /// Creates a new parser from a source string.
157 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
158 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
161 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
163 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
164 -> Result<Parser<'_>, Vec<Diagnostic>>
166 let mut parser = maybe_source_file_to_parser(sess,
167 sess.source_map().new_source_file(name, source))?;
168 parser.recurse_into_file_modules = false;
172 /// Creates a new parser, handling errors as appropriate
173 /// if the file doesn't exist
174 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
175 source_file_to_parser(sess, file_to_source_file(sess, path, None))
178 /// Creates a new parser, returning buffered diagnostics if the file doesn't
179 /// exist or from lexing the initial token stream.
180 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
181 -> Result<Parser<'a>, Vec<Diagnostic>> {
182 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
183 maybe_source_file_to_parser(sess, file)
186 /// Given a session, a crate config, a path, and a span, add
187 /// the file at the given path to the source_map, and return a parser.
188 /// On an error, use the given span as the source of the problem.
189 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
191 directory_ownership: DirectoryOwnership,
192 module_name: Option<String>,
193 sp: Span) -> Parser<'a> {
194 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
195 p.directory.ownership = directory_ownership;
196 p.root_module_name = module_name;
200 /// Given a source_file and config, return a parser
201 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
202 panictry_buffer!(&sess.span_diagnostic,
203 maybe_source_file_to_parser(sess, source_file))
206 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
207 /// initial token stream.
208 fn maybe_source_file_to_parser(
210 source_file: Lrc<SourceFile>,
211 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
212 let end_pos = source_file.end_pos;
213 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
214 let mut parser = stream_to_parser(sess, stream);
215 parser.unclosed_delims = unclosed_delims;
216 if parser.token == token::Eof && parser.span.is_dummy() {
217 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
223 // must preserve old name for now, because quote! from the *existing*
224 // compiler expands into it
225 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
226 stream_to_parser(sess, tts.into_iter().collect())
232 /// Given a session and a path and an optional span (for error reporting),
233 /// add the path to the session's source_map and return the new source_file or
234 /// error when a file can't be read.
235 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
236 -> Result<Lrc<SourceFile>, Diagnostic> {
237 sess.source_map().load_file(path)
239 let msg = format!("couldn't read {}: {}", path.display(), e);
240 let mut diag = Diagnostic::new(Level::Fatal, &msg);
241 if let Some(sp) = spanopt {
248 /// Given a session and a path and an optional span (for error reporting),
249 /// add the path to the session's `source_map` and return the new `source_file`.
250 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
252 match try_file_to_source_file(sess, path, spanopt) {
253 Ok(source_file) => source_file,
255 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
261 /// Given a source_file, produces a sequence of token trees.
262 pub fn source_file_to_stream(
264 source_file: Lrc<SourceFile>,
265 override_span: Option<Span>,
266 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
267 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
270 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
271 /// parsing the token tream.
272 pub fn maybe_file_to_stream(
274 source_file: Lrc<SourceFile>,
275 override_span: Option<Span>,
276 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
277 let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
280 match srdr.parse_all_token_trees() {
281 Ok(stream) => Ok((stream, srdr.unmatched_braces)),
283 let mut buffer = Vec::with_capacity(1);
284 err.buffer(&mut buffer);
285 // Not using `emit_unclosed_delims` to use `db.buffer`
286 for unmatched in srdr.unmatched_braces {
287 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
288 "incorrect close delimiter: `{}`",
289 token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
291 db.span_label(unmatched.found_span, "incorrect close delimiter");
292 if let Some(sp) = unmatched.candidate_span {
293 db.span_label(sp, "close delimiter possibly meant for this");
295 if let Some(sp) = unmatched.unclosed_span {
296 db.span_label(sp, "un-closed delimiter");
298 db.buffer(&mut buffer);
305 /// Given stream and the `ParseSess`, produces a parser.
306 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> {
307 Parser::new(sess, stream, None, true, false)
310 /// Parses a string representing a character literal into its final form.
311 /// Rather than just accepting/rejecting a given literal, unescapes it as
312 /// well. Can take any slice prefixed by a character escape. Returns the
313 /// character and the number of characters consumed.
314 fn char_lit(lit: &str, diag: Option<(Span, &Handler)>) -> (char, isize) {
317 // Handle non-escaped chars first.
318 if lit.as_bytes()[0] != b'\\' {
319 // If the first byte isn't '\\' it might part of a multi-byte char, so
320 // get the char with chars().
321 let c = lit.chars().next().unwrap();
325 // Handle escaped chars.
326 match lit.as_bytes()[1] as char {
335 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
336 let c = char::from_u32(v).unwrap();
340 assert_eq!(lit.as_bytes()[2], b'{');
341 let idx = lit.find('}').unwrap();
343 // All digits and '_' are ascii, so treat each byte as a char.
345 for c in lit[3..idx].bytes() {
346 let c = char::from(c);
348 let x = c.to_digit(16).unwrap();
349 v = v.checked_mul(16).unwrap().checked_add(x).unwrap();
352 let c = char::from_u32(v).unwrap_or_else(|| {
353 if let Some((span, diag)) = diag {
354 let mut diag = diag.struct_span_err(span, "invalid unicode character escape");
356 diag.help("unicode escape must be at most 10FFFF").emit();
358 diag.help("unicode escape must not be a surrogate").emit();
363 (c, (idx + 1) as isize)
365 _ => panic!("lexer should have rejected a bad character escape {}", lit)
369 /// Parses a string representing a string literal into its final form. Does unescaping.
370 fn str_lit(lit: &str, diag: Option<(Span, &Handler)>) -> String {
371 debug!("str_lit: given {}", lit.escape_default());
372 let mut res = String::with_capacity(lit.len());
374 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
376 /// Eat everything up to a non-whitespace.
377 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
379 match it.peek().map(|x| x.1) {
380 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
388 let mut chars = lit.char_indices().peekable();
389 while let Some((i, c)) = chars.next() {
392 let ch = chars.peek().unwrap_or_else(|| {
393 panic!("{}", error(i))
398 } else if ch == '\r' {
400 let ch = chars.peek().unwrap_or_else(|| {
401 panic!("{}", error(i))
405 panic!("lexer accepted bare CR");
409 // otherwise, a normal escape
410 let (c, n) = char_lit(&lit[i..], diag);
411 for _ in 0..n - 1 { // we don't need to move past the first \
418 let ch = chars.peek().unwrap_or_else(|| {
419 panic!("{}", error(i))
423 panic!("lexer accepted bare CR");
432 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
433 debug!("parse_str_lit: returning {}", res);
437 /// Parses a string representing a raw string literal into its final form. The
438 /// only operation this does is convert embedded CRLF into a single LF.
439 fn raw_str_lit(lit: &str) -> String {
440 debug!("raw_str_lit: given {}", lit.escape_default());
441 let mut res = String::with_capacity(lit.len());
443 let mut chars = lit.chars().peekable();
444 while let Some(c) = chars.next() {
446 if *chars.peek().unwrap() != '\n' {
447 panic!("lexer accepted bare CR");
460 // check if `s` looks like i32 or u1234 etc.
461 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
462 s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
466 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
468 Some(($span, $diag)) => { $($body)* }
474 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
475 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
479 token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
480 token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str(), diag).0))),
481 token::Err(i) => (true, Some(LitKind::Err(i))),
483 // There are some valid suffixes for integer and float literals,
484 // so all the handling is done internally.
485 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
486 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
488 token::Str_(mut sym) => {
489 // If there are no characters requiring special treatment we can
490 // reuse the symbol from the Token. Otherwise, we must generate a
491 // new symbol because the string in the LitKind is different to the
492 // string in the Token.
493 let s = &sym.as_str();
494 if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
495 sym = Symbol::intern(&str_lit(s, diag));
497 (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
499 token::StrRaw(mut sym, n) => {
501 let s = &sym.as_str();
502 if s.contains('\r') {
503 sym = Symbol::intern(&raw_str_lit(s));
505 (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
507 token::ByteStr(i) => {
508 (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
510 token::ByteStrRaw(i, _) => {
511 (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
516 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
517 -> Option<ast::LitKind> {
518 debug!("filtered_float_lit: {}, {:?}", data, suffix);
519 let suffix = match suffix {
520 Some(suffix) => suffix,
521 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
524 Some(match &*suffix.as_str() {
525 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
526 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
528 err!(diag, |span, diag| {
529 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
530 // if it looks like a width, lets try to be helpful.
531 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
532 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
534 let msg = format!("invalid suffix `{}` for float literal", suf);
535 diag.struct_span_err(span, &msg)
536 .span_label(span, format!("invalid suffix `{}`", suf))
537 .help("valid suffixes are `f32` and `f64`")
542 ast::LitKind::FloatUnsuffixed(data)
546 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
547 -> Option<ast::LitKind> {
548 debug!("float_lit: {:?}, {:?}", s, suffix);
549 // FIXME #2252: bounds checking float literals is deferred until trans
551 // Strip underscores without allocating a new String unless necessary.
553 let s = if s.chars().any(|c| c == '_') {
554 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
560 filtered_float_lit(Symbol::intern(s), suffix, diag)
563 /// Parses a string representing a byte literal into its final form. Similar to `char_lit`.
564 fn byte_lit(lit: &str) -> (u8, usize) {
565 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
568 (lit.as_bytes()[0], 1)
570 assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
571 let b = match lit.as_bytes()[1] {
580 match u64::from_str_radix(&lit[2..4], 16).ok() {
587 None => panic!(err(3))
595 fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
596 let mut res = Vec::with_capacity(lit.len());
598 let error = |i| panic!("lexer should have rejected {} at {}", lit, i);
600 /// Eat everything up to a non-whitespace.
601 fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
603 match it.peek().map(|x| x.1) {
604 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
612 // byte string literals *must* be ASCII, but the escapes don't have to be
613 let mut chars = lit.bytes().enumerate().peekable();
616 Some((i, b'\\')) => {
617 match chars.peek().unwrap_or_else(|| error(i)).1 {
618 b'\n' => eat(&mut chars),
621 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
622 panic!("lexer accepted bare CR");
627 // otherwise, a normal escape
628 let (c, n) = byte_lit(&lit[i..]);
629 // we don't need to move past the first \
637 Some((i, b'\r')) => {
638 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
639 panic!("lexer accepted bare CR");
644 Some((_, c)) => res.push(c),
652 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
653 -> Option<ast::LitKind> {
654 // s can only be ascii, byte indexing is fine
656 // Strip underscores without allocating a new String unless necessary.
658 let mut s = if s.chars().any(|c| c == '_') {
659 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
665 debug!("integer_lit: {}, {:?}", s, suffix);
669 let mut ty = ast::LitIntType::Unsuffixed;
671 if s.starts_with('0') && s.len() > 1 {
672 match s.as_bytes()[1] {
680 // 1f64 and 2f32 etc. are valid float literals.
681 if let Some(suf) = suffix {
682 if looks_like_width_suffix(&['f'], &suf.as_str()) {
683 let err = match base {
684 16 => Some("hexadecimal float literal is not supported"),
685 8 => Some("octal float literal is not supported"),
686 2 => Some("binary float literal is not supported"),
689 if let Some(err) = err {
690 err!(diag, |span, diag| {
691 diag.struct_span_err(span, err)
692 .span_label(span, "not supported")
696 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
704 if let Some(suf) = suffix {
705 if suf.as_str().is_empty() {
706 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
708 ty = match &*suf.as_str() {
709 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
710 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
711 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
712 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
713 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
714 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
715 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
716 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
717 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
718 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
719 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
720 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
722 // i<digits> and u<digits> look like widths, so lets
723 // give an error message along those lines
724 err!(diag, |span, diag| {
725 if looks_like_width_suffix(&['i', 'u'], suf) {
726 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
727 diag.struct_span_err(span, &msg)
728 .help("valid widths are 8, 16, 32, 64 and 128")
731 let msg = format!("invalid suffix `{}` for numeric literal", suf);
732 diag.struct_span_err(span, &msg)
733 .span_label(span, format!("invalid suffix `{}`", suf))
734 .help("the suffix must be one of the integral types \
735 (`u32`, `isize`, etc)")
745 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
746 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
748 Some(match u128::from_str_radix(s, base) {
749 Ok(r) => ast::LitKind::Int(r, ty),
751 // small bases are lexed as if they were base 10, e.g, the string
752 // might be `0b10201`. This will cause the conversion above to fail,
753 // but these cases have errors in the lexer: we don't want to emit
754 // two errors, and we especially don't want to emit this error since
755 // it isn't necessarily true.
756 let already_errored = base < 10 &&
757 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
759 if !already_errored {
760 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
762 ast::LitKind::Int(0, ty)
767 /// A sequence separator.
769 /// The seperator token.
770 pub sep: Option<token::Token>,
771 /// `true` if a trailing separator is allowed.
772 pub trailing_sep_allowed: bool,
776 pub fn trailing_allowed(t: token::Token) -> SeqSep {
779 trailing_sep_allowed: true,
783 pub fn none() -> SeqSep {
786 trailing_sep_allowed: false,
794 use crate::ast::{self, Ident, PatKind};
795 use crate::attr::first_attr_value_str_by_name;
797 use crate::print::pprust::item_to_string;
798 use crate::tokenstream::{DelimSpan, TokenTree};
799 use crate::util::parser_testing::string_to_stream;
800 use crate::util::parser_testing::{string_to_expr, string_to_item};
801 use crate::with_globals;
802 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
806 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
807 /// when a syntax error occurred.
808 fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
809 -> PResult<'_, Option<P<ast::Item>>> {
810 new_parser_from_source_str(sess, name, source).parse_item()
813 // produce a syntax_pos::span
814 fn sp(a: u32, b: u32) -> Span {
815 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
819 #[test] fn bad_path_expr_1() {
821 string_to_expr("::abc::def::return".to_string());
825 // check the token-tree-ization of macros
827 fn string_to_tts_macro () {
830 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
831 let tts: &[TokenTree] = &tts[..];
833 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
836 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
837 Some(&TokenTree::Token(_, token::Not)),
838 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
839 Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
841 if name_macro_rules.name == "macro_rules"
842 && name_zip.name == "zip" => {
843 let tts = ¯o_tts.trees().collect::<Vec<_>>();
844 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
847 Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
848 Some(&TokenTree::Token(_, token::FatArrow)),
849 Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
851 if macro_delim == token::Paren => {
852 let tts = &first_tts.trees().collect::<Vec<_>>();
853 match (tts.len(), tts.get(0), tts.get(1)) {
856 Some(&TokenTree::Token(_, token::Dollar)),
857 Some(&TokenTree::Token(_, token::Ident(ident, false))),
859 if first_delim == token::Paren && ident.name == "a" => {},
860 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
862 let tts = &second_tts.trees().collect::<Vec<_>>();
863 match (tts.len(), tts.get(0), tts.get(1)) {
866 Some(&TokenTree::Token(_, token::Dollar)),
867 Some(&TokenTree::Token(_, token::Ident(ident, false))),
869 if second_delim == token::Paren && ident.name == "a" => {},
870 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
873 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
876 _ => panic!("value: {:?}",tts),
882 fn string_to_tts_1() {
884 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
886 let expected = TokenStream::new(vec![
887 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
888 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
889 TokenTree::Delimited(
890 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
891 token::DelimToken::Paren,
892 TokenStream::new(vec![
893 TokenTree::Token(sp(6, 7),
894 token::Ident(Ident::from_str("b"), false)).into(),
895 TokenTree::Token(sp(8, 9), token::Colon).into(),
896 TokenTree::Token(sp(10, 13),
897 token::Ident(Ident::from_str("i32"), false)).into(),
900 TokenTree::Delimited(
901 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
902 token::DelimToken::Brace,
903 TokenStream::new(vec![
904 TokenTree::Token(sp(17, 18),
905 token::Ident(Ident::from_str("b"), false)).into(),
906 TokenTree::Token(sp(18, 19), token::Semi).into(),
911 assert_eq!(tts, expected);
915 #[test] fn parse_use() {
917 let use_s = "use foo::bar::baz;";
918 let vitem = string_to_item(use_s.to_string()).unwrap();
919 let vitem_s = item_to_string(&vitem);
920 assert_eq!(&vitem_s[..], use_s);
922 let use_s = "use foo::bar as baz;";
923 let vitem = string_to_item(use_s.to_string()).unwrap();
924 let vitem_s = item_to_string(&vitem);
925 assert_eq!(&vitem_s[..], use_s);
929 #[test] fn parse_extern_crate() {
931 let ex_s = "extern crate foo;";
932 let vitem = string_to_item(ex_s.to_string()).unwrap();
933 let vitem_s = item_to_string(&vitem);
934 assert_eq!(&vitem_s[..], ex_s);
936 let ex_s = "extern crate foo as bar;";
937 let vitem = string_to_item(ex_s.to_string()).unwrap();
938 let vitem_s = item_to_string(&vitem);
939 assert_eq!(&vitem_s[..], ex_s);
943 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
944 let item = string_to_item(src.to_string()).unwrap();
946 struct PatIdentVisitor {
949 impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
950 fn visit_pat(&mut self, p: &'a ast::Pat) {
952 PatKind::Ident(_ , ref spannedident, _) => {
953 self.spans.push(spannedident.span.clone());
956 crate::visit::walk_pat(self, p);
961 let mut v = PatIdentVisitor { spans: Vec::new() };
962 crate::visit::walk_item(&mut v, &item);
966 #[test] fn span_of_self_arg_pat_idents_are_correct() {
969 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
970 "impl z { fn a (&mut self, &myarg: i32) {} }",
971 "impl z { fn a (&'a self, &myarg: i32) {} }",
972 "impl z { fn a (self, &myarg: i32) {} }",
973 "impl z { fn a (self: Foo, &myarg: i32) {} }",
977 let spans = get_spans_of_pat_idents(src);
978 let (lo, hi) = (spans[0].lo(), spans[0].hi());
979 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
980 "\"{}\" != \"self\". src=\"{}\"",
981 &src[lo.to_usize()..hi.to_usize()], src)
986 #[test] fn parse_exprs () {
988 // just make sure that they parse....
989 string_to_expr("3 + 4".to_string());
990 string_to_expr("a::z.froob(b,&(987+3))".to_string());
994 #[test] fn attrs_fix_bug () {
996 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
997 -> Result<Box<Writer>, String> {
1000 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1004 fn wb() -> c_int { O_WRONLY as c_int }
1006 let mut fflags: c_int = wb();
1011 #[test] fn crlf_doc_comments() {
1013 let sess = ParseSess::new(FilePathMapping::empty());
1015 let name_1 = FileName::Custom("crlf_source_1".to_string());
1016 let source = "/// doc comment\r\nfn foo() {}".to_string();
1017 let item = parse_item_from_source_str(name_1, source, &sess)
1019 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1020 assert_eq!(doc, "/// doc comment");
1022 let name_2 = FileName::Custom("crlf_source_2".to_string());
1023 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1024 let item = parse_item_from_source_str(name_2, source, &sess)
1026 let docs = item.attrs.iter().filter(|a| a.path == "doc")
1027 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1028 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1029 assert_eq!(&docs[..], b);
1031 let name_3 = FileName::Custom("clrf_source_3".to_string());
1032 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1033 let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
1034 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1035 assert_eq!(doc, "/** doc comment\n * with CRLF */");
1041 fn parse_expr_from_source_str(
1042 name: FileName, source: String, sess: &ParseSess
1043 ) -> PResult<'_, P<ast::Expr>> {
1044 new_parser_from_source_str(sess, name, source).parse_expr()
1048 let sess = ParseSess::new(FilePathMapping::empty());
1049 let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
1050 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
1052 let tts: Vec<_> = match expr.node {
1053 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
1054 _ => panic!("not a macro"),
1057 let span = tts.iter().rev().next().unwrap().span();
1059 match sess.source_map().span_to_snippet(span) {
1060 Ok(s) => assert_eq!(&s[..], "{ body }"),
1061 Err(_) => panic!("could not get snippet"),
1066 // This tests that when parsing a string (rather than a file) we don't try
1067 // and read in a file for a module declaration and just parse a stub.
1068 // See `recurse_into_file_modules` in the parser.
1070 fn out_of_line_mod() {
1072 let sess = ParseSess::new(FilePathMapping::empty());
1073 let item = parse_item_from_source_str(
1074 PathBuf::from("foo").into(),
1075 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
1077 ).unwrap().unwrap();
1079 if let ast::ItemKind::Mod(ref m) = item.node {
1080 assert!(m.items.len() == 2);