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