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};
21 use std::path::{Path, PathBuf};
24 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
36 pub(crate) mod unescape;
37 use unescape::{unescape_str, unescape_char, unescape_byte_str, unescape_byte};
39 pub(crate) mod unescape_error_reporting;
41 /// Info about a parsing session.
42 pub struct ParseSess {
43 pub span_diagnostic: Handler,
44 pub unstable_features: UnstableFeatures,
45 pub config: CrateConfig,
46 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
47 /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
48 pub raw_identifier_spans: Lock<Vec<Span>>,
49 /// The registered diagnostics codes.
50 crate registered_diagnostics: Lock<ErrorMap>,
51 /// Used to determine and report recursive module inclusions.
52 included_mod_stack: Lock<Vec<PathBuf>>,
53 source_map: Lrc<SourceMap>,
54 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
55 /// Contains the spans of block expressions that could have been incomplete based on the
56 /// operation token that followed it, but that the parser cannot identify without further
58 pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
62 pub fn new(file_path_mapping: FilePathMapping) -> Self {
63 let cm = Lrc::new(SourceMap::new(file_path_mapping));
64 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
68 ParseSess::with_span_handler(handler, cm)
71 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
73 span_diagnostic: handler,
74 unstable_features: UnstableFeatures::from_environment(),
75 config: FxHashSet::default(),
76 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
77 raw_identifier_spans: Lock::new(Vec::new()),
78 registered_diagnostics: Lock::new(ErrorMap::new()),
79 included_mod_stack: Lock::new(vec![]),
81 buffered_lints: Lock::new(vec![]),
82 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
87 pub fn source_map(&self) -> &SourceMap {
91 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
92 lint_id: BufferedEarlyLintId,
97 self.buffered_lints.with_lock(|buffered_lints| {
98 buffered_lints.push(BufferedEarlyLint{
107 /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
108 /// parser to continue parsing the following operation as part of the same expression.
109 pub fn expr_parentheses_needed(
111 err: &mut DiagnosticBuilder<'_>,
113 alt_snippet: Option<String>,
115 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
118 "parentheses are required to parse this as an expression",
119 format!("({})", snippet),
120 Applicability::MachineApplicable,
127 pub struct Directory<'a> {
128 pub path: Cow<'a, Path>,
129 pub ownership: DirectoryOwnership,
132 #[derive(Copy, Clone)]
133 pub enum DirectoryOwnership {
135 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
136 relative: Option<ast::Ident>,
139 UnownedViaMod(bool /* legacy warnings? */),
142 // a bunch of utility functions of the form parse_<thing>_from_<source>
143 // where <thing> includes crate, expr, item, stmt, tts, and one that
144 // uses a HOF to parse anything, and <source> includes file and
147 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
148 let mut parser = new_parser_from_file(sess, input);
149 parser.parse_crate_mod()
152 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
153 -> PResult<'a, Vec<ast::Attribute>> {
154 let mut parser = new_parser_from_file(sess, input);
155 parser.parse_inner_attributes()
158 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
159 -> PResult<'_, ast::Crate> {
160 new_parser_from_source_str(sess, name, source).parse_crate_mod()
163 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
164 -> PResult<'_, Vec<ast::Attribute>> {
165 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
168 pub fn parse_stream_from_source_str(
172 override_span: Option<Span>,
174 let (stream, mut errors) = source_file_to_stream(
176 sess.source_map().new_source_file(name, source),
179 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
183 /// Creates a new parser from a source string.
184 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
185 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
188 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
190 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
191 -> Result<Parser<'_>, Vec<Diagnostic>>
193 let mut parser = maybe_source_file_to_parser(sess,
194 sess.source_map().new_source_file(name, source))?;
195 parser.recurse_into_file_modules = false;
199 /// Creates a new parser, handling errors as appropriate
200 /// if the file doesn't exist
201 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
202 source_file_to_parser(sess, file_to_source_file(sess, path, None))
205 /// Creates a new parser, returning buffered diagnostics if the file doesn't
206 /// exist or from lexing the initial token stream.
207 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
208 -> Result<Parser<'a>, Vec<Diagnostic>> {
209 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
210 maybe_source_file_to_parser(sess, file)
213 /// Given a session, a crate config, a path, and a span, add
214 /// the file at the given path to the source_map, and return a parser.
215 /// On an error, use the given span as the source of the problem.
216 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
218 directory_ownership: DirectoryOwnership,
219 module_name: Option<String>,
220 sp: Span) -> Parser<'a> {
221 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
222 p.directory.ownership = directory_ownership;
223 p.root_module_name = module_name;
227 /// Given a source_file and config, return a parser
228 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
229 panictry_buffer!(&sess.span_diagnostic,
230 maybe_source_file_to_parser(sess, source_file))
233 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
234 /// initial token stream.
235 fn maybe_source_file_to_parser(
237 source_file: Lrc<SourceFile>,
238 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
239 let end_pos = source_file.end_pos;
240 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
241 let mut parser = stream_to_parser(sess, stream);
242 parser.unclosed_delims = unclosed_delims;
243 if parser.token == token::Eof && parser.span.is_dummy() {
244 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
250 // must preserve old name for now, because quote! from the *existing*
251 // compiler expands into it
252 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
253 stream_to_parser(sess, tts.into_iter().collect())
259 /// Given a session and a path and an optional span (for error reporting),
260 /// add the path to the session's source_map and return the new source_file or
261 /// error when a file can't be read.
262 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
263 -> Result<Lrc<SourceFile>, Diagnostic> {
264 sess.source_map().load_file(path)
266 let msg = format!("couldn't read {}: {}", path.display(), e);
267 let mut diag = Diagnostic::new(Level::Fatal, &msg);
268 if let Some(sp) = spanopt {
275 /// Given a session and a path and an optional span (for error reporting),
276 /// add the path to the session's `source_map` and return the new `source_file`.
277 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
279 match try_file_to_source_file(sess, path, spanopt) {
280 Ok(source_file) => source_file,
282 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
288 /// Given a source_file, produces a sequence of token trees.
289 pub fn source_file_to_stream(
291 source_file: Lrc<SourceFile>,
292 override_span: Option<Span>,
293 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
294 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
297 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
298 /// parsing the token tream.
299 pub fn maybe_file_to_stream(
301 source_file: Lrc<SourceFile>,
302 override_span: Option<Span>,
303 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
304 let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
307 match srdr.parse_all_token_trees() {
308 Ok(stream) => Ok((stream, srdr.unmatched_braces)),
310 let mut buffer = Vec::with_capacity(1);
311 err.buffer(&mut buffer);
312 // Not using `emit_unclosed_delims` to use `db.buffer`
313 for unmatched in srdr.unmatched_braces {
314 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
315 "incorrect close delimiter: `{}`",
316 token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
318 db.span_label(unmatched.found_span, "incorrect close delimiter");
319 if let Some(sp) = unmatched.candidate_span {
320 db.span_label(sp, "close delimiter possibly meant for this");
322 if let Some(sp) = unmatched.unclosed_span {
323 db.span_label(sp, "un-closed delimiter");
325 db.buffer(&mut buffer);
332 /// Given stream and the `ParseSess`, produces a parser.
333 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> {
334 Parser::new(sess, stream, None, true, false)
337 /// Parses a string representing a raw string literal into its final form. The
338 /// only operation this does is convert embedded CRLF into a single LF.
339 fn raw_str_lit(lit: &str) -> String {
340 debug!("raw_str_lit: given {}", lit.escape_default());
341 let mut res = String::with_capacity(lit.len());
343 let mut chars = lit.chars().peekable();
344 while let Some(c) = chars.next() {
346 if *chars.peek().unwrap() != '\n' {
347 panic!("lexer accepted bare CR");
360 // check if `s` looks like i32 or u1234 etc.
361 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
362 s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
366 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
368 Some(($span, $diag)) => { $($body)* }
374 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
375 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
380 let lit_kind = match unescape_byte(&i.as_str()) {
381 Ok(c) => LitKind::Byte(c),
382 Err(_) => LitKind::Err(i),
384 (true, Some(lit_kind))
387 let lit_kind = match unescape_char(&i.as_str()) {
388 Ok(c) => LitKind::Char(c),
389 Err(_) => LitKind::Err(i),
391 (true, Some(lit_kind))
393 token::Err(i) => (true, Some(LitKind::Err(i))),
395 // There are some valid suffixes for integer and float literals,
396 // so all the handling is done internally.
397 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
398 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
400 token::Str_(mut sym) => {
401 // If there are no characters requiring special treatment we can
402 // reuse the symbol from the Token. Otherwise, we must generate a
403 // new symbol because the string in the LitKind is different to the
404 // string in the Token.
405 let mut has_error = false;
406 let s = &sym.as_str();
407 if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
408 let mut buf = String::with_capacity(s.len());
409 unescape_str(s, &mut |_, unescaped_char| {
410 match unescaped_char {
411 Ok(c) => buf.push(c),
412 Err(_) => has_error = true,
416 return (true, Some(LitKind::Err(sym)));
418 sym = Symbol::intern(&buf)
421 (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
423 token::StrRaw(mut sym, n) => {
425 let s = &sym.as_str();
426 if s.contains('\r') {
427 sym = Symbol::intern(&raw_str_lit(s));
429 (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
431 token::ByteStr(i) => {
433 let mut buf = Vec::with_capacity(s.len());
434 let mut has_error = false;
435 unescape_byte_str(s, &mut |_, unescaped_byte| {
436 match unescaped_byte {
437 Ok(c) => buf.push(c),
438 Err(_) => has_error = true,
442 return (true, Some(LitKind::Err(i)));
445 (true, Some(LitKind::ByteStr(Lrc::new(buf))))
447 token::ByteStrRaw(i, _) => {
448 (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
453 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
454 -> Option<ast::LitKind> {
455 debug!("filtered_float_lit: {}, {:?}", data, suffix);
456 let suffix = match suffix {
457 Some(suffix) => suffix,
458 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
461 Some(match &*suffix.as_str() {
462 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
463 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
465 err!(diag, |span, diag| {
466 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
467 // if it looks like a width, lets try to be helpful.
468 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
469 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
471 let msg = format!("invalid suffix `{}` for float literal", suf);
472 diag.struct_span_err(span, &msg)
473 .span_label(span, format!("invalid suffix `{}`", suf))
474 .help("valid suffixes are `f32` and `f64`")
479 ast::LitKind::FloatUnsuffixed(data)
483 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
484 -> Option<ast::LitKind> {
485 debug!("float_lit: {:?}, {:?}", s, suffix);
486 // FIXME #2252: bounds checking float literals is deferred until trans
488 // Strip underscores without allocating a new String unless necessary.
490 let s = if s.chars().any(|c| c == '_') {
491 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
497 filtered_float_lit(Symbol::intern(s), suffix, diag)
500 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
501 -> Option<ast::LitKind> {
502 // s can only be ascii, byte indexing is fine
504 // Strip underscores without allocating a new String unless necessary.
506 let mut s = if s.chars().any(|c| c == '_') {
507 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
513 debug!("integer_lit: {}, {:?}", s, suffix);
517 let mut ty = ast::LitIntType::Unsuffixed;
519 if s.starts_with('0') && s.len() > 1 {
520 match s.as_bytes()[1] {
528 // 1f64 and 2f32 etc. are valid float literals.
529 if let Some(suf) = suffix {
530 if looks_like_width_suffix(&['f'], &suf.as_str()) {
531 let err = match base {
532 16 => Some("hexadecimal float literal is not supported"),
533 8 => Some("octal float literal is not supported"),
534 2 => Some("binary float literal is not supported"),
537 if let Some(err) = err {
538 err!(diag, |span, diag| {
539 diag.struct_span_err(span, err)
540 .span_label(span, "not supported")
544 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
552 if let Some(suf) = suffix {
553 if suf.as_str().is_empty() {
554 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
556 ty = match &*suf.as_str() {
557 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
558 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
559 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
560 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
561 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
562 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
563 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
564 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
565 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
566 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
567 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
568 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
570 // i<digits> and u<digits> look like widths, so lets
571 // give an error message along those lines
572 err!(diag, |span, diag| {
573 if looks_like_width_suffix(&['i', 'u'], suf) {
574 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
575 diag.struct_span_err(span, &msg)
576 .help("valid widths are 8, 16, 32, 64 and 128")
579 let msg = format!("invalid suffix `{}` for numeric literal", suf);
580 diag.struct_span_err(span, &msg)
581 .span_label(span, format!("invalid suffix `{}`", suf))
582 .help("the suffix must be one of the integral types \
583 (`u32`, `isize`, etc)")
593 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
594 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
596 Some(match u128::from_str_radix(s, base) {
597 Ok(r) => ast::LitKind::Int(r, ty),
599 // small bases are lexed as if they were base 10, e.g, the string
600 // might be `0b10201`. This will cause the conversion above to fail,
601 // but these cases have errors in the lexer: we don't want to emit
602 // two errors, and we especially don't want to emit this error since
603 // it isn't necessarily true.
604 let already_errored = base < 10 &&
605 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
607 if !already_errored {
608 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
610 ast::LitKind::Int(0, ty)
615 /// A sequence separator.
617 /// The seperator token.
618 pub sep: Option<token::Token>,
619 /// `true` if a trailing separator is allowed.
620 pub trailing_sep_allowed: bool,
624 pub fn trailing_allowed(t: token::Token) -> SeqSep {
627 trailing_sep_allowed: true,
631 pub fn none() -> SeqSep {
634 trailing_sep_allowed: false,
642 use crate::ast::{self, Ident, PatKind};
643 use crate::attr::first_attr_value_str_by_name;
645 use crate::print::pprust::item_to_string;
646 use crate::tokenstream::{DelimSpan, TokenTree};
647 use crate::util::parser_testing::string_to_stream;
648 use crate::util::parser_testing::{string_to_expr, string_to_item};
649 use crate::with_globals;
650 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
654 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
655 /// when a syntax error occurred.
656 fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
657 -> PResult<'_, Option<P<ast::Item>>> {
658 new_parser_from_source_str(sess, name, source).parse_item()
661 // produce a syntax_pos::span
662 fn sp(a: u32, b: u32) -> Span {
663 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
667 #[test] fn bad_path_expr_1() {
669 string_to_expr("::abc::def::return".to_string());
673 // check the token-tree-ization of macros
675 fn string_to_tts_macro () {
678 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
679 let tts: &[TokenTree] = &tts[..];
681 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
684 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
685 Some(&TokenTree::Token(_, token::Not)),
686 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
687 Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
689 if name_macro_rules.name == "macro_rules"
690 && name_zip.name == "zip" => {
691 let tts = ¯o_tts.trees().collect::<Vec<_>>();
692 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
695 Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
696 Some(&TokenTree::Token(_, token::FatArrow)),
697 Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
699 if macro_delim == token::Paren => {
700 let tts = &first_tts.trees().collect::<Vec<_>>();
701 match (tts.len(), tts.get(0), tts.get(1)) {
704 Some(&TokenTree::Token(_, token::Dollar)),
705 Some(&TokenTree::Token(_, token::Ident(ident, false))),
707 if first_delim == token::Paren && ident.name == "a" => {},
708 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
710 let tts = &second_tts.trees().collect::<Vec<_>>();
711 match (tts.len(), tts.get(0), tts.get(1)) {
714 Some(&TokenTree::Token(_, token::Dollar)),
715 Some(&TokenTree::Token(_, token::Ident(ident, false))),
717 if second_delim == token::Paren && ident.name == "a" => {},
718 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
721 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
724 _ => panic!("value: {:?}",tts),
730 fn string_to_tts_1() {
732 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
734 let expected = TokenStream::new(vec![
735 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
736 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
737 TokenTree::Delimited(
738 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
739 token::DelimToken::Paren,
740 TokenStream::new(vec![
741 TokenTree::Token(sp(6, 7),
742 token::Ident(Ident::from_str("b"), false)).into(),
743 TokenTree::Token(sp(8, 9), token::Colon).into(),
744 TokenTree::Token(sp(10, 13),
745 token::Ident(Ident::from_str("i32"), false)).into(),
748 TokenTree::Delimited(
749 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
750 token::DelimToken::Brace,
751 TokenStream::new(vec![
752 TokenTree::Token(sp(17, 18),
753 token::Ident(Ident::from_str("b"), false)).into(),
754 TokenTree::Token(sp(18, 19), token::Semi).into(),
759 assert_eq!(tts, expected);
763 #[test] fn parse_use() {
765 let use_s = "use foo::bar::baz;";
766 let vitem = string_to_item(use_s.to_string()).unwrap();
767 let vitem_s = item_to_string(&vitem);
768 assert_eq!(&vitem_s[..], use_s);
770 let use_s = "use foo::bar as baz;";
771 let vitem = string_to_item(use_s.to_string()).unwrap();
772 let vitem_s = item_to_string(&vitem);
773 assert_eq!(&vitem_s[..], use_s);
777 #[test] fn parse_extern_crate() {
779 let ex_s = "extern crate foo;";
780 let vitem = string_to_item(ex_s.to_string()).unwrap();
781 let vitem_s = item_to_string(&vitem);
782 assert_eq!(&vitem_s[..], ex_s);
784 let ex_s = "extern crate foo as bar;";
785 let vitem = string_to_item(ex_s.to_string()).unwrap();
786 let vitem_s = item_to_string(&vitem);
787 assert_eq!(&vitem_s[..], ex_s);
791 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
792 let item = string_to_item(src.to_string()).unwrap();
794 struct PatIdentVisitor {
797 impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
798 fn visit_pat(&mut self, p: &'a ast::Pat) {
800 PatKind::Ident(_ , ref spannedident, _) => {
801 self.spans.push(spannedident.span.clone());
804 crate::visit::walk_pat(self, p);
809 let mut v = PatIdentVisitor { spans: Vec::new() };
810 crate::visit::walk_item(&mut v, &item);
814 #[test] fn span_of_self_arg_pat_idents_are_correct() {
817 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
818 "impl z { fn a (&mut self, &myarg: i32) {} }",
819 "impl z { fn a (&'a self, &myarg: i32) {} }",
820 "impl z { fn a (self, &myarg: i32) {} }",
821 "impl z { fn a (self: Foo, &myarg: i32) {} }",
825 let spans = get_spans_of_pat_idents(src);
826 let (lo, hi) = (spans[0].lo(), spans[0].hi());
827 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
828 "\"{}\" != \"self\". src=\"{}\"",
829 &src[lo.to_usize()..hi.to_usize()], src)
834 #[test] fn parse_exprs () {
836 // just make sure that they parse....
837 string_to_expr("3 + 4".to_string());
838 string_to_expr("a::z.froob(b,&(987+3))".to_string());
842 #[test] fn attrs_fix_bug () {
844 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
845 -> Result<Box<Writer>, String> {
848 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
852 fn wb() -> c_int { O_WRONLY as c_int }
854 let mut fflags: c_int = wb();
859 #[test] fn crlf_doc_comments() {
861 let sess = ParseSess::new(FilePathMapping::empty());
863 let name_1 = FileName::Custom("crlf_source_1".to_string());
864 let source = "/// doc comment\r\nfn foo() {}".to_string();
865 let item = parse_item_from_source_str(name_1, source, &sess)
867 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
868 assert_eq!(doc, "/// doc comment");
870 let name_2 = FileName::Custom("crlf_source_2".to_string());
871 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
872 let item = parse_item_from_source_str(name_2, source, &sess)
874 let docs = item.attrs.iter().filter(|a| a.path == "doc")
875 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
876 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
877 assert_eq!(&docs[..], b);
879 let name_3 = FileName::Custom("clrf_source_3".to_string());
880 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
881 let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
882 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
883 assert_eq!(doc, "/** doc comment\n * with CRLF */");
889 fn parse_expr_from_source_str(
890 name: FileName, source: String, sess: &ParseSess
891 ) -> PResult<'_, P<ast::Expr>> {
892 new_parser_from_source_str(sess, name, source).parse_expr()
896 let sess = ParseSess::new(FilePathMapping::empty());
897 let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
898 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
900 let tts: Vec<_> = match expr.node {
901 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
902 _ => panic!("not a macro"),
905 let span = tts.iter().rev().next().unwrap().span();
907 match sess.source_map().span_to_snippet(span) {
908 Ok(s) => assert_eq!(&s[..], "{ body }"),
909 Err(_) => panic!("could not get snippet"),
914 // This tests that when parsing a string (rather than a file) we don't try
915 // and read in a file for a module declaration and just parse a stub.
916 // See `recurse_into_file_modules` in the parser.
918 fn out_of_line_mod() {
920 let sess = ParseSess::new(FilePathMapping::empty());
921 let item = parse_item_from_source_str(
922 PathBuf::from("foo").into(),
923 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
927 if let ast::ItemKind::Mod(ref m) = item.node {
928 assert!(m.items.len() == 2);