]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/lib.rs
Rollup merge of #94113 - Mizobrook-kan:issue-94025, r=estebank
[rust.git] / compiler / rustc_parse / src / lib.rs
1 //! The main parser interface.
2
3 #![feature(array_windows)]
4 #![feature(crate_visibility_modifier)]
5 #![feature(if_let_guard)]
6 #![feature(box_patterns)]
7 #![feature(let_else)]
8 #![recursion_limit = "256"]
9
10 #[macro_use]
11 extern crate tracing;
12
13 use rustc_ast as ast;
14 use rustc_ast::token::{self, Nonterminal, Token, TokenKind};
15 use rustc_ast::tokenstream::{self, AttributesData, CanSynthesizeMissingTokens, LazyTokenStream};
16 use rustc_ast::tokenstream::{AttrAnnotatedTokenStream, AttrAnnotatedTokenTree};
17 use rustc_ast::tokenstream::{Spacing, TokenStream};
18 use rustc_ast::AstLike;
19 use rustc_ast::Attribute;
20 use rustc_ast::{AttrItem, MetaItem};
21 use rustc_ast_pretty::pprust;
22 use rustc_data_structures::sync::Lrc;
23 use rustc_errors::{Applicability, Diagnostic, FatalError, Level, PResult};
24 use rustc_session::parse::ParseSess;
25 use rustc_span::{FileName, SourceFile, Span};
26
27 use std::path::Path;
28 use std::str;
29
30 pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
31
32 #[macro_use]
33 pub mod parser;
34 use parser::{emit_unclosed_delims, make_unclosed_delims_error, Parser};
35 pub mod lexer;
36 pub mod validate_attr;
37
38 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
39 // where <thing> includes crate, expr, item, stmt, tts, and one that
40 // uses a HOF to parse anything, and <source> includes file and
41 // `source_str`.
42
43 /// A variant of 'panictry!' that works on a Vec<Diagnostic> instead of a single DiagnosticBuilder.
44 macro_rules! panictry_buffer {
45     ($handler:expr, $e:expr) => {{
46         use rustc_errors::FatalError;
47         use std::result::Result::{Err, Ok};
48         match $e {
49             Ok(e) => e,
50             Err(errs) => {
51                 for e in errs {
52                     $handler.emit_diagnostic(&e);
53                 }
54                 FatalError.raise()
55             }
56         }
57     }};
58 }
59
60 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
61     let mut parser = new_parser_from_file(sess, input, None);
62     parser.parse_crate_mod()
63 }
64
65 pub fn parse_crate_attrs_from_file<'a>(
66     input: &Path,
67     sess: &'a ParseSess,
68 ) -> PResult<'a, Vec<ast::Attribute>> {
69     let mut parser = new_parser_from_file(sess, input, None);
70     parser.parse_inner_attributes()
71 }
72
73 pub fn parse_crate_from_source_str(
74     name: FileName,
75     source: String,
76     sess: &ParseSess,
77 ) -> PResult<'_, ast::Crate> {
78     new_parser_from_source_str(sess, name, source).parse_crate_mod()
79 }
80
81 pub fn parse_crate_attrs_from_source_str(
82     name: FileName,
83     source: String,
84     sess: &ParseSess,
85 ) -> PResult<'_, Vec<ast::Attribute>> {
86     new_parser_from_source_str(sess, name, source).parse_inner_attributes()
87 }
88
89 pub fn parse_stream_from_source_str(
90     name: FileName,
91     source: String,
92     sess: &ParseSess,
93     override_span: Option<Span>,
94 ) -> TokenStream {
95     let (stream, mut errors) =
96         source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span);
97     emit_unclosed_delims(&mut errors, &sess);
98     stream
99 }
100
101 /// Creates a new parser from a source string.
102 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
103     panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
104 }
105
106 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
107 /// token stream.
108 pub fn maybe_new_parser_from_source_str(
109     sess: &ParseSess,
110     name: FileName,
111     source: String,
112 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
113     maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source))
114 }
115
116 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
117 /// If a span is given, that is used on an error as the source of the problem.
118 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path, sp: Option<Span>) -> Parser<'a> {
119     source_file_to_parser(sess, file_to_source_file(sess, path, sp))
120 }
121
122 /// Given a `source_file` and config, returns a parser.
123 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
124     panictry_buffer!(&sess.span_diagnostic, maybe_source_file_to_parser(sess, source_file))
125 }
126
127 /// Given a `source_file` and config, return a parser. Returns any buffered errors from lexing the
128 /// initial token stream.
129 fn maybe_source_file_to_parser(
130     sess: &ParseSess,
131     source_file: Lrc<SourceFile>,
132 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
133     let end_pos = source_file.end_pos;
134     let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
135     let mut parser = stream_to_parser(sess, stream, None);
136     parser.unclosed_delims = unclosed_delims;
137     if parser.token == token::Eof {
138         parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt(), None);
139     }
140
141     Ok(parser)
142 }
143
144 // Base abstractions
145
146 /// Given a session and a path and an optional span (for error reporting),
147 /// add the path to the session's source_map and return the new source_file or
148 /// error when a file can't be read.
149 fn try_file_to_source_file(
150     sess: &ParseSess,
151     path: &Path,
152     spanopt: Option<Span>,
153 ) -> Result<Lrc<SourceFile>, Diagnostic> {
154     sess.source_map().load_file(path).map_err(|e| {
155         let msg = format!("couldn't read {}: {}", path.display(), e);
156         let mut diag = Diagnostic::new(Level::Fatal, &msg);
157         if let Some(sp) = spanopt {
158             diag.set_span(sp);
159         }
160         diag
161     })
162 }
163
164 /// Given a session and a path and an optional span (for error reporting),
165 /// adds the path to the session's `source_map` and returns the new `source_file`.
166 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) -> Lrc<SourceFile> {
167     match try_file_to_source_file(sess, path, spanopt) {
168         Ok(source_file) => source_file,
169         Err(d) => {
170             sess.span_diagnostic.emit_diagnostic(&d);
171             FatalError.raise();
172         }
173     }
174 }
175
176 /// Given a `source_file`, produces a sequence of token trees.
177 pub fn source_file_to_stream(
178     sess: &ParseSess,
179     source_file: Lrc<SourceFile>,
180     override_span: Option<Span>,
181 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
182     panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
183 }
184
185 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
186 /// parsing the token stream.
187 pub fn maybe_file_to_stream(
188     sess: &ParseSess,
189     source_file: Lrc<SourceFile>,
190     override_span: Option<Span>,
191 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
192     let src = source_file.src.as_ref().unwrap_or_else(|| {
193         sess.span_diagnostic.bug(&format!(
194             "cannot lex `source_file` without source: {}",
195             sess.source_map().filename_for_diagnostics(&source_file.name)
196         ));
197     });
198
199     let (token_trees, unmatched_braces) =
200         lexer::parse_token_trees(sess, src.as_str(), source_file.start_pos, override_span);
201
202     match token_trees {
203         Ok(stream) => Ok((stream, unmatched_braces)),
204         Err(err) => {
205             let mut buffer = Vec::with_capacity(1);
206             err.buffer(&mut buffer);
207             // Not using `emit_unclosed_delims` to use `db.buffer`
208             for unmatched in unmatched_braces {
209                 if let Some(err) = make_unclosed_delims_error(unmatched, &sess) {
210                     err.buffer(&mut buffer);
211                 }
212             }
213             Err(buffer)
214         }
215     }
216 }
217
218 /// Given a stream and the `ParseSess`, produces a parser.
219 pub fn stream_to_parser<'a>(
220     sess: &'a ParseSess,
221     stream: TokenStream,
222     subparser_name: Option<&'static str>,
223 ) -> Parser<'a> {
224     Parser::new(sess, stream, false, subparser_name)
225 }
226
227 /// Runs the given subparser `f` on the tokens of the given `attr`'s item.
228 pub fn parse_in<'a, T>(
229     sess: &'a ParseSess,
230     tts: TokenStream,
231     name: &'static str,
232     mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
233 ) -> PResult<'a, T> {
234     let mut parser = Parser::new(sess, tts, false, Some(name));
235     let result = f(&mut parser)?;
236     if parser.token != token::Eof {
237         parser.unexpected()?;
238     }
239     Ok(result)
240 }
241
242 // NOTE(Centril): The following probably shouldn't be here but it acknowledges the
243 // fact that architecturally, we are using parsing (read on below to understand why).
244
245 pub fn nt_to_tokenstream(
246     nt: &Nonterminal,
247     sess: &ParseSess,
248     synthesize_tokens: CanSynthesizeMissingTokens,
249 ) -> 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.
253     //
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
257     // information.
258     //
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
263     let convert_tokens =
264         |tokens: Option<&LazyTokenStream>| Some(tokens?.create_token_stream().to_tokenstream());
265
266     let tokens = match *nt {
267         Nonterminal::NtItem(ref item) => prepend_attrs(&item.attrs, item.tokens.as_ref()),
268         Nonterminal::NtBlock(ref block) => convert_tokens(block.tokens.as_ref()),
269         Nonterminal::NtStmt(ref stmt) if let ast::StmtKind::Empty = stmt.kind => {
270             let tokens = AttrAnnotatedTokenStream::new(vec![(
271                 tokenstream::AttrAnnotatedTokenTree::Token(Token::new(
272                     TokenKind::Semi,
273                     stmt.span,
274                 )),
275                 Spacing::Alone,
276             )]);
277             prepend_attrs(&stmt.attrs(), Some(&LazyTokenStream::new(tokens)))
278         }
279         Nonterminal::NtStmt(ref stmt) => prepend_attrs(&stmt.attrs(), stmt.tokens()),
280         Nonterminal::NtPat(ref pat) => convert_tokens(pat.tokens.as_ref()),
281         Nonterminal::NtTy(ref ty) => convert_tokens(ty.tokens.as_ref()),
282         Nonterminal::NtIdent(ident, is_raw) => {
283             Some(tokenstream::TokenTree::token(token::Ident(ident.name, is_raw), ident.span).into())
284         }
285         Nonterminal::NtLifetime(ident) => {
286             Some(tokenstream::TokenTree::token(token::Lifetime(ident.name), ident.span).into())
287         }
288         Nonterminal::NtMeta(ref attr) => convert_tokens(attr.tokens.as_ref()),
289         Nonterminal::NtPath(ref path) => convert_tokens(path.tokens.as_ref()),
290         Nonterminal::NtVis(ref vis) => convert_tokens(vis.tokens.as_ref()),
291         Nonterminal::NtTT(ref tt) => Some(tt.clone().into()),
292         Nonterminal::NtExpr(ref expr) | Nonterminal::NtLiteral(ref expr) => {
293             prepend_attrs(&expr.attrs, expr.tokens.as_ref())
294         }
295     };
296
297     if let Some(tokens) = tokens {
298         return tokens;
299     } else if matches!(synthesize_tokens, CanSynthesizeMissingTokens::Yes) {
300         return fake_token_stream(sess, nt);
301     } else {
302         panic!(
303             "Missing tokens for nt {:?} at {:?}: {:?}",
304             nt,
305             nt.span(),
306             pprust::nonterminal_to_string(nt)
307         );
308     }
309 }
310
311 fn prepend_attrs(attrs: &[Attribute], tokens: Option<&LazyTokenStream>) -> Option<TokenStream> {
312     let tokens = tokens?;
313     if attrs.is_empty() {
314         return Some(tokens.create_token_stream().to_tokenstream());
315     }
316     let attr_data = AttributesData { attrs: attrs.to_vec().into(), tokens: tokens.clone() };
317     let wrapped = AttrAnnotatedTokenStream::new(vec![(
318         AttrAnnotatedTokenTree::Attributes(attr_data),
319         Spacing::Alone,
320     )]);
321     Some(wrapped.to_tokenstream())
322 }
323
324 pub fn fake_token_stream(sess: &ParseSess, nt: &Nonterminal) -> TokenStream {
325     let source = pprust::nonterminal_to_string(nt);
326     let filename = FileName::macro_expansion_source_code(&source);
327     parse_stream_from_source_str(filename, source, sess, Some(nt.span()))
328 }
329
330 pub fn fake_token_stream_for_crate(sess: &ParseSess, krate: &ast::Crate) -> TokenStream {
331     let source = pprust::crate_to_string_for_macros(krate);
332     let filename = FileName::macro_expansion_source_code(&source);
333     parse_stream_from_source_str(filename, source, sess, Some(krate.span))
334 }
335
336 pub fn parse_cfg_attr(
337     attr: &Attribute,
338     parse_sess: &ParseSess,
339 ) -> Option<(MetaItem, Vec<(AttrItem, Span)>)> {
340     match attr.get_normal_item().args {
341         ast::MacArgs::Delimited(dspan, delim, ref tts) if !tts.is_empty() => {
342             let msg = "wrong `cfg_attr` delimiters";
343             crate::validate_attr::check_meta_bad_delim(parse_sess, dspan, delim, msg);
344             match parse_in(parse_sess, tts.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) {
345                 Ok(r) => return Some(r),
346                 Err(mut e) => {
347                     e.help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
348                         .note(CFG_ATTR_NOTE_REF)
349                         .emit();
350                 }
351             }
352         }
353         _ => error_malformed_cfg_attr_missing(attr.span, parse_sess),
354     }
355     None
356 }
357
358 const CFG_ATTR_GRAMMAR_HELP: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
359 const CFG_ATTR_NOTE_REF: &str = "for more information, visit \
360     <https://doc.rust-lang.org/reference/conditional-compilation.html\
361     #the-cfg_attr-attribute>";
362
363 fn error_malformed_cfg_attr_missing(span: Span, parse_sess: &ParseSess) {
364     parse_sess
365         .span_diagnostic
366         .struct_span_err(span, "malformed `cfg_attr` attribute input")
367         .span_suggestion(
368             span,
369             "missing condition and attribute",
370             CFG_ATTR_GRAMMAR_HELP.to_string(),
371             Applicability::HasPlaceholders,
372         )
373         .note(CFG_ATTR_NOTE_REF)
374         .emit();
375 }