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