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