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::tokenstream::{TokenStream, TokenTree};
10 use crate::diagnostics::plugin::ErrorMap;
11 use crate::print::pprust::token_to_string;
13 use errors::{FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
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 raw identifiers.
42 pub raw_identifier_spans: Lock<Vec<Span>>,
43 /// The registered diagnostics codes.
44 crate registered_diagnostics: Lock<ErrorMap>,
45 /// Used to determine and report recursive module inclusions.
46 included_mod_stack: Lock<Vec<PathBuf>>,
47 source_map: Lrc<SourceMap>,
48 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
52 pub fn new(file_path_mapping: FilePathMapping) -> Self {
53 let cm = Lrc::new(SourceMap::new(file_path_mapping));
54 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
58 ParseSess::with_span_handler(handler, cm)
61 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
63 span_diagnostic: handler,
64 unstable_features: UnstableFeatures::from_environment(),
65 config: FxHashSet::default(),
66 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
67 raw_identifier_spans: Lock::new(Vec::new()),
68 registered_diagnostics: Lock::new(ErrorMap::new()),
69 included_mod_stack: Lock::new(vec![]),
71 buffered_lints: Lock::new(vec![]),
76 pub fn source_map(&self) -> &SourceMap {
80 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
81 lint_id: BufferedEarlyLintId,
86 self.buffered_lints.with_lock(|buffered_lints| {
87 buffered_lints.push(BufferedEarlyLint{
98 pub struct Directory<'a> {
99 pub path: Cow<'a, Path>,
100 pub ownership: DirectoryOwnership,
103 #[derive(Copy, Clone)]
104 pub enum DirectoryOwnership {
106 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
107 relative: Option<ast::Ident>,
110 UnownedViaMod(bool /* legacy warnings? */),
113 // a bunch of utility functions of the form parse_<thing>_from_<source>
114 // where <thing> includes crate, expr, item, stmt, tts, and one that
115 // uses a HOF to parse anything, and <source> includes file and
118 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
119 let mut parser = new_parser_from_file(sess, input);
120 parser.parse_crate_mod()
123 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
124 -> PResult<'a, Vec<ast::Attribute>> {
125 let mut parser = new_parser_from_file(sess, input);
126 parser.parse_inner_attributes()
129 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
130 -> PResult<'_, ast::Crate> {
131 new_parser_from_source_str(sess, name, source).parse_crate_mod()
134 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
135 -> PResult<'_, Vec<ast::Attribute>> {
136 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
139 pub fn parse_stream_from_source_str(
143 override_span: Option<Span>,
144 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
145 source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span)
148 /// Creates a new parser from a source string.
149 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
150 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
153 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
155 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
156 -> Result<Parser<'_>, Vec<Diagnostic>>
158 let mut parser = maybe_source_file_to_parser(sess,
159 sess.source_map().new_source_file(name, source))?;
160 parser.recurse_into_file_modules = false;
164 /// Creates a new parser, handling errors as appropriate
165 /// if the file doesn't exist
166 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
167 source_file_to_parser(sess, file_to_source_file(sess, path, None))
170 /// Creates a new parser, returning buffered diagnostics if the file doesn't
171 /// exist or from lexing the initial token stream.
172 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
173 -> Result<Parser<'a>, Vec<Diagnostic>> {
174 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
175 maybe_source_file_to_parser(sess, file)
178 /// Given a session, a crate config, a path, and a span, add
179 /// the file at the given path to the source_map, and return a parser.
180 /// On an error, use the given span as the source of the problem.
181 crate fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
183 directory_ownership: DirectoryOwnership,
184 module_name: Option<String>,
185 sp: Span) -> Parser<'a> {
186 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
187 p.directory.ownership = directory_ownership;
188 p.root_module_name = module_name;
192 /// Given a source_file and config, return a parser
193 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
194 panictry_buffer!(&sess.span_diagnostic,
195 maybe_source_file_to_parser(sess, source_file))
198 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
199 /// initial token stream.
200 fn maybe_source_file_to_parser(
202 source_file: Lrc<SourceFile>,
203 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
204 let end_pos = source_file.end_pos;
205 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
206 let mut parser = stream_to_parser(sess, stream);
207 parser.unclosed_delims = unclosed_delims;
208 if parser.token == token::Eof && parser.span.is_dummy() {
209 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
215 // must preserve old name for now, because quote! from the *existing*
216 // compiler expands into it
217 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
218 stream_to_parser(sess, tts.into_iter().collect())
224 /// Given a session and a path and an optional span (for error reporting),
225 /// add the path to the session's source_map and return the new source_file or
226 /// error when a file can't be read.
227 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
228 -> Result<Lrc<SourceFile>, Diagnostic> {
229 sess.source_map().load_file(path)
231 let msg = format!("couldn't read {}: {}", path.display(), e);
232 let mut diag = Diagnostic::new(Level::Fatal, &msg);
233 if let Some(sp) = spanopt {
240 /// Given a session and a path and an optional span (for error reporting),
241 /// add the path to the session's `source_map` and return the new `source_file`.
242 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
244 match try_file_to_source_file(sess, path, spanopt) {
245 Ok(source_file) => source_file,
247 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
253 /// Given a source_file, produces a sequence of token trees.
254 pub fn source_file_to_stream(
256 source_file: Lrc<SourceFile>,
257 override_span: Option<Span>,
258 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
259 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
262 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
263 /// parsing the token tream.
264 pub fn maybe_file_to_stream(
266 source_file: Lrc<SourceFile>,
267 override_span: Option<Span>,
268 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
269 let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
272 match srdr.parse_all_token_trees() {
273 Ok(stream) => Ok((stream, srdr.unmatched_braces)),
275 let mut buffer = Vec::with_capacity(1);
276 err.buffer(&mut buffer);
277 // Not using `emit_unclosed_delims` to use `db.buffer`
278 for unmatched in srdr.unmatched_braces {
279 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
280 "incorrect close delimiter: `{}`",
281 token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
283 db.span_label(unmatched.found_span, "incorrect close delimiter");
284 if let Some(sp) = unmatched.candidate_span {
285 db.span_label(sp, "close delimiter possibly meant for this");
287 if let Some(sp) = unmatched.unclosed_span {
288 db.span_label(sp, "un-closed delimiter");
290 db.buffer(&mut buffer);
297 /// Given stream and the `ParseSess`, produces a parser.
298 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser<'_> {
299 Parser::new(sess, stream, None, true, false)
302 /// Parses a string representing a character literal into its final form.
303 /// Rather than just accepting/rejecting a given literal, unescapes it as
304 /// well. Can take any slice prefixed by a character escape. Returns the
305 /// character and the number of characters consumed.
306 fn char_lit(lit: &str, diag: Option<(Span, &Handler)>) -> (char, isize) {
309 // Handle non-escaped chars first.
310 if lit.as_bytes()[0] != b'\\' {
311 // If the first byte isn't '\\' it might part of a multi-byte char, so
312 // get the char with chars().
313 let c = lit.chars().next().unwrap();
317 // Handle escaped chars.
318 match lit.as_bytes()[1] as char {
327 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
328 let c = char::from_u32(v).unwrap();
332 assert_eq!(lit.as_bytes()[2], b'{');
333 let idx = lit.find('}').unwrap();
335 // All digits and '_' are ascii, so treat each byte as a char.
337 for c in lit[3..idx].bytes() {
338 let c = char::from(c);
340 let x = c.to_digit(16).unwrap();
341 v = v.checked_mul(16).unwrap().checked_add(x).unwrap();
344 let c = char::from_u32(v).unwrap_or_else(|| {
345 if let Some((span, diag)) = diag {
346 let mut diag = diag.struct_span_err(span, "invalid unicode character escape");
348 diag.help("unicode escape must be at most 10FFFF").emit();
350 diag.help("unicode escape must not be a surrogate").emit();
355 (c, (idx + 1) as isize)
357 _ => panic!("lexer should have rejected a bad character escape {}", lit)
361 /// Parses a string representing a string literal into its final form. Does unescaping.
362 pub fn str_lit(lit: &str, diag: Option<(Span, &Handler)>) -> String {
363 debug!("str_lit: given {}", lit.escape_default());
364 let mut res = String::with_capacity(lit.len());
366 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
368 /// Eat everything up to a non-whitespace.
369 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
371 match it.peek().map(|x| x.1) {
372 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
380 let mut chars = lit.char_indices().peekable();
381 while let Some((i, c)) = chars.next() {
384 let ch = chars.peek().unwrap_or_else(|| {
385 panic!("{}", error(i))
390 } else if ch == '\r' {
392 let ch = chars.peek().unwrap_or_else(|| {
393 panic!("{}", error(i))
397 panic!("lexer accepted bare CR");
401 // otherwise, a normal escape
402 let (c, n) = char_lit(&lit[i..], diag);
403 for _ in 0..n - 1 { // we don't need to move past the first \
410 let ch = chars.peek().unwrap_or_else(|| {
411 panic!("{}", error(i))
415 panic!("lexer accepted bare CR");
424 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
425 debug!("parse_str_lit: returning {}", res);
429 /// Parses a string representing a raw string literal into its final form. The
430 /// only operation this does is convert embedded CRLF into a single LF.
431 fn raw_str_lit(lit: &str) -> String {
432 debug!("raw_str_lit: given {}", lit.escape_default());
433 let mut res = String::with_capacity(lit.len());
435 let mut chars = lit.chars().peekable();
436 while let Some(c) = chars.next() {
438 if *chars.peek().unwrap() != '\n' {
439 panic!("lexer accepted bare CR");
452 // check if `s` looks like i32 or u1234 etc.
453 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
454 s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
458 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
460 Some(($span, $diag)) => { $($body)* }
466 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
467 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
471 token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
472 token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str(), diag).0))),
473 token::Err(i) => (true, Some(LitKind::Err(i))),
475 // There are some valid suffixes for integer and float literals,
476 // so all the handling is done internally.
477 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
478 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
480 token::Str_(mut sym) => {
481 // If there are no characters requiring special treatment we can
482 // reuse the symbol from the Token. Otherwise, we must generate a
483 // new symbol because the string in the LitKind is different to the
484 // string in the Token.
485 let s = &sym.as_str();
486 if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
487 sym = Symbol::intern(&str_lit(s, diag));
489 (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
491 token::StrRaw(mut sym, n) => {
493 let s = &sym.as_str();
494 if s.contains('\r') {
495 sym = Symbol::intern(&raw_str_lit(s));
497 (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
499 token::ByteStr(i) => {
500 (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
502 token::ByteStrRaw(i, _) => {
503 (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
508 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
509 -> Option<ast::LitKind> {
510 debug!("filtered_float_lit: {}, {:?}", data, suffix);
511 let suffix = match suffix {
512 Some(suffix) => suffix,
513 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
516 Some(match &*suffix.as_str() {
517 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
518 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
520 err!(diag, |span, diag| {
521 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
522 // if it looks like a width, lets try to be helpful.
523 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
524 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
526 let msg = format!("invalid suffix `{}` for float literal", suf);
527 diag.struct_span_err(span, &msg)
528 .span_label(span, format!("invalid suffix `{}`", suf))
529 .help("valid suffixes are `f32` and `f64`")
534 ast::LitKind::FloatUnsuffixed(data)
538 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
539 -> Option<ast::LitKind> {
540 debug!("float_lit: {:?}, {:?}", s, suffix);
541 // FIXME #2252: bounds checking float literals is deferred until trans
543 // Strip underscores without allocating a new String unless necessary.
545 let s = if s.chars().any(|c| c == '_') {
546 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
552 filtered_float_lit(Symbol::intern(s), suffix, diag)
555 /// Parses a string representing a byte literal into its final form. Similar to `char_lit`.
556 fn byte_lit(lit: &str) -> (u8, usize) {
557 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
560 (lit.as_bytes()[0], 1)
562 assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
563 let b = match lit.as_bytes()[1] {
572 match u64::from_str_radix(&lit[2..4], 16).ok() {
579 None => panic!(err(3))
587 fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
588 let mut res = Vec::with_capacity(lit.len());
590 let error = |i| panic!("lexer should have rejected {} at {}", lit, i);
592 /// Eat everything up to a non-whitespace.
593 fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
595 match it.peek().map(|x| x.1) {
596 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
604 // byte string literals *must* be ASCII, but the escapes don't have to be
605 let mut chars = lit.bytes().enumerate().peekable();
608 Some((i, b'\\')) => {
609 match chars.peek().unwrap_or_else(|| error(i)).1 {
610 b'\n' => eat(&mut chars),
613 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
614 panic!("lexer accepted bare CR");
619 // otherwise, a normal escape
620 let (c, n) = byte_lit(&lit[i..]);
621 // we don't need to move past the first \
629 Some((i, b'\r')) => {
630 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
631 panic!("lexer accepted bare CR");
636 Some((_, c)) => res.push(c),
644 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
645 -> Option<ast::LitKind> {
646 // s can only be ascii, byte indexing is fine
648 // Strip underscores without allocating a new String unless necessary.
650 let mut s = if s.chars().any(|c| c == '_') {
651 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
657 debug!("integer_lit: {}, {:?}", s, suffix);
661 let mut ty = ast::LitIntType::Unsuffixed;
663 if s.starts_with('0') && s.len() > 1 {
664 match s.as_bytes()[1] {
672 // 1f64 and 2f32 etc. are valid float literals.
673 if let Some(suf) = suffix {
674 if looks_like_width_suffix(&['f'], &suf.as_str()) {
675 let err = match base {
676 16 => Some("hexadecimal float literal is not supported"),
677 8 => Some("octal float literal is not supported"),
678 2 => Some("binary float literal is not supported"),
681 if let Some(err) = err {
682 err!(diag, |span, diag| {
683 diag.struct_span_err(span, err)
684 .span_label(span, "not supported")
688 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
696 if let Some(suf) = suffix {
697 if suf.as_str().is_empty() {
698 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
700 ty = match &*suf.as_str() {
701 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
702 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
703 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
704 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
705 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
706 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
707 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
708 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
709 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
710 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
711 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
712 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
714 // i<digits> and u<digits> look like widths, so lets
715 // give an error message along those lines
716 err!(diag, |span, diag| {
717 if looks_like_width_suffix(&['i', 'u'], suf) {
718 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
719 diag.struct_span_err(span, &msg)
720 .help("valid widths are 8, 16, 32, 64 and 128")
723 let msg = format!("invalid suffix `{}` for numeric literal", suf);
724 diag.struct_span_err(span, &msg)
725 .span_label(span, format!("invalid suffix `{}`", suf))
726 .help("the suffix must be one of the integral types \
727 (`u32`, `isize`, etc)")
737 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
738 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
740 Some(match u128::from_str_radix(s, base) {
741 Ok(r) => ast::LitKind::Int(r, ty),
743 // small bases are lexed as if they were base 10, e.g, the string
744 // might be `0b10201`. This will cause the conversion above to fail,
745 // but these cases have errors in the lexer: we don't want to emit
746 // two errors, and we especially don't want to emit this error since
747 // it isn't necessarily true.
748 let already_errored = base < 10 &&
749 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
751 if !already_errored {
752 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
754 ast::LitKind::Int(0, ty)
759 /// A sequence separator.
761 /// The seperator token.
762 pub sep: Option<token::Token>,
763 /// `true` if a trailing separator is allowed.
764 pub trailing_sep_allowed: bool,
768 pub fn trailing_allowed(t: token::Token) -> SeqSep {
771 trailing_sep_allowed: true,
775 pub fn none() -> SeqSep {
778 trailing_sep_allowed: false,
786 use crate::ast::{self, Ident, PatKind};
787 use crate::attr::first_attr_value_str_by_name;
789 use crate::print::pprust::item_to_string;
790 use crate::tokenstream::{DelimSpan, TokenTree};
791 use crate::util::parser_testing::string_to_stream;
792 use crate::util::parser_testing::{string_to_expr, string_to_item};
793 use crate::with_globals;
794 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
798 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
799 /// when a syntax error occurred.
800 fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
801 -> PResult<'_, Option<P<ast::Item>>> {
802 new_parser_from_source_str(sess, name, source).parse_item()
805 // produce a syntax_pos::span
806 fn sp(a: u32, b: u32) -> Span {
807 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
811 #[test] fn bad_path_expr_1() {
813 string_to_expr("::abc::def::return".to_string());
817 // check the token-tree-ization of macros
819 fn string_to_tts_macro () {
822 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
823 let tts: &[TokenTree] = &tts[..];
825 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
828 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
829 Some(&TokenTree::Token(_, token::Not)),
830 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
831 Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
833 if name_macro_rules.name == "macro_rules"
834 && name_zip.name == "zip" => {
835 let tts = ¯o_tts.trees().collect::<Vec<_>>();
836 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
839 Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
840 Some(&TokenTree::Token(_, token::FatArrow)),
841 Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
843 if macro_delim == token::Paren => {
844 let tts = &first_tts.trees().collect::<Vec<_>>();
845 match (tts.len(), tts.get(0), tts.get(1)) {
848 Some(&TokenTree::Token(_, token::Dollar)),
849 Some(&TokenTree::Token(_, token::Ident(ident, false))),
851 if first_delim == token::Paren && ident.name == "a" => {},
852 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
854 let tts = &second_tts.trees().collect::<Vec<_>>();
855 match (tts.len(), tts.get(0), tts.get(1)) {
858 Some(&TokenTree::Token(_, token::Dollar)),
859 Some(&TokenTree::Token(_, token::Ident(ident, false))),
861 if second_delim == token::Paren && ident.name == "a" => {},
862 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
865 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
868 _ => panic!("value: {:?}",tts),
874 fn string_to_tts_1() {
876 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
878 let expected = TokenStream::new(vec![
879 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
880 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
881 TokenTree::Delimited(
882 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
883 token::DelimToken::Paren,
884 TokenStream::new(vec![
885 TokenTree::Token(sp(6, 7),
886 token::Ident(Ident::from_str("b"), false)).into(),
887 TokenTree::Token(sp(8, 9), token::Colon).into(),
888 TokenTree::Token(sp(10, 13),
889 token::Ident(Ident::from_str("i32"), false)).into(),
892 TokenTree::Delimited(
893 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
894 token::DelimToken::Brace,
895 TokenStream::new(vec![
896 TokenTree::Token(sp(17, 18),
897 token::Ident(Ident::from_str("b"), false)).into(),
898 TokenTree::Token(sp(18, 19), token::Semi).into(),
903 assert_eq!(tts, expected);
907 #[test] fn parse_use() {
909 let use_s = "use foo::bar::baz;";
910 let vitem = string_to_item(use_s.to_string()).unwrap();
911 let vitem_s = item_to_string(&vitem);
912 assert_eq!(&vitem_s[..], use_s);
914 let use_s = "use foo::bar as baz;";
915 let vitem = string_to_item(use_s.to_string()).unwrap();
916 let vitem_s = item_to_string(&vitem);
917 assert_eq!(&vitem_s[..], use_s);
921 #[test] fn parse_extern_crate() {
923 let ex_s = "extern crate foo;";
924 let vitem = string_to_item(ex_s.to_string()).unwrap();
925 let vitem_s = item_to_string(&vitem);
926 assert_eq!(&vitem_s[..], ex_s);
928 let ex_s = "extern crate foo as bar;";
929 let vitem = string_to_item(ex_s.to_string()).unwrap();
930 let vitem_s = item_to_string(&vitem);
931 assert_eq!(&vitem_s[..], ex_s);
935 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
936 let item = string_to_item(src.to_string()).unwrap();
938 struct PatIdentVisitor {
941 impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
942 fn visit_pat(&mut self, p: &'a ast::Pat) {
944 PatKind::Ident(_ , ref spannedident, _) => {
945 self.spans.push(spannedident.span.clone());
948 crate::visit::walk_pat(self, p);
953 let mut v = PatIdentVisitor { spans: Vec::new() };
954 crate::visit::walk_item(&mut v, &item);
958 #[test] fn span_of_self_arg_pat_idents_are_correct() {
961 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
962 "impl z { fn a (&mut self, &myarg: i32) {} }",
963 "impl z { fn a (&'a self, &myarg: i32) {} }",
964 "impl z { fn a (self, &myarg: i32) {} }",
965 "impl z { fn a (self: Foo, &myarg: i32) {} }",
969 let spans = get_spans_of_pat_idents(src);
970 let (lo, hi) = (spans[0].lo(), spans[0].hi());
971 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
972 "\"{}\" != \"self\". src=\"{}\"",
973 &src[lo.to_usize()..hi.to_usize()], src)
978 #[test] fn parse_exprs () {
980 // just make sure that they parse....
981 string_to_expr("3 + 4".to_string());
982 string_to_expr("a::z.froob(b,&(987+3))".to_string());
986 #[test] fn attrs_fix_bug () {
988 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
989 -> Result<Box<Writer>, String> {
992 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
996 fn wb() -> c_int { O_WRONLY as c_int }
998 let mut fflags: c_int = wb();
1003 #[test] fn crlf_doc_comments() {
1005 let sess = ParseSess::new(FilePathMapping::empty());
1007 let name_1 = FileName::Custom("crlf_source_1".to_string());
1008 let source = "/// doc comment\r\nfn foo() {}".to_string();
1009 let item = parse_item_from_source_str(name_1, source, &sess)
1011 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1012 assert_eq!(doc, "/// doc comment");
1014 let name_2 = FileName::Custom("crlf_source_2".to_string());
1015 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1016 let item = parse_item_from_source_str(name_2, source, &sess)
1018 let docs = item.attrs.iter().filter(|a| a.path == "doc")
1019 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
1020 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1021 assert_eq!(&docs[..], b);
1023 let name_3 = FileName::Custom("clrf_source_3".to_string());
1024 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1025 let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
1026 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1027 assert_eq!(doc, "/** doc comment\n * with CRLF */");
1033 fn parse_expr_from_source_str(
1034 name: FileName, source: String, sess: &ParseSess
1035 ) -> PResult<'_, P<ast::Expr>> {
1036 new_parser_from_source_str(sess, name, source).parse_expr()
1040 let sess = ParseSess::new(FilePathMapping::empty());
1041 let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
1042 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
1044 let tts: Vec<_> = match expr.node {
1045 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
1046 _ => panic!("not a macro"),
1049 let span = tts.iter().rev().next().unwrap().span();
1051 match sess.source_map().span_to_snippet(span) {
1052 Ok(s) => assert_eq!(&s[..], "{ body }"),
1053 Err(_) => panic!("could not get snippet"),
1058 // This tests that when parsing a string (rather than a file) we don't try
1059 // and read in a file for a module declaration and just parse a stub.
1060 // See `recurse_into_file_modules` in the parser.
1062 fn out_of_line_mod() {
1064 let sess = ParseSess::new(FilePathMapping::empty());
1065 let item = parse_item_from_source_str(
1066 PathBuf::from("foo").into(),
1067 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
1069 ).unwrap().unwrap();
1071 if let ast::ItemKind::Mod(ref m) = item.node {
1072 assert!(m.items.len() == 2);