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>>;
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>>,
53 pub fn new(file_path_mapping: FilePathMapping) -> Self {
54 let cm = Lrc::new(SourceMap::new(file_path_mapping));
55 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
59 ParseSess::with_span_handler(handler, cm)
62 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
64 span_diagnostic: handler,
65 unstable_features: UnstableFeatures::from_environment(),
66 config: FxHashSet::default(),
67 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
68 raw_identifier_spans: Lock::new(Vec::new()),
69 registered_diagnostics: Lock::new(ErrorMap::new()),
70 included_mod_stack: Lock::new(vec![]),
72 buffered_lints: Lock::new(vec![]),
77 pub fn source_map(&self) -> &SourceMap {
81 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
82 lint_id: BufferedEarlyLintId,
87 self.buffered_lints.with_lock(|buffered_lints| {
88 buffered_lints.push(BufferedEarlyLint{
99 pub struct Directory<'a> {
100 pub path: Cow<'a, Path>,
101 pub ownership: DirectoryOwnership,
104 #[derive(Copy, Clone)]
105 pub enum DirectoryOwnership {
107 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
108 relative: Option<ast::Ident>,
111 UnownedViaMod(bool /* legacy warnings? */),
114 // a bunch of utility functions of the form parse_<thing>_from_<source>
115 // where <thing> includes crate, expr, item, stmt, tts, and one that
116 // uses a HOF to parse anything, and <source> includes file and
119 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
120 let mut parser = new_parser_from_file(sess, input);
121 parser.parse_crate_mod()
124 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
125 -> PResult<'a, Vec<ast::Attribute>> {
126 let mut parser = new_parser_from_file(sess, input);
127 parser.parse_inner_attributes()
130 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
131 -> PResult<'_, ast::Crate> {
132 new_parser_from_source_str(sess, name, source).parse_crate_mod()
135 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
136 -> PResult<'_, Vec<ast::Attribute>> {
137 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
140 pub fn parse_stream_from_source_str(
144 override_span: Option<Span>,
146 let (stream, mut errors) = source_file_to_stream(
148 sess.source_map().new_source_file(name, source),
151 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
155 /// Creates a new parser from a source string.
156 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
157 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
160 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
162 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
163 -> Result<Parser<'_>, Vec<Diagnostic>>
165 let mut parser = maybe_source_file_to_parser(sess,
166 sess.source_map().new_source_file(name, source))?;
167 parser.recurse_into_file_modules = false;
171 /// Creates a new parser, handling errors as appropriate
172 /// if the file doesn't exist
173 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
174 source_file_to_parser(sess, file_to_source_file(sess, path, None))
177 /// Creates a new parser, returning buffered diagnostics if the file doesn't
178 /// exist or from lexing the initial token stream.
179 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
180 -> Result<Parser<'a>, Vec<Diagnostic>> {
181 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
182 maybe_source_file_to_parser(sess, file)
185 /// Given a session, a crate config, a path, and a span, add
186 /// the file at the given path to the source_map, and return a parser.
187 /// On an error, use the given span as the source of the problem.
188 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
190 directory_ownership: DirectoryOwnership,
191 module_name: Option<String>,
192 sp: Span) -> Parser<'a> {
193 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
194 p.directory.ownership = directory_ownership;
195 p.root_module_name = module_name;
199 /// Given a source_file and config, return a parser
200 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
201 panictry_buffer!(&sess.span_diagnostic,
202 maybe_source_file_to_parser(sess, source_file))
205 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
206 /// initial token stream.
207 fn maybe_source_file_to_parser(
209 source_file: Lrc<SourceFile>,
210 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
211 let end_pos = source_file.end_pos;
212 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
213 let mut parser = stream_to_parser(sess, stream);
214 parser.unclosed_delims = unclosed_delims;
215 if parser.token == token::Eof && parser.span.is_dummy() {
216 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
222 // must preserve old name for now, because quote! from the *existing*
223 // compiler expands into it
224 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
225 stream_to_parser(sess, tts.into_iter().collect())
231 /// Given a session and a path and an optional span (for error reporting),
232 /// add the path to the session's source_map and return the new source_file or
233 /// error when a file can't be read.
234 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
235 -> Result<Lrc<SourceFile>, Diagnostic> {
236 sess.source_map().load_file(path)
238 let msg = format!("couldn't read {}: {}", path.display(), e);
239 let mut diag = Diagnostic::new(Level::Fatal, &msg);
240 if let Some(sp) = spanopt {
247 /// Given a session and a path and an optional span (for error reporting),
248 /// add the path to the session's `source_map` and return the new `source_file`.
249 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
251 match try_file_to_source_file(sess, path, spanopt) {
252 Ok(source_file) => source_file,
254 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
260 /// Given a source_file, produces a sequence of token trees.
261 pub fn source_file_to_stream(
263 source_file: Lrc<SourceFile>,
264 override_span: Option<Span>,
265 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
266 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
269 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
270 /// parsing the token tream.
271 pub fn maybe_file_to_stream(
273 source_file: Lrc<SourceFile>,
274 override_span: Option<Span>,
275 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
276 let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
279 match srdr.parse_all_token_trees() {
280 Ok(stream) => Ok((stream, srdr.unmatched_braces)),
282 let mut buffer = Vec::with_capacity(1);
283 err.buffer(&mut buffer);
284 // Not using `emit_unclosed_delims` to use `db.buffer`
285 for unmatched in srdr.unmatched_braces {
286 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
287 "incorrect close delimiter: `{}`",
288 token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
290 db.span_label(unmatched.found_span, "incorrect close delimiter");
291 if let Some(sp) = unmatched.candidate_span {
292 db.span_label(sp, "close delimiter possibly meant for this");
294 if let Some(sp) = unmatched.unclosed_span {
295 db.span_label(sp, "un-closed delimiter");
297 db.buffer(&mut buffer);
304 /// Given stream and the `ParseSess`, produces a parser.
305 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> {
306 Parser::new(sess, stream, None, true, false)
309 /// Parses a string representing a character literal into its final form.
310 /// Rather than just accepting/rejecting a given literal, unescapes it as
311 /// well. Can take any slice prefixed by a character escape. Returns the
312 /// character and the number of characters consumed.
313 fn char_lit(lit: &str, diag: Option<(Span, &Handler)>) -> (char, isize) {
316 // Handle non-escaped chars first.
317 if lit.as_bytes()[0] != b'\\' {
318 // If the first byte isn't '\\' it might part of a multi-byte char, so
319 // get the char with chars().
320 let c = lit.chars().next().unwrap();
324 // Handle escaped chars.
325 match lit.as_bytes()[1] as char {
334 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
335 let c = char::from_u32(v).unwrap();
339 assert_eq!(lit.as_bytes()[2], b'{');
340 let idx = lit.find('}').unwrap();
342 // All digits and '_' are ascii, so treat each byte as a char.
344 for c in lit[3..idx].bytes() {
345 let c = char::from(c);
347 let x = c.to_digit(16).unwrap();
348 v = v.checked_mul(16).unwrap().checked_add(x).unwrap();
351 let c = char::from_u32(v).unwrap_or_else(|| {
352 if let Some((span, diag)) = diag {
353 let mut diag = diag.struct_span_err(span, "invalid unicode character escape");
355 diag.help("unicode escape must be at most 10FFFF").emit();
357 diag.help("unicode escape must not be a surrogate").emit();
362 (c, (idx + 1) as isize)
364 _ => panic!("lexer should have rejected a bad character escape {}", lit)
368 /// Parses a string representing a string literal into its final form. Does unescaping.
369 fn str_lit(lit: &str, diag: Option<(Span, &Handler)>) -> String {
370 debug!("str_lit: given {}", lit.escape_default());
371 let mut res = String::with_capacity(lit.len());
373 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
375 /// Eat everything up to a non-whitespace.
376 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
378 match it.peek().map(|x| x.1) {
379 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
387 let mut chars = lit.char_indices().peekable();
388 while let Some((i, c)) = chars.next() {
391 let ch = chars.peek().unwrap_or_else(|| {
392 panic!("{}", error(i))
397 } else if ch == '\r' {
399 let ch = chars.peek().unwrap_or_else(|| {
400 panic!("{}", error(i))
404 panic!("lexer accepted bare CR");
408 // otherwise, a normal escape
409 let (c, n) = char_lit(&lit[i..], diag);
410 for _ in 0..n - 1 { // we don't need to move past the first \
417 let ch = chars.peek().unwrap_or_else(|| {
418 panic!("{}", error(i))
422 panic!("lexer accepted bare CR");
431 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
432 debug!("parse_str_lit: returning {}", res);
436 /// Parses a string representing a raw string literal into its final form. The
437 /// only operation this does is convert embedded CRLF into a single LF.
438 fn raw_str_lit(lit: &str) -> String {
439 debug!("raw_str_lit: given {}", lit.escape_default());
440 let mut res = String::with_capacity(lit.len());
442 let mut chars = lit.chars().peekable();
443 while let Some(c) = chars.next() {
445 if *chars.peek().unwrap() != '\n' {
446 panic!("lexer accepted bare CR");
459 // check if `s` looks like i32 or u1234 etc.
460 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
461 s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
465 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
467 Some(($span, $diag)) => { $($body)* }
473 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
474 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
478 token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
479 token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str(), diag).0))),
480 token::Err(i) => (true, Some(LitKind::Err(i))),
482 // There are some valid suffixes for integer and float literals,
483 // so all the handling is done internally.
484 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
485 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
487 token::Str_(mut sym) => {
488 // If there are no characters requiring special treatment we can
489 // reuse the symbol from the Token. Otherwise, we must generate a
490 // new symbol because the string in the LitKind is different to the
491 // string in the Token.
492 let s = &sym.as_str();
493 if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
494 sym = Symbol::intern(&str_lit(s, diag));
496 (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
498 token::StrRaw(mut sym, n) => {
500 let s = &sym.as_str();
501 if s.contains('\r') {
502 sym = Symbol::intern(&raw_str_lit(s));
504 (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
506 token::ByteStr(i) => {
507 (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
509 token::ByteStrRaw(i, _) => {
510 (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
515 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
516 -> Option<ast::LitKind> {
517 debug!("filtered_float_lit: {}, {:?}", data, suffix);
518 let suffix = match suffix {
519 Some(suffix) => suffix,
520 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
523 Some(match &*suffix.as_str() {
524 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
525 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
527 err!(diag, |span, diag| {
528 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
529 // if it looks like a width, lets try to be helpful.
530 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
531 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
533 let msg = format!("invalid suffix `{}` for float literal", suf);
534 diag.struct_span_err(span, &msg)
535 .span_label(span, format!("invalid suffix `{}`", suf))
536 .help("valid suffixes are `f32` and `f64`")
541 ast::LitKind::FloatUnsuffixed(data)
545 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
546 -> Option<ast::LitKind> {
547 debug!("float_lit: {:?}, {:?}", s, suffix);
548 // FIXME #2252: bounds checking float literals is deferred until trans
550 // Strip underscores without allocating a new String unless necessary.
552 let s = if s.chars().any(|c| c == '_') {
553 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
559 filtered_float_lit(Symbol::intern(s), suffix, diag)
562 /// Parses a string representing a byte literal into its final form. Similar to `char_lit`.
563 fn byte_lit(lit: &str) -> (u8, usize) {
564 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
567 (lit.as_bytes()[0], 1)
569 assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
570 let b = match lit.as_bytes()[1] {
579 match u64::from_str_radix(&lit[2..4], 16).ok() {
586 None => panic!(err(3))
594 fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
595 let mut res = Vec::with_capacity(lit.len());
597 let error = |i| panic!("lexer should have rejected {} at {}", lit, i);
599 /// Eat everything up to a non-whitespace.
600 fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
602 match it.peek().map(|x| x.1) {
603 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
611 // byte string literals *must* be ASCII, but the escapes don't have to be
612 let mut chars = lit.bytes().enumerate().peekable();
615 Some((i, b'\\')) => {
616 match chars.peek().unwrap_or_else(|| error(i)).1 {
617 b'\n' => eat(&mut chars),
620 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
621 panic!("lexer accepted bare CR");
626 // otherwise, a normal escape
627 let (c, n) = byte_lit(&lit[i..]);
628 // we don't need to move past the first \
636 Some((i, b'\r')) => {
637 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
638 panic!("lexer accepted bare CR");
643 Some((_, c)) => res.push(c),
651 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
652 -> Option<ast::LitKind> {
653 // s can only be ascii, byte indexing is fine
655 // Strip underscores without allocating a new String unless necessary.
657 let mut s = if s.chars().any(|c| c == '_') {
658 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
664 debug!("integer_lit: {}, {:?}", s, suffix);
668 let mut ty = ast::LitIntType::Unsuffixed;
670 if s.starts_with('0') && s.len() > 1 {
671 match s.as_bytes()[1] {
679 // 1f64 and 2f32 etc. are valid float literals.
680 if let Some(suf) = suffix {
681 if looks_like_width_suffix(&['f'], &suf.as_str()) {
682 let err = match base {
683 16 => Some("hexadecimal float literal is not supported"),
684 8 => Some("octal float literal is not supported"),
685 2 => Some("binary float literal is not supported"),
688 if let Some(err) = err {
689 err!(diag, |span, diag| {
690 diag.struct_span_err(span, err)
691 .span_label(span, "not supported")
695 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
703 if let Some(suf) = suffix {
704 if suf.as_str().is_empty() {
705 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
707 ty = match &*suf.as_str() {
708 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
709 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
710 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
711 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
712 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
713 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
714 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
715 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
716 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
717 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
718 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
719 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
721 // i<digits> and u<digits> look like widths, so lets
722 // give an error message along those lines
723 err!(diag, |span, diag| {
724 if looks_like_width_suffix(&['i', 'u'], suf) {
725 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
726 diag.struct_span_err(span, &msg)
727 .help("valid widths are 8, 16, 32, 64 and 128")
730 let msg = format!("invalid suffix `{}` for numeric literal", suf);
731 diag.struct_span_err(span, &msg)
732 .span_label(span, format!("invalid suffix `{}`", suf))
733 .help("the suffix must be one of the integral types \
734 (`u32`, `isize`, etc)")
744 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
745 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
747 Some(match u128::from_str_radix(s, base) {
748 Ok(r) => ast::LitKind::Int(r, ty),
750 // small bases are lexed as if they were base 10, e.g, the string
751 // might be `0b10201`. This will cause the conversion above to fail,
752 // but these cases have errors in the lexer: we don't want to emit
753 // two errors, and we especially don't want to emit this error since
754 // it isn't necessarily true.
755 let already_errored = base < 10 &&
756 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
758 if !already_errored {
759 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
761 ast::LitKind::Int(0, ty)
766 /// A sequence separator.
768 /// The seperator token.
769 pub sep: Option<token::Token>,
770 /// `true` if a trailing separator is allowed.
771 pub trailing_sep_allowed: bool,
775 pub fn trailing_allowed(t: token::Token) -> SeqSep {
778 trailing_sep_allowed: true,
782 pub fn none() -> SeqSep {
785 trailing_sep_allowed: false,
793 use crate::ast::{self, Ident, PatKind};
794 use crate::attr::first_attr_value_str_by_name;
796 use crate::print::pprust::item_to_string;
797 use crate::tokenstream::{DelimSpan, TokenTree};
798 use crate::util::parser_testing::string_to_stream;
799 use crate::util::parser_testing::{string_to_expr, string_to_item};
800 use crate::with_globals;
801 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
805 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
806 /// when a syntax error occurred.
807 fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
808 -> PResult<'_, Option<P<ast::Item>>> {
809 new_parser_from_source_str(sess, name, source).parse_item()
812 // produce a syntax_pos::span
813 fn sp(a: u32, b: u32) -> Span {
814 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
818 #[test] fn bad_path_expr_1() {
820 string_to_expr("::abc::def::return".to_string());
824 // check the token-tree-ization of macros
826 fn string_to_tts_macro () {
829 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
830 let tts: &[TokenTree] = &tts[..];
832 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
835 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
836 Some(&TokenTree::Token(_, token::Not)),
837 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
838 Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
840 if name_macro_rules.name == "macro_rules"
841 && name_zip.name == "zip" => {
842 let tts = ¯o_tts.trees().collect::<Vec<_>>();
843 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
846 Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
847 Some(&TokenTree::Token(_, token::FatArrow)),
848 Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
850 if macro_delim == token::Paren => {
851 let tts = &first_tts.trees().collect::<Vec<_>>();
852 match (tts.len(), tts.get(0), tts.get(1)) {
855 Some(&TokenTree::Token(_, token::Dollar)),
856 Some(&TokenTree::Token(_, token::Ident(ident, false))),
858 if first_delim == token::Paren && ident.name == "a" => {},
859 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
861 let tts = &second_tts.trees().collect::<Vec<_>>();
862 match (tts.len(), tts.get(0), tts.get(1)) {
865 Some(&TokenTree::Token(_, token::Dollar)),
866 Some(&TokenTree::Token(_, token::Ident(ident, false))),
868 if second_delim == token::Paren && ident.name == "a" => {},
869 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
872 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
875 _ => panic!("value: {:?}",tts),
881 fn string_to_tts_1() {
883 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
885 let expected = TokenStream::new(vec![
886 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
887 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
888 TokenTree::Delimited(
889 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
890 token::DelimToken::Paren,
891 TokenStream::new(vec![
892 TokenTree::Token(sp(6, 7),
893 token::Ident(Ident::from_str("b"), false)).into(),
894 TokenTree::Token(sp(8, 9), token::Colon).into(),
895 TokenTree::Token(sp(10, 13),
896 token::Ident(Ident::from_str("i32"), false)).into(),
899 TokenTree::Delimited(
900 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
901 token::DelimToken::Brace,
902 TokenStream::new(vec![
903 TokenTree::Token(sp(17, 18),
904 token::Ident(Ident::from_str("b"), false)).into(),
905 TokenTree::Token(sp(18, 19), token::Semi).into(),
910 assert_eq!(tts, expected);
914 #[test] fn parse_use() {
916 let use_s = "use foo::bar::baz;";
917 let vitem = string_to_item(use_s.to_string()).unwrap();
918 let vitem_s = item_to_string(&vitem);
919 assert_eq!(&vitem_s[..], use_s);
921 let use_s = "use foo::bar as baz;";
922 let vitem = string_to_item(use_s.to_string()).unwrap();
923 let vitem_s = item_to_string(&vitem);
924 assert_eq!(&vitem_s[..], use_s);
928 #[test] fn parse_extern_crate() {
930 let ex_s = "extern crate foo;";
931 let vitem = string_to_item(ex_s.to_string()).unwrap();
932 let vitem_s = item_to_string(&vitem);
933 assert_eq!(&vitem_s[..], ex_s);
935 let ex_s = "extern crate foo as bar;";
936 let vitem = string_to_item(ex_s.to_string()).unwrap();
937 let vitem_s = item_to_string(&vitem);
938 assert_eq!(&vitem_s[..], ex_s);
942 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
943 let item = string_to_item(src.to_string()).unwrap();
945 struct PatIdentVisitor {
948 impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
949 fn visit_pat(&mut self, p: &'a ast::Pat) {
951 PatKind::Ident(_ , ref spannedident, _) => {
952 self.spans.push(spannedident.span.clone());
955 crate::visit::walk_pat(self, p);
960 let mut v = PatIdentVisitor { spans: Vec::new() };
961 crate::visit::walk_item(&mut v, &item);
965 #[test] fn span_of_self_arg_pat_idents_are_correct() {
968 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
969 "impl z { fn a (&mut self, &myarg: i32) {} }",
970 "impl z { fn a (&'a self, &myarg: i32) {} }",
971 "impl z { fn a (self, &myarg: i32) {} }",
972 "impl z { fn a (self: Foo, &myarg: i32) {} }",
976 let spans = get_spans_of_pat_idents(src);
977 let (lo, hi) = (spans[0].lo(), spans[0].hi());
978 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
979 "\"{}\" != \"self\". src=\"{}\"",
980 &src[lo.to_usize()..hi.to_usize()], src)
985 #[test] fn parse_exprs () {
987 // just make sure that they parse....
988 string_to_expr("3 + 4".to_string());
989 string_to_expr("a::z.froob(b,&(987+3))".to_string());
993 #[test] fn attrs_fix_bug () {
995 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
996 -> Result<Box<Writer>, String> {
999 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1003 fn wb() -> c_int { O_WRONLY as c_int }
1005 let mut fflags: c_int = wb();
1010 #[test] fn crlf_doc_comments() {
1012 let sess = ParseSess::new(FilePathMapping::empty());
1014 let name_1 = FileName::Custom("crlf_source_1".to_string());
1015 let source = "/// doc comment\r\nfn foo() {}".to_string();
1016 let item = parse_item_from_source_str(name_1, source, &sess)
1018 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1019 assert_eq!(doc, "/// doc comment");
1021 let name_2 = FileName::Custom("crlf_source_2".to_string());
1022 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1023 let item = parse_item_from_source_str(name_2, source, &sess)
1025 let docs = item.attrs.iter().filter(|a| a.path == "doc")
1026 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1027 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1028 assert_eq!(&docs[..], b);
1030 let name_3 = FileName::Custom("clrf_source_3".to_string());
1031 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1032 let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
1033 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1034 assert_eq!(doc, "/** doc comment\n * with CRLF */");
1040 fn parse_expr_from_source_str(
1041 name: FileName, source: String, sess: &ParseSess
1042 ) -> PResult<'_, P<ast::Expr>> {
1043 new_parser_from_source_str(sess, name, source).parse_expr()
1047 let sess = ParseSess::new(FilePathMapping::empty());
1048 let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
1049 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
1051 let tts: Vec<_> = match expr.node {
1052 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
1053 _ => panic!("not a macro"),
1056 let span = tts.iter().rev().next().unwrap().span();
1058 match sess.source_map().span_to_snippet(span) {
1059 Ok(s) => assert_eq!(&s[..], "{ body }"),
1060 Err(_) => panic!("could not get snippet"),
1065 // This tests that when parsing a string (rather than a file) we don't try
1066 // and read in a file for a module declaration and just parse a stub.
1067 // See `recurse_into_file_modules` in the parser.
1069 fn out_of_line_mod() {
1071 let sess = ParseSess::new(FilePathMapping::empty());
1072 let item = parse_item_from_source_str(
1073 PathBuf::from("foo").into(),
1074 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
1076 ).unwrap().unwrap();
1078 if let ast::ItemKind::Mod(ref m) = item.node {
1079 assert!(m.items.len() == 2);