]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/lib.rs
Rollup merge of #69973 - tspiteri:const-int-conversion-since, r=dtolnay
[rust.git] / src / librustc_parse / lib.rs
1 //! The main parser interface.
2
3 #![feature(bool_to_option)]
4 #![feature(crate_visibility_modifier)]
5 #![feature(bindings_after_at)]
6
7 use rustc_ast::ast;
8 use rustc_ast::token::{self, Nonterminal};
9 use rustc_ast::tokenstream::{self, TokenStream, TokenTree};
10 use rustc_ast_pretty::pprust;
11 use rustc_data_structures::sync::Lrc;
12 use rustc_errors::{Diagnostic, FatalError, Level, PResult};
13 use rustc_session::parse::ParseSess;
14 use rustc_span::{FileName, SourceFile, Span};
15
16 use std::path::{Path, PathBuf};
17 use std::str;
18
19 use log::info;
20
21 pub const MACRO_ARGUMENTS: Option<&'static str> = Some("macro arguments");
22
23 #[macro_use]
24 pub mod parser;
25 use parser::{emit_unclosed_delims, make_unclosed_delims_error, Parser};
26 pub mod lexer;
27 pub mod validate_attr;
28 #[macro_use]
29 pub mod config;
30
31 #[derive(Clone)]
32 pub struct Directory {
33     pub path: PathBuf,
34     pub ownership: DirectoryOwnership,
35 }
36
37 #[derive(Copy, Clone)]
38 pub enum DirectoryOwnership {
39     Owned {
40         // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
41         relative: Option<ast::Ident>,
42     },
43     UnownedViaBlock,
44     UnownedViaMod,
45 }
46
47 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
48 // where <thing> includes crate, expr, item, stmt, tts, and one that
49 // uses a HOF to parse anything, and <source> includes file and
50 // `source_str`.
51
52 /// A variant of 'panictry!' that works on a Vec<Diagnostic> instead of a single DiagnosticBuilder.
53 macro_rules! panictry_buffer {
54     ($handler:expr, $e:expr) => {{
55         use rustc_errors::FatalError;
56         use std::result::Result::{Err, Ok};
57         match $e {
58             Ok(e) => e,
59             Err(errs) => {
60                 for e in errs {
61                     $handler.emit_diagnostic(&e);
62                 }
63                 FatalError.raise()
64             }
65         }
66     }};
67 }
68
69 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
70     let mut parser = new_parser_from_file(sess, input);
71     parser.parse_crate_mod()
72 }
73
74 pub fn parse_crate_attrs_from_file<'a>(
75     input: &Path,
76     sess: &'a ParseSess,
77 ) -> PResult<'a, Vec<ast::Attribute>> {
78     let mut parser = new_parser_from_file(sess, input);
79     parser.parse_inner_attributes()
80 }
81
82 pub fn parse_crate_from_source_str(
83     name: FileName,
84     source: String,
85     sess: &ParseSess,
86 ) -> PResult<'_, ast::Crate> {
87     new_parser_from_source_str(sess, name, source).parse_crate_mod()
88 }
89
90 pub fn parse_crate_attrs_from_source_str(
91     name: FileName,
92     source: String,
93     sess: &ParseSess,
94 ) -> PResult<'_, Vec<ast::Attribute>> {
95     new_parser_from_source_str(sess, name, source).parse_inner_attributes()
96 }
97
98 pub fn parse_stream_from_source_str(
99     name: FileName,
100     source: String,
101     sess: &ParseSess,
102     override_span: Option<Span>,
103 ) -> TokenStream {
104     let (stream, mut errors) =
105         source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span);
106     emit_unclosed_delims(&mut errors, &sess);
107     stream
108 }
109
110 /// Creates a new parser from a source string.
111 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
112     panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
113 }
114
115 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
116 /// token stream.
117 pub fn maybe_new_parser_from_source_str(
118     sess: &ParseSess,
119     name: FileName,
120     source: String,
121 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
122     let mut parser =
123         maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source))?;
124     parser.recurse_into_file_modules = false;
125     Ok(parser)
126 }
127
128 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
129 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
130     source_file_to_parser(sess, file_to_source_file(sess, path, None))
131 }
132
133 /// Creates a new parser, returning buffered diagnostics if the file doesn't exist,
134 /// or from lexing the initial token stream.
135 pub fn maybe_new_parser_from_file<'a>(
136     sess: &'a ParseSess,
137     path: &Path,
138 ) -> Result<Parser<'a>, Vec<Diagnostic>> {
139     let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
140     maybe_source_file_to_parser(sess, file)
141 }
142
143 /// Given a session, a crate config, a path, and a span, add
144 /// the file at the given path to the `source_map`, and returns a parser.
145 /// On an error, uses the given span as the source of the problem.
146 pub fn new_sub_parser_from_file<'a>(
147     sess: &'a ParseSess,
148     path: &Path,
149     directory_ownership: DirectoryOwnership,
150     module_name: Option<String>,
151     sp: Span,
152 ) -> Parser<'a> {
153     let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
154     p.directory.ownership = directory_ownership;
155     p.root_module_name = module_name;
156     p
157 }
158
159 /// Given a `source_file` and config, returns a parser.
160 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
161     panictry_buffer!(&sess.span_diagnostic, maybe_source_file_to_parser(sess, source_file))
162 }
163
164 /// Given a `source_file` and config, return a parser. Returns any buffered errors from lexing the
165 /// initial token stream.
166 fn maybe_source_file_to_parser(
167     sess: &ParseSess,
168     source_file: Lrc<SourceFile>,
169 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
170     let end_pos = source_file.end_pos;
171     let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
172     let mut parser = stream_to_parser(sess, stream, None);
173     parser.unclosed_delims = unclosed_delims;
174     if parser.token == token::Eof {
175         parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt());
176     }
177
178     Ok(parser)
179 }
180
181 // Must preserve old name for now, because `quote!` from the *existing*
182 // compiler expands into it.
183 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
184     stream_to_parser(sess, tts.into_iter().collect(), crate::MACRO_ARGUMENTS)
185 }
186
187 // Base abstractions
188
189 /// Given a session and a path and an optional span (for error reporting),
190 /// add the path to the session's source_map and return the new source_file or
191 /// error when a file can't be read.
192 fn try_file_to_source_file(
193     sess: &ParseSess,
194     path: &Path,
195     spanopt: Option<Span>,
196 ) -> Result<Lrc<SourceFile>, Diagnostic> {
197     sess.source_map().load_file(path).map_err(|e| {
198         let msg = format!("couldn't read {}: {}", path.display(), e);
199         let mut diag = Diagnostic::new(Level::Fatal, &msg);
200         if let Some(sp) = spanopt {
201             diag.set_span(sp);
202         }
203         diag
204     })
205 }
206
207 /// Given a session and a path and an optional span (for error reporting),
208 /// adds the path to the session's `source_map` and returns the new `source_file`.
209 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) -> Lrc<SourceFile> {
210     match try_file_to_source_file(sess, path, spanopt) {
211         Ok(source_file) => source_file,
212         Err(d) => {
213             sess.span_diagnostic.emit_diagnostic(&d);
214             FatalError.raise();
215         }
216     }
217 }
218
219 /// Given a `source_file`, produces a sequence of token trees.
220 pub fn source_file_to_stream(
221     sess: &ParseSess,
222     source_file: Lrc<SourceFile>,
223     override_span: Option<Span>,
224 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
225     panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
226 }
227
228 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
229 /// parsing the token stream.
230 pub fn maybe_file_to_stream(
231     sess: &ParseSess,
232     source_file: Lrc<SourceFile>,
233     override_span: Option<Span>,
234 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
235     let srdr = lexer::StringReader::new(sess, source_file, override_span);
236     let (token_trees, unmatched_braces) = srdr.into_token_trees();
237
238     match token_trees {
239         Ok(stream) => Ok((stream, unmatched_braces)),
240         Err(err) => {
241             let mut buffer = Vec::with_capacity(1);
242             err.buffer(&mut buffer);
243             // Not using `emit_unclosed_delims` to use `db.buffer`
244             for unmatched in unmatched_braces {
245                 if let Some(err) = make_unclosed_delims_error(unmatched, &sess) {
246                     err.buffer(&mut buffer);
247                 }
248             }
249             Err(buffer)
250         }
251     }
252 }
253
254 /// Given a stream and the `ParseSess`, produces a parser.
255 pub fn stream_to_parser<'a>(
256     sess: &'a ParseSess,
257     stream: TokenStream,
258     subparser_name: Option<&'static str>,
259 ) -> Parser<'a> {
260     Parser::new(sess, stream, None, true, false, subparser_name)
261 }
262
263 /// Given a stream, the `ParseSess` and the base directory, produces a parser.
264 ///
265 /// Use this function when you are creating a parser from the token stream
266 /// and also care about the current working directory of the parser (e.g.,
267 /// you are trying to resolve modules defined inside a macro invocation).
268 ///
269 /// # Note
270 ///
271 /// The main usage of this function is outside of rustc, for those who uses
272 /// librustc_ast as a library. Please do not remove this function while refactoring
273 /// just because it is not used in rustc codebase!
274 pub fn stream_to_parser_with_base_dir(
275     sess: &ParseSess,
276     stream: TokenStream,
277     base_dir: Directory,
278 ) -> Parser<'_> {
279     Parser::new(sess, stream, Some(base_dir), true, false, None)
280 }
281
282 /// Runs the given subparser `f` on the tokens of the given `attr`'s item.
283 pub fn parse_in<'a, T>(
284     sess: &'a ParseSess,
285     tts: TokenStream,
286     name: &'static str,
287     mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
288 ) -> PResult<'a, T> {
289     let mut parser = Parser::new(sess, tts, None, false, false, Some(name));
290     let result = f(&mut parser)?;
291     if parser.token != token::Eof {
292         parser.unexpected()?;
293     }
294     Ok(result)
295 }
296
297 // NOTE(Centril): The following probably shouldn't be here but it acknowledges the
298 // fact that architecturally, we are using parsing (read on below to understand why).
299
300 pub fn nt_to_tokenstream(nt: &Nonterminal, sess: &ParseSess, span: Span) -> TokenStream {
301     // A `Nonterminal` is often a parsed AST item. At this point we now
302     // need to convert the parsed AST to an actual token stream, e.g.
303     // un-parse it basically.
304     //
305     // Unfortunately there's not really a great way to do that in a
306     // guaranteed lossless fashion right now. The fallback here is to just
307     // stringify the AST node and reparse it, but this loses all span
308     // information.
309     //
310     // As a result, some AST nodes are annotated with the token stream they
311     // came from. Here we attempt to extract these lossless token streams
312     // before we fall back to the stringification.
313     let tokens = match *nt {
314         Nonterminal::NtItem(ref item) => {
315             prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span)
316         }
317         Nonterminal::NtIdent(ident, is_raw) => {
318             Some(tokenstream::TokenTree::token(token::Ident(ident.name, is_raw), ident.span).into())
319         }
320         Nonterminal::NtLifetime(ident) => {
321             Some(tokenstream::TokenTree::token(token::Lifetime(ident.name), ident.span).into())
322         }
323         Nonterminal::NtTT(ref tt) => Some(tt.clone().into()),
324         _ => None,
325     };
326
327     // FIXME(#43081): Avoid this pretty-print + reparse hack
328     let source = pprust::nonterminal_to_string(nt);
329     let filename = FileName::macro_expansion_source_code(&source);
330     let tokens_for_real = parse_stream_from_source_str(filename, source, sess, Some(span));
331
332     // During early phases of the compiler the AST could get modified
333     // directly (e.g., attributes added or removed) and the internal cache
334     // of tokens my not be invalidated or updated. Consequently if the
335     // "lossless" token stream disagrees with our actual stringification
336     // (which has historically been much more battle-tested) then we go
337     // with the lossy stream anyway (losing span information).
338     //
339     // Note that the comparison isn't `==` here to avoid comparing spans,
340     // but it *also* is a "probable" equality which is a pretty weird
341     // definition. We mostly want to catch actual changes to the AST
342     // like a `#[cfg]` being processed or some weird `macro_rules!`
343     // expansion.
344     //
345     // What we *don't* want to catch is the fact that a user-defined
346     // literal like `0xf` is stringified as `15`, causing the cached token
347     // stream to not be literal `==` token-wise (ignoring spans) to the
348     // token stream we got from stringification.
349     //
350     // Instead the "probably equal" check here is "does each token
351     // recursively have the same discriminant?" We basically don't look at
352     // the token values here and assume that such fine grained token stream
353     // modifications, including adding/removing typically non-semantic
354     // tokens such as extra braces and commas, don't happen.
355     if let Some(tokens) = tokens {
356         if tokens.probably_equal_for_proc_macro(&tokens_for_real) {
357             return tokens;
358         }
359         info!(
360             "cached tokens found, but they're not \"probably equal\", \
361                 going with stringified version"
362         );
363     }
364     return tokens_for_real;
365 }
366
367 fn prepend_attrs(
368     sess: &ParseSess,
369     attrs: &[ast::Attribute],
370     tokens: Option<&tokenstream::TokenStream>,
371     span: rustc_span::Span,
372 ) -> Option<tokenstream::TokenStream> {
373     let tokens = tokens?;
374     if attrs.is_empty() {
375         return Some(tokens.clone());
376     }
377     let mut builder = tokenstream::TokenStreamBuilder::new();
378     for attr in attrs {
379         assert_eq!(
380             attr.style,
381             ast::AttrStyle::Outer,
382             "inner attributes should prevent cached tokens from existing"
383         );
384
385         let source = pprust::attribute_to_string(attr);
386         let macro_filename = FileName::macro_expansion_source_code(&source);
387
388         let item = match attr.kind {
389             ast::AttrKind::Normal(ref item) => item,
390             ast::AttrKind::DocComment(_) => {
391                 let stream = parse_stream_from_source_str(macro_filename, source, sess, Some(span));
392                 builder.push(stream);
393                 continue;
394             }
395         };
396
397         // synthesize # [ $path $tokens ] manually here
398         let mut brackets = tokenstream::TokenStreamBuilder::new();
399
400         // For simple paths, push the identifier directly
401         if item.path.segments.len() == 1 && item.path.segments[0].args.is_none() {
402             let ident = item.path.segments[0].ident;
403             let token = token::Ident(ident.name, ident.as_str().starts_with("r#"));
404             brackets.push(tokenstream::TokenTree::token(token, ident.span));
405
406         // ... and for more complicated paths, fall back to a reparse hack that
407         // should eventually be removed.
408         } else {
409             let stream = parse_stream_from_source_str(macro_filename, source, sess, Some(span));
410             brackets.push(stream);
411         }
412
413         brackets.push(item.args.outer_tokens());
414
415         // The span we list here for `#` and for `[ ... ]` are both wrong in
416         // that it encompasses more than each token, but it hopefully is "good
417         // enough" for now at least.
418         builder.push(tokenstream::TokenTree::token(token::Pound, attr.span));
419         let delim_span = tokenstream::DelimSpan::from_single(attr.span);
420         builder.push(tokenstream::TokenTree::Delimited(
421             delim_span,
422             token::DelimToken::Bracket,
423             brackets.build(),
424         ));
425     }
426     builder.push(tokens.clone());
427     Some(builder.build())
428 }