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