1 //! The main parser interface
3 use rustc_data_structures::sync::{Lrc, Lock};
4 use ast::{self, CrateConfig, NodeId};
5 use early_buffered_lints::{BufferedEarlyLint, BufferedEarlyLintId};
6 use source_map::{SourceMap, FilePathMapping};
7 use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
8 use errors::{FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
9 use feature_gate::UnstableFeatures;
10 use parse::parser::Parser;
13 use tokenstream::{TokenStream, TokenTree};
14 use diagnostics::plugin::ErrorMap;
16 use rustc_data_structures::fx::FxHashSet;
19 use std::path::{Path, PathBuf};
22 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
33 /// Info about a parsing session.
34 pub struct ParseSess {
35 pub span_diagnostic: Handler,
36 pub unstable_features: UnstableFeatures,
37 pub config: CrateConfig,
38 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
39 /// Places where raw identifiers were used. This is used for feature gating
41 pub raw_identifier_spans: Lock<Vec<Span>>,
42 /// The registered diagnostics codes
43 crate registered_diagnostics: Lock<ErrorMap>,
44 /// Used to determine and report recursive mod inclusions
45 included_mod_stack: Lock<Vec<PathBuf>>,
46 source_map: Lrc<SourceMap>,
47 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
51 pub fn new(file_path_mapping: FilePathMapping) -> Self {
52 let cm = Lrc::new(SourceMap::new(file_path_mapping));
53 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
57 ParseSess::with_span_handler(handler, cm)
60 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
62 span_diagnostic: handler,
63 unstable_features: UnstableFeatures::from_environment(),
64 config: FxHashSet::default(),
65 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
66 raw_identifier_spans: Lock::new(Vec::new()),
67 registered_diagnostics: Lock::new(ErrorMap::new()),
68 included_mod_stack: Lock::new(vec![]),
70 buffered_lints: Lock::new(vec![]),
75 pub fn source_map(&self) -> &SourceMap {
79 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
80 lint_id: BufferedEarlyLintId,
85 self.buffered_lints.with_lock(|buffered_lints| {
86 buffered_lints.push(BufferedEarlyLint{
97 pub struct Directory<'a> {
98 pub path: Cow<'a, Path>,
99 pub ownership: DirectoryOwnership,
102 #[derive(Copy, Clone)]
103 pub enum DirectoryOwnership {
105 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
106 relative: Option<ast::Ident>,
109 UnownedViaMod(bool /* legacy warnings? */),
112 // a bunch of utility functions of the form parse_<thing>_from_<source>
113 // where <thing> includes crate, expr, item, stmt, tts, and one that
114 // uses a HOF to parse anything, and <source> includes file and
117 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
118 let mut parser = new_parser_from_file(sess, input);
119 parser.parse_crate_mod()
122 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
123 -> PResult<'a, Vec<ast::Attribute>> {
124 let mut parser = new_parser_from_file(sess, input);
125 parser.parse_inner_attributes()
128 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
129 -> PResult<ast::Crate> {
130 new_parser_from_source_str(sess, name, source).parse_crate_mod()
133 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
134 -> PResult<Vec<ast::Attribute>> {
135 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
138 crate fn parse_expr_from_source_str(name: FileName, source: String, sess: &ParseSess)
139 -> PResult<P<ast::Expr>> {
140 new_parser_from_source_str(sess, name, source).parse_expr()
145 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
146 /// when a syntax error occurred.
147 crate fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
148 -> PResult<Option<P<ast::Item>>> {
149 new_parser_from_source_str(sess, name, source).parse_item()
152 crate fn parse_stmt_from_source_str(name: FileName, source: String, sess: &ParseSess)
153 -> PResult<Option<ast::Stmt>> {
154 new_parser_from_source_str(sess, name, source).parse_stmt()
157 pub fn parse_stream_from_source_str(name: FileName, source: String, sess: &ParseSess,
158 override_span: Option<Span>)
160 source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span)
163 /// Create a new parser from a source string
164 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
166 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
169 /// Create a new parser from a source string. Returns any buffered errors from lexing the initial
171 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
172 -> Result<Parser, Vec<Diagnostic>>
174 let mut parser = maybe_source_file_to_parser(sess,
175 sess.source_map().new_source_file(name, source))?;
176 parser.recurse_into_file_modules = false;
180 /// Create a new parser, handling errors as appropriate
181 /// if the file doesn't exist
182 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
183 source_file_to_parser(sess, file_to_source_file(sess, path, None))
186 /// Create a new parser, returning buffered diagnostics if the file doesn't
187 /// exist or from lexing the initial token stream.
188 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
189 -> Result<Parser<'a>, Vec<Diagnostic>> {
190 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
191 maybe_source_file_to_parser(sess, file)
194 /// Given a session, a crate config, a path, and a span, add
195 /// the file at the given path to the source_map, and return a parser.
196 /// On an error, use the given span as the source of the problem.
197 crate fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
199 directory_ownership: DirectoryOwnership,
200 module_name: Option<String>,
201 sp: Span) -> Parser<'a> {
202 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
203 p.directory.ownership = directory_ownership;
204 p.root_module_name = module_name;
208 /// Given a source_file and config, return a parser
209 fn source_file_to_parser(sess: & ParseSess, source_file: Lrc<SourceFile>) -> Parser {
210 panictry_buffer!(&sess.span_diagnostic,
211 maybe_source_file_to_parser(sess, source_file))
214 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
215 /// initial token stream.
216 fn maybe_source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>)
217 -> Result<Parser, Vec<Diagnostic>>
219 let end_pos = source_file.end_pos;
220 let mut parser = stream_to_parser(sess, maybe_file_to_stream(sess, source_file, None)?);
222 if parser.token == token::Eof && parser.span.is_dummy() {
223 parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
229 // must preserve old name for now, because quote! from the *existing*
230 // compiler expands into it
231 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser {
232 stream_to_parser(sess, tts.into_iter().collect())
238 /// Given a session and a path and an optional span (for error reporting),
239 /// add the path to the session's source_map and return the new source_file or
240 /// error when a file can't be read.
241 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
242 -> Result<Lrc<SourceFile>, Diagnostic> {
243 sess.source_map().load_file(path)
245 let msg = format!("couldn't read {}: {}", path.display(), e);
246 let mut diag = Diagnostic::new(Level::Fatal, &msg);
247 if let Some(sp) = spanopt {
254 /// Given a session and a path and an optional span (for error reporting),
255 /// add the path to the session's source_map and return the new source_file.
256 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
258 match try_file_to_source_file(sess, path, spanopt) {
259 Ok(source_file) => source_file,
261 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
267 /// Given a source_file, produce a sequence of token-trees
268 pub fn source_file_to_stream(sess: &ParseSess,
269 source_file: Lrc<SourceFile>,
270 override_span: Option<Span>) -> TokenStream {
271 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
274 /// Given a source file, produce a sequence of token-trees. Returns any buffered errors from
275 /// parsing the token tream.
276 pub fn maybe_file_to_stream(sess: &ParseSess,
277 source_file: Lrc<SourceFile>,
278 override_span: Option<Span>) -> Result<TokenStream, Vec<Diagnostic>> {
279 let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
282 match srdr.parse_all_token_trees() {
283 Ok(stream) => Ok(stream),
285 let mut buffer = Vec::with_capacity(1);
286 err.buffer(&mut buffer);
292 /// Given stream and the `ParseSess`, produce a parser
293 pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser {
294 Parser::new(sess, stream, None, true, false)
297 /// Parse a string representing a character literal into its final form.
298 /// Rather than just accepting/rejecting a given literal, unescapes it as
299 /// well. Can take any slice prefixed by a character escape. Returns the
300 /// character and the number of characters consumed.
301 fn char_lit(lit: &str, diag: Option<(Span, &Handler)>) -> (char, isize) {
304 // Handle non-escaped chars first.
305 if lit.as_bytes()[0] != b'\\' {
306 // If the first byte isn't '\\' it might part of a multi-byte char, so
307 // get the char with chars().
308 let c = lit.chars().next().unwrap();
312 // Handle escaped chars.
313 match lit.as_bytes()[1] as char {
322 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
323 let c = char::from_u32(v).unwrap();
327 assert_eq!(lit.as_bytes()[2], b'{');
328 let idx = lit.find('}').unwrap();
330 // All digits and '_' are ascii, so treat each byte as a char.
332 for c in lit[3..idx].bytes() {
333 let c = char::from(c);
335 let x = c.to_digit(16).unwrap();
336 v = v.checked_mul(16).unwrap().checked_add(x).unwrap();
339 let c = char::from_u32(v).unwrap_or_else(|| {
340 if let Some((span, diag)) = diag {
341 let mut diag = diag.struct_span_err(span, "invalid unicode character escape");
343 diag.help("unicode escape must be at most 10FFFF").emit();
345 diag.help("unicode escape must not be a surrogate").emit();
350 (c, (idx + 1) as isize)
352 _ => panic!("lexer should have rejected a bad character escape {}", lit)
356 /// Parse a string representing a string literal into its final form. Does
358 pub fn str_lit(lit: &str, diag: Option<(Span, &Handler)>) -> String {
359 debug!("str_lit: given {}", lit.escape_default());
360 let mut res = String::with_capacity(lit.len());
362 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
364 /// Eat everything up to a non-whitespace
365 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
367 match it.peek().map(|x| x.1) {
368 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
376 let mut chars = lit.char_indices().peekable();
377 while let Some((i, c)) = chars.next() {
380 let ch = chars.peek().unwrap_or_else(|| {
381 panic!("{}", error(i))
386 } else if ch == '\r' {
388 let ch = chars.peek().unwrap_or_else(|| {
389 panic!("{}", error(i))
393 panic!("lexer accepted bare CR");
397 // otherwise, a normal escape
398 let (c, n) = char_lit(&lit[i..], diag);
399 for _ in 0..n - 1 { // we don't need to move past the first \
406 let ch = chars.peek().unwrap_or_else(|| {
407 panic!("{}", error(i))
411 panic!("lexer accepted bare CR");
420 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
421 debug!("parse_str_lit: returning {}", res);
425 /// Parse a string representing a raw string literal into its final form. The
426 /// only operation this does is convert embedded CRLF into a single LF.
427 fn raw_str_lit(lit: &str) -> String {
428 debug!("raw_str_lit: given {}", lit.escape_default());
429 let mut res = String::with_capacity(lit.len());
431 let mut chars = lit.chars().peekable();
432 while let Some(c) = chars.next() {
434 if *chars.peek().unwrap() != '\n' {
435 panic!("lexer accepted bare CR");
448 // check if `s` looks like i32 or u1234 etc.
449 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
450 s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
454 ($opt_diag:expr, |$span:ident, $diag:ident| $($body:tt)*) => {
456 Some(($span, $diag)) => { $($body)* }
462 crate fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Handler)>)
463 -> (bool /* suffix illegal? */, Option<ast::LitKind>) {
467 token::Byte(i) => (true, Some(LitKind::Byte(byte_lit(&i.as_str()).0))),
468 token::Char(i) => (true, Some(LitKind::Char(char_lit(&i.as_str(), diag).0))),
470 // There are some valid suffixes for integer and float literals,
471 // so all the handling is done internally.
472 token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
473 token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
475 token::Str_(mut sym) => {
476 // If there are no characters requiring special treatment we can
477 // reuse the symbol from the Token. Otherwise, we must generate a
478 // new symbol because the string in the LitKind is different to the
479 // string in the Token.
480 let s = &sym.as_str();
481 if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
482 sym = Symbol::intern(&str_lit(s, diag));
484 (true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
486 token::StrRaw(mut sym, n) => {
488 let s = &sym.as_str();
489 if s.contains('\r') {
490 sym = Symbol::intern(&raw_str_lit(s));
492 (true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
494 token::ByteStr(i) => {
495 (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))
497 token::ByteStrRaw(i, _) => {
498 (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes()))))
503 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
504 -> Option<ast::LitKind> {
505 debug!("filtered_float_lit: {}, {:?}", data, suffix);
506 let suffix = match suffix {
507 Some(suffix) => suffix,
508 None => return Some(ast::LitKind::FloatUnsuffixed(data)),
511 Some(match &*suffix.as_str() {
512 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
513 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
515 err!(diag, |span, diag| {
516 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
517 // if it looks like a width, lets try to be helpful.
518 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
519 diag.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit()
521 let msg = format!("invalid suffix `{}` for float literal", suf);
522 diag.struct_span_err(span, &msg)
523 .help("valid suffixes are `f32` and `f64`")
528 ast::LitKind::FloatUnsuffixed(data)
532 fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
533 -> Option<ast::LitKind> {
534 debug!("float_lit: {:?}, {:?}", s, suffix);
535 // FIXME #2252: bounds checking float literals is deferred until trans
537 // Strip underscores without allocating a new String unless necessary.
539 let s = if s.chars().any(|c| c == '_') {
540 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
546 filtered_float_lit(Symbol::intern(s), suffix, diag)
549 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
550 fn byte_lit(lit: &str) -> (u8, usize) {
551 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
554 (lit.as_bytes()[0], 1)
556 assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
557 let b = match lit.as_bytes()[1] {
566 match u64::from_str_radix(&lit[2..4], 16).ok() {
573 None => panic!(err(3))
581 fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
582 let mut res = Vec::with_capacity(lit.len());
584 let error = |i| panic!("lexer should have rejected {} at {}", lit, i);
586 /// Eat everything up to a non-whitespace
587 fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
589 match it.peek().map(|x| x.1) {
590 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
598 // byte string literals *must* be ASCII, but the escapes don't have to be
599 let mut chars = lit.bytes().enumerate().peekable();
602 Some((i, b'\\')) => {
603 match chars.peek().unwrap_or_else(|| error(i)).1 {
604 b'\n' => eat(&mut chars),
607 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
608 panic!("lexer accepted bare CR");
613 // otherwise, a normal escape
614 let (c, n) = byte_lit(&lit[i..]);
615 // we don't need to move past the first \
623 Some((i, b'\r')) => {
624 if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
625 panic!("lexer accepted bare CR");
630 Some((_, c)) => res.push(c),
638 fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
639 -> Option<ast::LitKind> {
640 // s can only be ascii, byte indexing is fine
642 // Strip underscores without allocating a new String unless necessary.
644 let mut s = if s.chars().any(|c| c == '_') {
645 s2 = s.chars().filter(|&c| c != '_').collect::<String>();
651 debug!("integer_lit: {}, {:?}", s, suffix);
655 let mut ty = ast::LitIntType::Unsuffixed;
657 if s.starts_with('0') && s.len() > 1 {
658 match s.as_bytes()[1] {
666 // 1f64 and 2f32 etc. are valid float literals.
667 if let Some(suf) = suffix {
668 if looks_like_width_suffix(&['f'], &suf.as_str()) {
669 let err = match base {
670 16 => Some("hexadecimal float literal is not supported"),
671 8 => Some("octal float literal is not supported"),
672 2 => Some("binary float literal is not supported"),
675 if let Some(err) = err {
676 err!(diag, |span, diag| diag.span_err(span, err));
678 return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
686 if let Some(suf) = suffix {
687 if suf.as_str().is_empty() {
688 err!(diag, |span, diag| diag.span_bug(span, "found empty literal suffix in Some"));
690 ty = match &*suf.as_str() {
691 "isize" => ast::LitIntType::Signed(ast::IntTy::Isize),
692 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
693 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
694 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
695 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
696 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
697 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Usize),
698 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
699 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
700 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
701 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
702 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
704 // i<digits> and u<digits> look like widths, so lets
705 // give an error message along those lines
706 err!(diag, |span, diag| {
707 if looks_like_width_suffix(&['i', 'u'], suf) {
708 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
709 diag.struct_span_err(span, &msg)
710 .help("valid widths are 8, 16, 32, 64 and 128")
713 let msg = format!("invalid suffix `{}` for numeric literal", suf);
714 diag.struct_span_err(span, &msg)
715 .help("the suffix must be one of the integral types \
716 (`u32`, `isize`, etc)")
726 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
727 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
729 Some(match u128::from_str_radix(s, base) {
730 Ok(r) => ast::LitKind::Int(r, ty),
732 // small bases are lexed as if they were base 10, e.g, the string
733 // might be `0b10201`. This will cause the conversion above to fail,
734 // but these cases have errors in the lexer: we don't want to emit
735 // two errors, and we especially don't want to emit this error since
736 // it isn't necessarily true.
737 let already_errored = base < 10 &&
738 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
740 if !already_errored {
741 err!(diag, |span, diag| diag.span_err(span, "int literal is too large"));
743 ast::LitKind::Int(0, ty)
748 /// `SeqSep` : a sequence separator (token)
749 /// and whether a trailing separator is allowed.
751 pub sep: Option<token::Token>,
752 pub trailing_sep_allowed: bool,
756 pub fn trailing_allowed(t: token::Token) -> SeqSep {
759 trailing_sep_allowed: true,
763 pub fn none() -> SeqSep {
766 trailing_sep_allowed: false,
774 use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
775 use ast::{self, Ident, PatKind};
776 use attr::first_attr_value_str_by_name;
778 use print::pprust::item_to_string;
779 use tokenstream::{DelimSpan, TokenTree};
780 use util::parser_testing::string_to_stream;
781 use util::parser_testing::{string_to_expr, string_to_item};
784 // produce a syntax_pos::span
785 fn sp(a: u32, b: u32) -> Span {
786 Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
790 #[test] fn bad_path_expr_1() {
792 string_to_expr("::abc::def::return".to_string());
796 // check the token-tree-ization of macros
798 fn string_to_tts_macro () {
801 string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
802 let tts: &[TokenTree] = &tts[..];
804 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
807 Some(&TokenTree::Token(_, token::Ident(name_macro_rules, false))),
808 Some(&TokenTree::Token(_, token::Not)),
809 Some(&TokenTree::Token(_, token::Ident(name_zip, false))),
810 Some(&TokenTree::Delimited(_, macro_delim, ref macro_tts)),
812 if name_macro_rules.name == "macro_rules"
813 && name_zip.name == "zip" => {
814 let tts = ¯o_tts.stream().trees().collect::<Vec<_>>();
815 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
818 Some(&TokenTree::Delimited(_, first_delim, ref first_tts)),
819 Some(&TokenTree::Token(_, token::FatArrow)),
820 Some(&TokenTree::Delimited(_, second_delim, ref second_tts)),
822 if macro_delim == token::Paren => {
823 let tts = &first_tts.stream().trees().collect::<Vec<_>>();
824 match (tts.len(), tts.get(0), tts.get(1)) {
827 Some(&TokenTree::Token(_, token::Dollar)),
828 Some(&TokenTree::Token(_, token::Ident(ident, false))),
830 if first_delim == token::Paren && ident.name == "a" => {},
831 _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
833 let tts = &second_tts.stream().trees().collect::<Vec<_>>();
834 match (tts.len(), tts.get(0), tts.get(1)) {
837 Some(&TokenTree::Token(_, token::Dollar)),
838 Some(&TokenTree::Token(_, token::Ident(ident, false))),
840 if second_delim == token::Paren && ident.name == "a" => {},
841 _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
844 _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
847 _ => panic!("value: {:?}",tts),
853 fn string_to_tts_1() {
855 let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
857 let expected = TokenStream::new(vec![
858 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"), false)).into(),
859 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"), false)).into(),
860 TokenTree::Delimited(
861 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
862 token::DelimToken::Paren,
863 TokenStream::new(vec![
864 TokenTree::Token(sp(6, 7),
865 token::Ident(Ident::from_str("b"), false)).into(),
866 TokenTree::Token(sp(8, 9), token::Colon).into(),
867 TokenTree::Token(sp(10, 13),
868 token::Ident(Ident::from_str("i32"), false)).into(),
871 TokenTree::Delimited(
872 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
873 token::DelimToken::Brace,
874 TokenStream::new(vec![
875 TokenTree::Token(sp(17, 18),
876 token::Ident(Ident::from_str("b"), false)).into(),
877 TokenTree::Token(sp(18, 19), token::Semi).into(),
882 assert_eq!(tts, expected);
886 #[test] fn parse_use() {
888 let use_s = "use foo::bar::baz;";
889 let vitem = string_to_item(use_s.to_string()).unwrap();
890 let vitem_s = item_to_string(&vitem);
891 assert_eq!(&vitem_s[..], use_s);
893 let use_s = "use foo::bar as baz;";
894 let vitem = string_to_item(use_s.to_string()).unwrap();
895 let vitem_s = item_to_string(&vitem);
896 assert_eq!(&vitem_s[..], use_s);
900 #[test] fn parse_extern_crate() {
902 let ex_s = "extern crate foo;";
903 let vitem = string_to_item(ex_s.to_string()).unwrap();
904 let vitem_s = item_to_string(&vitem);
905 assert_eq!(&vitem_s[..], ex_s);
907 let ex_s = "extern crate foo as bar;";
908 let vitem = string_to_item(ex_s.to_string()).unwrap();
909 let vitem_s = item_to_string(&vitem);
910 assert_eq!(&vitem_s[..], ex_s);
914 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
915 let item = string_to_item(src.to_string()).unwrap();
917 struct PatIdentVisitor {
920 impl<'a> ::visit::Visitor<'a> for PatIdentVisitor {
921 fn visit_pat(&mut self, p: &'a ast::Pat) {
923 PatKind::Ident(_ , ref spannedident, _) => {
924 self.spans.push(spannedident.span.clone());
927 ::visit::walk_pat(self, p);
932 let mut v = PatIdentVisitor { spans: Vec::new() };
933 ::visit::walk_item(&mut v, &item);
937 #[test] fn span_of_self_arg_pat_idents_are_correct() {
940 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
941 "impl z { fn a (&mut self, &myarg: i32) {} }",
942 "impl z { fn a (&'a self, &myarg: i32) {} }",
943 "impl z { fn a (self, &myarg: i32) {} }",
944 "impl z { fn a (self: Foo, &myarg: i32) {} }",
948 let spans = get_spans_of_pat_idents(src);
949 let (lo, hi) = (spans[0].lo(), spans[0].hi());
950 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
951 "\"{}\" != \"self\". src=\"{}\"",
952 &src[lo.to_usize()..hi.to_usize()], src)
957 #[test] fn parse_exprs () {
959 // just make sure that they parse....
960 string_to_expr("3 + 4".to_string());
961 string_to_expr("a::z.froob(b,&(987+3))".to_string());
965 #[test] fn attrs_fix_bug () {
967 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
968 -> Result<Box<Writer>, String> {
971 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
975 fn wb() -> c_int { O_WRONLY as c_int }
977 let mut fflags: c_int = wb();
982 #[test] fn crlf_doc_comments() {
984 let sess = ParseSess::new(FilePathMapping::empty());
986 let name_1 = FileName::Custom("crlf_source_1".to_string());
987 let source = "/// doc comment\r\nfn foo() {}".to_string();
988 let item = parse_item_from_source_str(name_1, source, &sess)
990 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
991 assert_eq!(doc, "/// doc comment");
993 let name_2 = FileName::Custom("crlf_source_2".to_string());
994 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
995 let item = parse_item_from_source_str(name_2, source, &sess)
997 let docs = item.attrs.iter().filter(|a| a.path == "doc")
998 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
999 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1000 assert_eq!(&docs[..], b);
1002 let name_3 = FileName::Custom("clrf_source_3".to_string());
1003 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1004 let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
1005 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
1006 assert_eq!(doc, "/** doc comment\n * with CRLF */");
1013 let sess = ParseSess::new(FilePathMapping::empty());
1014 let expr = parse::parse_expr_from_source_str(PathBuf::from("foo").into(),
1015 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
1017 let tts: Vec<_> = match expr.node {
1018 ast::ExprKind::Mac(ref mac) => mac.node.stream().trees().collect(),
1019 _ => panic!("not a macro"),
1022 let span = tts.iter().rev().next().unwrap().span();
1024 match sess.source_map().span_to_snippet(span) {
1025 Ok(s) => assert_eq!(&s[..], "{ body }"),
1026 Err(_) => panic!("could not get snippet"),
1031 // This tests that when parsing a string (rather than a file) we don't try
1032 // and read in a file for a module declaration and just parse a stub.
1033 // See `recurse_into_file_modules` in the parser.
1035 fn out_of_line_mod() {
1037 let sess = ParseSess::new(FilePathMapping::empty());
1038 let item = parse_item_from_source_str(
1039 PathBuf::from("foo").into(),
1040 "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
1042 ).unwrap().unwrap();
1044 if let ast::ItemKind::Mod(ref m) = item.node {
1045 assert!(m.items.len() == 2);