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