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::errors::{FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
7 use crate::feature_gate::UnstableFeatures;
8 use crate::parse::parser::Parser;
9 use crate::symbol::Symbol;
10 use crate::tokenstream::{TokenStream, TokenTree};
11 use crate::diagnostics::plugin::ErrorMap;
12 use crate::print::pprust::token_to_string;
14 use rustc_data_structures::sync::{Lrc, Lock};
15 use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
18 use rustc_data_structures::fx::FxHashSet;
21 use std::path::{Path, PathBuf};
24 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
35 /// Info about a parsing session.
36 pub struct ParseSess {
37 pub span_diagnostic: Handler,
38 pub unstable_features: UnstableFeatures,
39 pub config: CrateConfig,
40 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
41 /// Places where raw identifiers were used. This is used for feature gating
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 mod 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>,
145 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
146 source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span)
149 /// Create a new parser from a source string
150 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
151 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
154 /// Create a new parser from a source string. Returns any buffered errors from lexing the initial
156 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
157 -> Result<Parser<'_>, Vec<Diagnostic>>
159 let mut parser = maybe_source_file_to_parser(sess,
160 sess.source_map().new_source_file(name, source))?;
161 parser.recurse_into_file_modules = false;
165 /// Create a new parser, handling errors as appropriate
166 /// if the file doesn't exist
167 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
168 source_file_to_parser(sess, file_to_source_file(sess, path, None))
171 /// Create a new parser, returning buffered diagnostics if the file doesn't
172 /// exist or from lexing the initial token stream.
173 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
174 -> Result<Parser<'a>, Vec<Diagnostic>> {
175 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
176 maybe_source_file_to_parser(sess, file)
179 /// Given a session, a crate config, a path, and a span, add
180 /// the file at the given path to the source_map, and return a parser.
181 /// On an error, use the given span as the source of the problem.
182 crate fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
184 directory_ownership: DirectoryOwnership,
185 module_name: Option<String>,
186 sp: Span) -> Parser<'a> {
187 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
188 p.directory.ownership = directory_ownership;
189 p.root_module_name = module_name;
193 /// Given a source_file and config, return a parser
194 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
195 panictry_buffer!(&sess.span_diagnostic,
196 maybe_source_file_to_parser(sess, source_file))
199 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
200 /// initial token stream.
201 fn maybe_source_file_to_parser(
203 source_file: Lrc<SourceFile>,
204 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
205 let end_pos = source_file.end_pos;
206 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
207 let mut parser = stream_to_parser(sess, stream);
208 parser.unclosed_delims = unclosed_delims;
209 if parser.token == token::Eof && parser.span.is_dummy() {
210 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
216 // must preserve old name for now, because quote! from the *existing*
217 // compiler expands into it
218 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
219 stream_to_parser(sess, tts.into_iter().collect())
225 /// Given a session and a path and an optional span (for error reporting),
226 /// add the path to the session's source_map and return the new source_file or
227 /// error when a file can't be read.
228 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
229 -> Result<Lrc<SourceFile>, Diagnostic> {
230 sess.source_map().load_file(path)
232 let msg = format!("couldn't read {}: {}", path.display(), e);
233 let mut diag = Diagnostic::new(Level::Fatal, &msg);
234 if let Some(sp) = spanopt {
241 /// Given a session and a path and an optional span (for error reporting),
242 /// add the path to the session's source_map and return the new source_file.
243 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
245 match try_file_to_source_file(sess, path, spanopt) {
246 Ok(source_file) => source_file,
248 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
254 /// Given a source_file, produce a sequence of token-trees
255 pub fn source_file_to_stream(
257 source_file: Lrc<SourceFile>,
258 override_span: Option<Span>,
259 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
260 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
263 /// Given a source file, produce a sequence of token-trees. Returns any buffered errors from
264 /// parsing the token tream.
265 pub fn maybe_file_to_stream(
267 source_file: Lrc<SourceFile>,
268 override_span: Option<Span>,
269 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
270 let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
273 match srdr.parse_all_token_trees() {
274 Ok(stream) => Ok((stream, srdr.unmatched_braces)),
276 let mut buffer = Vec::with_capacity(1);
277 err.buffer(&mut buffer);
278 // Not using `emit_unclosed_delims` to use `db.buffer`
279 for unmatched in srdr.unmatched_braces {
280 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
281 "incorrect close delimiter: `{}`",
282 token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
284 db.span_label(unmatched.found_span, "incorrect close delimiter");
285 if let Some(sp) = unmatched.candidate_span {
286 db.span_label(sp, "close delimiter possibly meant for this");
288 if let Some(sp) = unmatched.unclosed_span {
289 db.span_label(sp, "un-closed delimiter");
291 db.buffer(&mut buffer);
298 /// Given stream and the `ParseSess`, produce a parser
299 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> {
300 Parser::new(sess, stream, None, true, false)
303 /// Parse a string representing a character literal into its final form.
304 /// Rather than just accepting/rejecting a given literal, unescapes it as
305 /// well. Can take any slice prefixed by a character escape. Returns the
306 /// character and the number of characters consumed.
307 fn char_lit(lit: &str, diag: Option<(Span, &Handler)>) -> (char, isize) {
310 // Handle non-escaped chars first.
311 if lit.as_bytes()[0] != b'\\' {
312 // If the first byte isn't '\\' it might part of a multi-byte char, so
313 // get the char with chars().
314 let c = lit.chars().next().unwrap();
318 // Handle escaped chars.
319 match lit.as_bytes()[1] as char {
328 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
329 let c = char::from_u32(v).unwrap();
333 assert_eq!(lit.as_bytes()[2], b'{');
334 let idx = lit.find('}').unwrap();
336 // All digits and '_' are ascii, so treat each byte as a char.
338 for c in lit[3..idx].bytes() {
339 let c = char::from(c);
341 let x = c.to_digit(16).unwrap();
342 v = v.checked_mul(16).unwrap().checked_add(x).unwrap();
345 let c = char::from_u32(v).unwrap_or_else(|| {
346 if let Some((span, diag)) = diag {
347 let mut diag = diag.struct_span_err(span, "invalid unicode character escape");
349 diag.help("unicode escape must be at most 10FFFF").emit();
351 diag.help("unicode escape must not be a surrogate").emit();
356 (c, (idx + 1) as isize)
358 _ => panic!("lexer should have rejected a bad character escape {}", lit)
362 /// Parse a string representing a string literal into its final form. Does
364 pub fn str_lit(lit: &str, diag: Option<(Span, &Handler)>) -> String {
365 debug!("str_lit: given {}", lit.escape_default());
366 let mut res = String::with_capacity(lit.len());
368 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
370 /// Eat everything up to a non-whitespace
371 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
373 match it.peek().map(|x| x.1) {
374 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
382 let mut chars = lit.char_indices().peekable();
383 while let Some((i, c)) = chars.next() {
386 let ch = chars.peek().unwrap_or_else(|| {
387 panic!("{}", error(i))
392 } else if ch == '\r' {
394 let ch = chars.peek().unwrap_or_else(|| {
395 panic!("{}", error(i))
399 panic!("lexer accepted bare CR");
403 // otherwise, a normal escape
404 let (c, n) = char_lit(&lit[i..], diag);
405 for _ in 0..n - 1 { // we don't need to move past the first \
412 let ch = chars.peek().unwrap_or_else(|| {
413 panic!("{}", error(i))
417 panic!("lexer accepted bare CR");
426 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
427 debug!("parse_str_lit: returning {}", res);
431 /// Parse a string representing a raw string literal into its final form. The
432 /// only operation this does is convert embedded CRLF into a single LF.
433 fn raw_str_lit(lit: &str) -> String {
434 debug!("raw_str_lit: given {}", lit.escape_default());
435 let mut res = String::with_capacity(lit.len());
437 let mut chars = lit.chars().peekable();
438 while let Some(c) = chars.next() {
440 if *chars.peek().unwrap() != '\n' {
441 panic!("lexer accepted bare CR");
454 // check if `s` looks like i32 or u1234 etc.
455 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
456 s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
460 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
462 Some(($span, $diag)) => { $($body)* }
468 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
469 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
473 token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
474 token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str(), diag).0))),
475 token::Err(i) => (true, Some(LitKind::Err(i))),
477 // There are some valid suffixes for integer and float literals,
478 // so all the handling is done internally.
479 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
480 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
482 token::Str_(mut sym) => {
483 // If there are no characters requiring special treatment we can
484 // reuse the symbol from the Token. Otherwise, we must generate a
485 // new symbol because the string in the LitKind is different to the
486 // string in the Token.
487 let s = &sym.as_str();
488 if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
489 sym = Symbol::intern(&str_lit(s, diag));
491 (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
493 token::StrRaw(mut sym, n) => {
495 let s = &sym.as_str();
496 if s.contains('\r') {
497 sym = Symbol::intern(&raw_str_lit(s));
499 (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
501 token::ByteStr(i) => {
502 (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
504 token::ByteStrRaw(i, _) => {
505 (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
510 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
511 -> Option<ast::LitKind> {
512 debug!("filtered_float_lit: {}, {:?}", data, suffix);
513 let suffix = match suffix {
514 Some(suffix) => suffix,
515 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
518 Some(match &*suffix.as_str() {
519 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
520 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
522 err!(diag, |span, diag| {
523 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
524 // if it looks like a width, lets try to be helpful.
525 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
526 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
528 let msg = format!("invalid suffix `{}` for float literal", suf);
529 diag.struct_span_err(span, &msg)
530 .span_label(span, format!("invalid suffix `{}`", suf))
531 .help("valid suffixes are `f32` and `f64`")
536 ast::LitKind::FloatUnsuffixed(data)
540 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
541 -> Option<ast::LitKind> {
542 debug!("float_lit: {:?}, {:?}", s, suffix);
543 // FIXME #2252: bounds checking float literals is deferred until trans
545 // Strip underscores without allocating a new String unless necessary.
547 let s = if s.chars().any(|c| c == '_') {
548 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
554 filtered_float_lit(Symbol::intern(s), suffix, diag)
557 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
558 fn byte_lit(lit: &str) -> (u8, usize) {
559 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
562 (lit.as_bytes()[0], 1)
564 assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
565 let b = match lit.as_bytes()[1] {
574 match u64::from_str_radix(&lit[2..4], 16).ok() {
581 None => panic!(err(3))
589 fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
590 let mut res = Vec::with_capacity(lit.len());
592 let error = |i| panic!("lexer should have rejected {} at {}", lit, i);
594 /// Eat everything up to a non-whitespace
595 fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
597 match it.peek().map(|x| x.1) {
598 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
606 // byte string literals *must* be ASCII, but the escapes don't have to be
607 let mut chars = lit.bytes().enumerate().peekable();
610 Some((i, b'\\')) => {
611 match chars.peek().unwrap_or_else(|| error(i)).1 {
612 b'\n' => eat(&mut chars),
615 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
616 panic!("lexer accepted bare CR");
621 // otherwise, a normal escape
622 let (c, n) = byte_lit(&lit[i..]);
623 // we don't need to move past the first \
631 Some((i, b'\r')) => {
632 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
633 panic!("lexer accepted bare CR");
638 Some((_, c)) => res.push(c),
646 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
647 -> Option<ast::LitKind> {
648 // s can only be ascii, byte indexing is fine
650 // Strip underscores without allocating a new String unless necessary.
652 let mut s = if s.chars().any(|c| c == '_') {
653 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
659 debug!("integer_lit: {}, {:?}", s, suffix);
663 let mut ty = ast::LitIntType::Unsuffixed;
665 if s.starts_with('0') && s.len() > 1 {
666 match s.as_bytes()[1] {
674 // 1f64 and 2f32 etc. are valid float literals.
675 if let Some(suf) = suffix {
676 if looks_like_width_suffix(&['f'], &suf.as_str()) {
677 let err = match base {
678 16 => Some("hexadecimal float literal is not supported"),
679 8 => Some("octal float literal is not supported"),
680 2 => Some("binary float literal is not supported"),
683 if let Some(err) = err {
684 err!(diag, |span, diag| {
685 diag.struct_span_err(span, err)
686 .span_label(span, "not supported")
690 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
698 if let Some(suf) = suffix {
699 if suf.as_str().is_empty() {
700 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
702 ty = match &*suf.as_str() {
703 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
704 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
705 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
706 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
707 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
708 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
709 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
710 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
711 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
712 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
713 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
714 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
716 // i<digits> and u<digits> look like widths, so lets
717 // give an error message along those lines
718 err!(diag, |span, diag| {
719 if looks_like_width_suffix(&['i', 'u'], suf) {
720 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
721 diag.struct_span_err(span, &msg)
722 .help("valid widths are 8, 16, 32, 64 and 128")
725 let msg = format!("invalid suffix `{}` for numeric literal", suf);
726 diag.struct_span_err(span, &msg)
727 .span_label(span, format!("invalid suffix `{}`", suf))
728 .help("the suffix must be one of the integral types \
729 (`u32`, `isize`, etc)")
739 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
740 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
742 Some(match u128::from_str_radix(s, base) {
743 Ok(r) => ast::LitKind::Int(r, ty),
745 // small bases are lexed as if they were base 10, e.g, the string
746 // might be `0b10201`. This will cause the conversion above to fail,
747 // but these cases have errors in the lexer: we don't want to emit
748 // two errors, and we especially don't want to emit this error since
749 // it isn't necessarily true.
750 let already_errored = base < 10 &&
751 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
753 if !already_errored {
754 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
756 ast::LitKind::Int(0, ty)
761 /// `SeqSep` : a sequence separator (token)
762 /// and whether a trailing separator is allowed.
764 pub sep: Option<token::Token>,
765 pub trailing_sep_allowed: bool,
769 pub fn trailing_allowed(t: token::Token) -> SeqSep {
772 trailing_sep_allowed: true,
776 pub fn none() -> SeqSep {
779 trailing_sep_allowed: false,
787 use crate::ast::{self, Ident, PatKind};
788 use crate::attr::first_attr_value_str_by_name;
790 use crate::print::pprust::item_to_string;
791 use crate::tokenstream::{DelimSpan, TokenTree};
792 use crate::util::parser_testing::string_to_stream;
793 use crate::util::parser_testing::{string_to_expr, string_to_item};
794 use crate::with_globals;
795 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
799 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
800 /// when a syntax error occurred.
801 fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
802 -> PResult<'_, Option<P<ast::Item>>> {
803 new_parser_from_source_str(sess, name, source).parse_item()
806 // produce a syntax_pos::span
807 fn sp(a: u32, b: u32) -> Span {
808 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
812 #[test] fn bad_path_expr_1() {
814 string_to_expr("::abc::def::return".to_string());
818 // check the token-tree-ization of macros
820 fn string_to_tts_macro () {
823 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
824 let tts: &[TokenTree] = &tts[..];
826 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
829 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
830 Some(&TokenTree::Token(_, token::Not)),
831 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
832 Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
834 if name_macro_rules.name == "macro_rules"
835 && name_zip.name == "zip" => {
836 let tts = ¯o_tts.trees().collect::<Vec<_>>();
837 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
840 Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
841 Some(&TokenTree::Token(_, token::FatArrow)),
842 Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
844 if macro_delim == token::Paren => {
845 let tts = &first_tts.trees().collect::<Vec<_>>();
846 match (tts.len(), tts.get(0), tts.get(1)) {
849 Some(&TokenTree::Token(_, token::Dollar)),
850 Some(&TokenTree::Token(_, token::Ident(ident, false))),
852 if first_delim == token::Paren && ident.name == "a" => {},
853 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
855 let tts = &second_tts.trees().collect::<Vec<_>>();
856 match (tts.len(), tts.get(0), tts.get(1)) {
859 Some(&TokenTree::Token(_, token::Dollar)),
860 Some(&TokenTree::Token(_, token::Ident(ident, false))),
862 if second_delim == token::Paren && ident.name == "a" => {},
863 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
866 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
869 _ => panic!("value: {:?}",tts),
875 fn string_to_tts_1() {
877 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
879 let expected = TokenStream::new(vec![
880 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
881 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
882 TokenTree::Delimited(
883 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
884 token::DelimToken::Paren,
885 TokenStream::new(vec![
886 TokenTree::Token(sp(6, 7),
887 token::Ident(Ident::from_str("b"), false)).into(),
888 TokenTree::Token(sp(8, 9), token::Colon).into(),
889 TokenTree::Token(sp(10, 13),
890 token::Ident(Ident::from_str("i32"), false)).into(),
893 TokenTree::Delimited(
894 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
895 token::DelimToken::Brace,
896 TokenStream::new(vec![
897 TokenTree::Token(sp(17, 18),
898 token::Ident(Ident::from_str("b"), false)).into(),
899 TokenTree::Token(sp(18, 19), token::Semi).into(),
904 assert_eq!(tts, expected);
908 #[test] fn parse_use() {
910 let use_s = "use foo::bar::baz;";
911 let vitem = string_to_item(use_s.to_string()).unwrap();
912 let vitem_s = item_to_string(&vitem);
913 assert_eq!(&vitem_s[..], use_s);
915 let use_s = "use foo::bar as baz;";
916 let vitem = string_to_item(use_s.to_string()).unwrap();
917 let vitem_s = item_to_string(&vitem);
918 assert_eq!(&vitem_s[..], use_s);
922 #[test] fn parse_extern_crate() {
924 let ex_s = "extern crate foo;";
925 let vitem = string_to_item(ex_s.to_string()).unwrap();
926 let vitem_s = item_to_string(&vitem);
927 assert_eq!(&vitem_s[..], ex_s);
929 let ex_s = "extern crate foo as bar;";
930 let vitem = string_to_item(ex_s.to_string()).unwrap();
931 let vitem_s = item_to_string(&vitem);
932 assert_eq!(&vitem_s[..], ex_s);
936 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
937 let item = string_to_item(src.to_string()).unwrap();
939 struct PatIdentVisitor {
942 impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
943 fn visit_pat(&mut self, p: &'a ast::Pat) {
945 PatKind::Ident(_ , ref spannedident, _) => {
946 self.spans.push(spannedident.span.clone());
949 crate::visit::walk_pat(self, p);
954 let mut v = PatIdentVisitor { spans: Vec::new() };
955 crate::visit::walk_item(&mut v, &item);
959 #[test] fn span_of_self_arg_pat_idents_are_correct() {
962 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
963 "impl z { fn a (&mut self, &myarg: i32) {} }",
964 "impl z { fn a (&'a self, &myarg: i32) {} }",
965 "impl z { fn a (self, &myarg: i32) {} }",
966 "impl z { fn a (self: Foo, &myarg: i32) {} }",
970 let spans = get_spans_of_pat_idents(src);
971 let (lo, hi) = (spans[0].lo(), spans[0].hi());
972 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
973 "\"{}\" != \"self\". src=\"{}\"",
974 &src[lo.to_usize()..hi.to_usize()], src)
979 #[test] fn parse_exprs () {
981 // just make sure that they parse....
982 string_to_expr("3 + 4".to_string());
983 string_to_expr("a::z.froob(b,&(987+3))".to_string());
987 #[test] fn attrs_fix_bug () {
989 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
990 -> Result<Box<Writer>, String> {
993 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
997 fn wb() -> c_int { O_WRONLY as c_int }
999 let mut fflags: c_int = wb();
1004 #[test] fn crlf_doc_comments() {
1006 let sess = ParseSess::new(FilePathMapping::empty());
1008 let name_1 = FileName::Custom("crlf_source_1".to_string());
1009 let source = "/// doc comment\r\nfn foo() {}".to_string();
1010 let item = parse_item_from_source_str(name_1, source, &sess)
1012 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1013 assert_eq!(doc, "/// doc comment");
1015 let name_2 = FileName::Custom("crlf_source_2".to_string());
1016 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1017 let item = parse_item_from_source_str(name_2, source, &sess)
1019 let docs = item.attrs.iter().filter(|a| a.path == "doc")
1020 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1021 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1022 assert_eq!(&docs[..], b);
1024 let name_3 = FileName::Custom("clrf_source_3".to_string());
1025 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1026 let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
1027 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1028 assert_eq!(doc, "/** doc comment\n * with CRLF */");
1034 fn parse_expr_from_source_str(
1035 name: FileName, source: String, sess: &ParseSess
1036 ) -> PResult<'_, P<ast::Expr>> {
1037 new_parser_from_source_str(sess, name, source).parse_expr()
1041 let sess = ParseSess::new(FilePathMapping::empty());
1042 let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
1043 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
1045 let tts: Vec<_> = match expr.node {
1046 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
1047 _ => panic!("not a macro"),
1050 let span = tts.iter().rev().next().unwrap().span();
1052 match sess.source_map().span_to_snippet(span) {
1053 Ok(s) => assert_eq!(&s[..], "{ body }"),
1054 Err(_) => panic!("could not get snippet"),
1059 // This tests that when parsing a string (rather than a file) we don't try
1060 // and read in a file for a module declaration and just parse a stub.
1061 // See `recurse_into_file_modules` in the parser.
1063 fn out_of_line_mod() {
1065 let sess = ParseSess::new(FilePathMapping::empty());
1066 let item = parse_item_from_source_str(
1067 PathBuf::from("foo").into(),
1068 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
1070 ).unwrap().unwrap();
1072 if let ast::ItemKind::Mod(ref m) = item.node {
1073 assert!(m.items.len() == 2);