1 //! The main parser interface.
3 #![feature(bool_to_option)]
4 #![feature(crate_visibility_modifier)]
5 #![feature(bindings_after_at)]
6 #![feature(try_blocks)]
7 #![feature(or_patterns)]
10 use rustc_ast::token::{self, DelimToken, Nonterminal, Token};
11 use rustc_ast::tokenstream::{self, TokenStream, TokenTree};
12 use rustc_ast_pretty::pprust;
13 use rustc_data_structures::sync::Lrc;
14 use rustc_errors::{Diagnostic, FatalError, Level, PResult};
15 use rustc_session::parse::ParseSess;
16 use rustc_span::{symbol::kw, FileName, SourceFile, Span, DUMMY_SP};
18 use smallvec::SmallVec;
23 use tracing::{debug, info};
25 pub const MACRO_ARGUMENTS: Option<&'static str> = Some("macro arguments");
29 use parser::{emit_unclosed_delims, make_unclosed_delims_error, Parser};
31 pub mod validate_attr;
33 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
34 // where <thing> includes crate, expr, item, stmt, tts, and one that
35 // uses a HOF to parse anything, and <source> includes file and
38 /// A variant of 'panictry!' that works on a Vec<Diagnostic> instead of a single DiagnosticBuilder.
39 macro_rules! panictry_buffer {
40 ($handler:expr, $e:expr) => {{
41 use rustc_errors::FatalError;
42 use std::result::Result::{Err, Ok};
47 $handler.emit_diagnostic(&e);
55 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
56 let mut parser = new_parser_from_file(sess, input, None);
57 parser.parse_crate_mod()
60 pub fn parse_crate_attrs_from_file<'a>(
63 ) -> PResult<'a, Vec<ast::Attribute>> {
64 let mut parser = new_parser_from_file(sess, input, None);
65 parser.parse_inner_attributes()
68 pub fn parse_crate_from_source_str(
72 ) -> PResult<'_, ast::Crate> {
73 new_parser_from_source_str(sess, name, source).parse_crate_mod()
76 pub fn parse_crate_attrs_from_source_str(
80 ) -> PResult<'_, Vec<ast::Attribute>> {
81 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
84 pub fn parse_stream_from_source_str(
88 override_span: Option<Span>,
90 let (stream, mut errors) =
91 source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span);
92 emit_unclosed_delims(&mut errors, &sess);
96 /// Creates a new parser from a source string.
97 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
98 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
101 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
103 pub fn maybe_new_parser_from_source_str(
107 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
108 maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source))
111 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
112 /// If a span is given, that is used on an error as the as the source of the problem.
113 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path, sp: Option<Span>) -> Parser<'a> {
114 source_file_to_parser(sess, file_to_source_file(sess, path, sp))
117 /// Creates a new parser, returning buffered diagnostics if the file doesn't exist,
118 /// or from lexing the initial token stream.
119 pub fn maybe_new_parser_from_file<'a>(
122 ) -> Result<Parser<'a>, Vec<Diagnostic>> {
123 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
124 maybe_source_file_to_parser(sess, file)
127 /// Given a `source_file` and config, returns a parser.
128 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
129 panictry_buffer!(&sess.span_diagnostic, maybe_source_file_to_parser(sess, source_file))
132 /// Given a `source_file` and config, return a parser. Returns any buffered errors from lexing the
133 /// initial token stream.
134 fn maybe_source_file_to_parser(
136 source_file: Lrc<SourceFile>,
137 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
138 let end_pos = source_file.end_pos;
139 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
140 let mut parser = stream_to_parser(sess, stream, None);
141 parser.unclosed_delims = unclosed_delims;
142 if parser.token == token::Eof {
143 parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt());
149 // Must preserve old name for now, because `quote!` from the *existing*
150 // compiler expands into it.
151 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
152 stream_to_parser(sess, tts.into_iter().collect(), crate::MACRO_ARGUMENTS)
157 /// Given a session and a path and an optional span (for error reporting),
158 /// add the path to the session's source_map and return the new source_file or
159 /// error when a file can't be read.
160 fn try_file_to_source_file(
163 spanopt: Option<Span>,
164 ) -> Result<Lrc<SourceFile>, Diagnostic> {
165 sess.source_map().load_file(path).map_err(|e| {
166 let msg = format!("couldn't read {}: {}", path.display(), e);
167 let mut diag = Diagnostic::new(Level::Fatal, &msg);
168 if let Some(sp) = spanopt {
175 /// Given a session and a path and an optional span (for error reporting),
176 /// adds the path to the session's `source_map` and returns the new `source_file`.
177 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) -> Lrc<SourceFile> {
178 match try_file_to_source_file(sess, path, spanopt) {
179 Ok(source_file) => source_file,
181 sess.span_diagnostic.emit_diagnostic(&d);
187 /// Given a `source_file`, produces a sequence of token trees.
188 pub fn source_file_to_stream(
190 source_file: Lrc<SourceFile>,
191 override_span: Option<Span>,
192 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
193 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
196 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
197 /// parsing the token stream.
198 pub fn maybe_file_to_stream(
200 source_file: Lrc<SourceFile>,
201 override_span: Option<Span>,
202 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
203 let srdr = lexer::StringReader::new(sess, source_file, override_span);
204 let (token_trees, unmatched_braces) = srdr.into_token_trees();
207 Ok(stream) => Ok((stream, unmatched_braces)),
209 let mut buffer = Vec::with_capacity(1);
210 err.buffer(&mut buffer);
211 // Not using `emit_unclosed_delims` to use `db.buffer`
212 for unmatched in unmatched_braces {
213 if let Some(err) = make_unclosed_delims_error(unmatched, &sess) {
214 err.buffer(&mut buffer);
222 /// Given a stream and the `ParseSess`, produces a parser.
223 pub fn stream_to_parser<'a>(
226 subparser_name: Option<&'static str>,
228 Parser::new(sess, stream, false, subparser_name)
231 /// Runs the given subparser `f` on the tokens of the given `attr`'s item.
232 pub fn parse_in<'a, T>(
236 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
237 ) -> PResult<'a, T> {
238 let mut parser = Parser::new(sess, tts, false, Some(name));
239 let result = f(&mut parser)?;
240 if parser.token != token::Eof {
241 parser.unexpected()?;
246 // NOTE(Centril): The following probably shouldn't be here but it acknowledges the
247 // fact that architecturally, we are using parsing (read on below to understand why).
249 pub fn nt_to_tokenstream(nt: &Nonterminal, sess: &ParseSess, span: Span) -> TokenStream {
250 // A `Nonterminal` is often a parsed AST item. At this point we now
251 // need to convert the parsed AST to an actual token stream, e.g.
252 // un-parse it basically.
254 // Unfortunately there's not really a great way to do that in a
255 // guaranteed lossless fashion right now. The fallback here is to just
256 // stringify the AST node and reparse it, but this loses all span
259 // As a result, some AST nodes are annotated with the token stream they
260 // came from. Here we attempt to extract these lossless token streams
261 // before we fall back to the stringification.
262 let tokens = match *nt {
263 Nonterminal::NtItem(ref item) => {
264 prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span)
266 Nonterminal::NtIdent(ident, is_raw) => {
267 Some(tokenstream::TokenTree::token(token::Ident(ident.name, is_raw), ident.span).into())
269 Nonterminal::NtLifetime(ident) => {
270 Some(tokenstream::TokenTree::token(token::Lifetime(ident.name), ident.span).into())
272 Nonterminal::NtTT(ref tt) => Some(tt.clone().into()),
273 Nonterminal::NtExpr(ref expr) => {
274 if expr.tokens.is_none() {
275 debug!("missing tokens for expr {:?}", expr);
277 prepend_attrs(sess, &expr.attrs, expr.tokens.as_ref(), span)
282 // FIXME(#43081): Avoid this pretty-print + reparse hack
283 let source = pprust::nonterminal_to_string(nt);
284 let filename = FileName::macro_expansion_source_code(&source);
285 let tokens_for_real = parse_stream_from_source_str(filename, source, sess, Some(span));
287 // During early phases of the compiler the AST could get modified
288 // directly (e.g., attributes added or removed) and the internal cache
289 // of tokens my not be invalidated or updated. Consequently if the
290 // "lossless" token stream disagrees with our actual stringification
291 // (which has historically been much more battle-tested) then we go
292 // with the lossy stream anyway (losing span information).
294 // Note that the comparison isn't `==` here to avoid comparing spans,
295 // but it *also* is a "probable" equality which is a pretty weird
296 // definition. We mostly want to catch actual changes to the AST
297 // like a `#[cfg]` being processed or some weird `macro_rules!`
300 // What we *don't* want to catch is the fact that a user-defined
301 // literal like `0xf` is stringified as `15`, causing the cached token
302 // stream to not be literal `==` token-wise (ignoring spans) to the
303 // token stream we got from stringification.
305 // Instead the "probably equal" check here is "does each token
306 // recursively have the same discriminant?" We basically don't look at
307 // the token values here and assume that such fine grained token stream
308 // modifications, including adding/removing typically non-semantic
309 // tokens such as extra braces and commas, don't happen.
310 if let Some(tokens) = tokens {
311 if tokenstream_probably_equal_for_proc_macro(&tokens, &tokens_for_real) {
315 "cached tokens found, but they're not \"probably equal\", \
316 going with stringified version"
318 info!("cached tokens: {:?}", tokens);
319 info!("reparsed tokens: {:?}", tokens_for_real);
324 // See comments in `Nonterminal::to_tokenstream` for why we care about
325 // *probably* equal here rather than actual equality
327 // This is otherwise the same as `eq_unspanned`, only recursing with a
329 pub fn tokenstream_probably_equal_for_proc_macro(first: &TokenStream, other: &TokenStream) -> bool {
330 // When checking for `probably_eq`, we ignore certain tokens that aren't
331 // preserved in the AST. Because they are not preserved, the pretty
332 // printer arbitrarily adds or removes them when printing as token
333 // streams, making a comparison between a token stream generated from an
334 // AST and a token stream which was parsed into an AST more reliable.
335 fn semantic_tree(tree: &TokenTree) -> bool {
336 if let TokenTree::Token(token) = tree {
338 // The pretty printer tends to add trailing commas to
339 // everything, and in particular, after struct fields.
341 // The pretty printer emits `NoDelim` as whitespace.
342 | token::OpenDelim(DelimToken::NoDelim)
343 | token::CloseDelim(DelimToken::NoDelim)
344 // The pretty printer collapses many semicolons into one.
346 // The pretty printer collapses whitespace arbitrarily and can
347 // introduce whitespace from `NoDelim`.
349 // The pretty printer can turn `$crate` into `::crate_name`
350 | token::ModSep = token.kind {
357 // When comparing two `TokenStream`s, we ignore the `IsJoint` information.
359 // However, `rustc_parse::lexer::tokentrees::TokenStreamBuilder` will
360 // use `Token.glue` on adjacent tokens with the proper `IsJoint`.
361 // Since we are ignoreing `IsJoint`, a 'glued' token (e.g. `BinOp(Shr)`)
362 // and its 'split'/'unglued' compoenents (e.g. `Gt, Gt`) are equivalent
363 // when determining if two `TokenStream`s are 'probably equal'.
365 // Therefore, we use `break_two_token_op` to convert all tokens
366 // to the 'unglued' form (if it exists). This ensures that two
367 // `TokenStream`s which differ only in how their tokens are glued
368 // will be considered 'probably equal', which allows us to keep spans.
370 // This is important when the original `TokenStream` contained
371 // extra spaces (e.g. `f :: < Vec < _ > > ( ) ;'). These extra spaces
372 // will be omitted when we pretty-print, which can cause the original
373 // and reparsed `TokenStream`s to differ in the assignment of `IsJoint`,
374 // leading to some tokens being 'glued' together in one stream but not
375 // the other. See #68489 for more details.
376 fn break_tokens(tree: TokenTree) -> impl Iterator<Item = TokenTree> {
377 // In almost all cases, we should have either zero or one levels
378 // of 'unglueing'. However, in some unusual cases, we may need
379 // to iterate breaking tokens mutliple times. For example:
380 // '[BinOpEq(Shr)] => [Gt, Ge] -> [Gt, Gt, Eq]'
381 let mut token_trees: SmallVec<[_; 2]>;
382 if let TokenTree::Token(token) = &tree {
383 let mut out = SmallVec::<[_; 2]>::new();
384 out.push(token.clone());
385 // Iterate to fixpoint:
386 // * We start off with 'out' containing our initial token, and `temp` empty
387 // * If we are able to break any tokens in `out`, then `out` will have
388 // at least one more element than 'temp', so we will try to break tokens
390 // * If we cannot break any tokens in 'out', we are done
392 let mut temp = SmallVec::<[_; 2]>::new();
393 let mut changed = false;
395 for token in out.into_iter() {
396 if let Some((first, second)) = token.kind.break_two_token_op() {
397 temp.push(Token::new(first, DUMMY_SP));
398 temp.push(Token::new(second, DUMMY_SP));
409 token_trees = out.into_iter().map(TokenTree::Token).collect();
410 if token_trees.len() != 1 {
411 debug!("break_tokens: broke {:?} to {:?}", tree, token_trees);
414 token_trees = SmallVec::new();
415 token_trees.push(tree);
417 token_trees.into_iter()
420 let mut t1 = first.trees().filter(semantic_tree).flat_map(break_tokens);
421 let mut t2 = other.trees().filter(semantic_tree).flat_map(break_tokens);
422 for (t1, t2) in t1.by_ref().zip(t2.by_ref()) {
423 if !tokentree_probably_equal_for_proc_macro(&t1, &t2) {
427 t1.next().is_none() && t2.next().is_none()
430 // See comments in `Nonterminal::to_tokenstream` for why we care about
431 // *probably* equal here rather than actual equality
433 // This is otherwise the same as `eq_unspanned`, only recursing with a
435 fn tokentree_probably_equal_for_proc_macro(first: &TokenTree, other: &TokenTree) -> bool {
436 match (first, other) {
437 (TokenTree::Token(token), TokenTree::Token(token2)) => {
438 token_probably_equal_for_proc_macro(token, token2)
440 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
441 delim == delim2 && tokenstream_probably_equal_for_proc_macro(&tts, &tts2)
447 // See comments in `Nonterminal::to_tokenstream` for why we care about
448 // *probably* equal here rather than actual equality
449 fn token_probably_equal_for_proc_macro(first: &Token, other: &Token) -> bool {
450 if mem::discriminant(&first.kind) != mem::discriminant(&other.kind) {
453 use rustc_ast::token::TokenKind::*;
454 match (&first.kind, &other.kind) {
469 | (&DotDotDot, &DotDotDot)
470 | (&DotDotEq, &DotDotEq)
477 | (&FatArrow, &FatArrow)
480 | (&Question, &Question)
481 | (&Whitespace, &Whitespace)
482 | (&Comment, &Comment)
483 | (&Eof, &Eof) => true,
485 (&BinOp(a), &BinOp(b)) | (&BinOpEq(a), &BinOpEq(b)) => a == b,
487 (&OpenDelim(a), &OpenDelim(b)) | (&CloseDelim(a), &CloseDelim(b)) => a == b,
489 (&DocComment(a1, a2, a3), &DocComment(b1, b2, b3)) => a1 == b1 && a2 == b2 && a3 == b3,
491 (&Shebang(a), &Shebang(b)) => a == b,
493 (&Literal(a), &Literal(b)) => a == b,
495 (&Lifetime(a), &Lifetime(b)) => a == b,
496 (&Ident(a, b), &Ident(c, d)) => {
497 b == d && (a == c || a == kw::DollarCrate || c == kw::DollarCrate)
500 (&Interpolated(..), &Interpolated(..)) => false,
502 _ => panic!("forgot to add a token?"),
508 attrs: &[ast::Attribute],
509 tokens: Option<&tokenstream::TokenStream>,
510 span: rustc_span::Span,
511 ) -> Option<tokenstream::TokenStream> {
512 let tokens = tokens?;
513 if attrs.is_empty() {
514 return Some(tokens.clone());
516 let mut builder = tokenstream::TokenStreamBuilder::new();
520 ast::AttrStyle::Outer,
521 "inner attributes should prevent cached tokens from existing"
524 let source = pprust::attribute_to_string(attr);
525 let macro_filename = FileName::macro_expansion_source_code(&source);
527 let item = match attr.kind {
528 ast::AttrKind::Normal(ref item) => item,
529 ast::AttrKind::DocComment(..) => {
530 let stream = parse_stream_from_source_str(macro_filename, source, sess, Some(span));
531 builder.push(stream);
536 // synthesize # [ $path $tokens ] manually here
537 let mut brackets = tokenstream::TokenStreamBuilder::new();
539 // For simple paths, push the identifier directly
540 if item.path.segments.len() == 1 && item.path.segments[0].args.is_none() {
541 let ident = item.path.segments[0].ident;
542 let token = token::Ident(ident.name, ident.as_str().starts_with("r#"));
543 brackets.push(tokenstream::TokenTree::token(token, ident.span));
545 // ... and for more complicated paths, fall back to a reparse hack that
546 // should eventually be removed.
548 let stream = parse_stream_from_source_str(macro_filename, source, sess, Some(span));
549 brackets.push(stream);
552 brackets.push(item.args.outer_tokens());
554 // The span we list here for `#` and for `[ ... ]` are both wrong in
555 // that it encompasses more than each token, but it hopefully is "good
556 // enough" for now at least.
557 builder.push(tokenstream::TokenTree::token(token::Pound, attr.span));
558 let delim_span = tokenstream::DelimSpan::from_single(attr.span);
559 builder.push(tokenstream::TokenTree::Delimited(
561 token::DelimToken::Bracket,
565 builder.push(tokens.clone());
566 Some(builder.build())