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