Skip to main content

rustc_parse/
lib.rs

1//! The main parser interface.
2
3// tidy-alphabetical-start
4#![cfg_attr(test, feature(iter_order_by))]
5#![feature(default_field_values)]
6#![feature(deref_patterns)]
7#![feature(iter_intersperse)]
8#![recursion_limit = "256"]
9// tidy-alphabetical-end
10
11use std::path::{Path, PathBuf};
12use std::str::Utf8Error;
13use std::sync::Arc;
14
15use rustc_ast as ast;
16use rustc_ast::token;
17use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree};
18use rustc_ast_pretty::pprust;
19use rustc_errors::{Diag, FatalError, PResult, pluralize};
20use rustc_session::parse::ParseSess;
21use rustc_span::edit_distance::find_best_match_for_name;
22use rustc_span::source_map::SourceMap;
23use rustc_span::{FileName, SourceFile, Span, Symbol};
24
25pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
26
27#[macro_use]
28pub mod parser;
29use parser::Parser;
30
31use crate::lexer::StripTokens;
32
33pub mod lexer;
34
35mod diagnostics;
36
37// Unwrap the result if `Ok`, otherwise emit the diagnostics and abort.
38pub fn unwrap_or_emit_fatal<T>(expr: Result<T, Vec<Diag<'_>>>) -> T {
39    match expr {
40        Ok(expr) => expr,
41        Err(errs) => {
42            for err in errs {
43                err.emit();
44            }
45            FatalError.raise()
46        }
47    }
48}
49
50/// Creates a new parser from a source string.
51///
52/// On failure, the errors must be consumed via `unwrap_or_emit_fatal`, `emit`, `cancel`,
53/// etc., otherwise a panic will occur when they are dropped.
54pub fn new_parser_from_source_str(
55    psess: &ParseSess,
56    name: FileName,
57    source: String,
58    strip_tokens: StripTokens,
59) -> Result<Parser<'_>, Vec<Diag<'_>>> {
60    let source_file = psess.source_map().new_source_file(name, source);
61    new_parser_from_source_file(psess, source_file, strip_tokens)
62}
63
64/// Creates a new parser from a filename. On failure, the errors must be consumed via
65/// `unwrap_or_emit_fatal`, `emit`, `cancel`, etc., otherwise a panic will occur when they are
66/// dropped.
67///
68/// If a span is given, that is used on an error as the source of the problem.
69///
70/// Error messages are tailored to the specific error kind.
71pub fn new_parser_from_file<'a>(
72    psess: &'a ParseSess,
73    path: &Path,
74    strip_tokens: StripTokens,
75    sp: Option<Span>,
76) -> Result<Parser<'a>, Vec<Diag<'a>>> {
77    let sm = psess.source_map();
78    let source_file = sm.load_file(path).unwrap_or_else(|e| {
79        use std::io::ErrorKind;
80
81        let msg = match e.kind() {
82            ErrorKind::NotFound => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("couldn\'t find file `{0}`",
                path.display()))
    })format!("couldn't find file `{}`", path.display()),
83            ErrorKind::PermissionDenied => {
84                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("permission denied when opening file `{0}`",
                path.display()))
    })format!("permission denied when opening file `{}`", path.display())
85            }
86            ErrorKind::IsADirectory => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is a directory",
                path.display()))
    })format!("`{}` is a directory", path.display()),
87            _ => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("couldn\'t read `{0}`: {1}",
                path.display(), e))
    })format!("couldn't read `{}`: {}", path.display(), e),
88        };
89
90        let mut err = psess.dcx().struct_fatal(msg);
91
92        if e.kind() == ErrorKind::NotFound {
93            if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
94                let parent = match path.parent() {
95                    Some(p) if !p.as_os_str().is_empty() => p,
96                    _ => Path::new("."),
97                };
98                if let Ok(entries) = std::fs::read_dir(parent) {
99                    let candidates: Vec<Symbol> = entries
100                        .flatten()
101                        .filter_map(|entry| entry.file_name().to_str().map(Symbol::intern))
102                        .collect();
103                    let lookup = Symbol::intern(file_name);
104                    if let Some(suggestion) = find_best_match_for_name(&candidates, lookup, None) {
105                        let suggested_path = if parent == Path::new(".") {
106                            suggestion.as_str().to_string()
107                        } else {
108                            parent.join(suggestion.as_str()).display().to_string()
109                        };
110                        err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might have meant to open `{0}`",
                suggested_path))
    })format!("you might have meant to open `{}`", suggested_path));
111                    }
112                }
113            }
114        }
115        if let Ok(contents) = std::fs::read(path)
116            && let Err(utf8err) = std::str::from_utf8(&contents)
117        {
118            utf8_error(sm, &path.display().to_string(), sp, &mut err, utf8err, &contents);
119        }
120        if let Some(sp) = sp {
121            err.span(sp);
122        }
123        err.emit_fatal()
124    });
125    new_parser_from_source_file(psess, source_file, strip_tokens)
126}
127
128pub fn utf8_error(
129    sm: &SourceMap,
130    path: &str,
131    sp: Option<Span>,
132    err: &mut Diag<'_>,
133    utf8err: Utf8Error,
134    contents: &[u8],
135) {
136    // The file exists, but it wasn't valid UTF-8.
137    let start = utf8err.valid_up_to();
138    let note = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("invalid utf-8 at byte `{0}`",
                start))
    })format!("invalid utf-8 at byte `{start}`");
139    let msg = if let Some(len) = utf8err.error_len() {
140        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("byte{1} `{0}` {2} not valid utf-8",
                if len == 1 {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0:?}", contents[start]))
                        })
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0:?}",
                                    &contents[start..start + len]))
                        })
                }, if len == 1 { "" } else { "s" },
                if len == 1 { "is" } else { "are" }))
    })format!(
141            "byte{s} `{bytes}` {are} not valid utf-8",
142            bytes = if len == 1 {
143                format!("{:?}", contents[start])
144            } else {
145                format!("{:?}", &contents[start..start + len])
146            },
147            s = pluralize!(len),
148            are = if len == 1 { "is" } else { "are" },
149        )
150    } else {
151        note.clone()
152    };
153    let contents = String::from_utf8_lossy(contents).to_string();
154
155    // We only emit this error for files in the current session
156    // so the working directory can only be the current working directory
157    let filename = FileName::Real(
158        sm.path_mapping().to_real_filename(sm.working_dir(), PathBuf::from(path).as_path()),
159    );
160    let source = sm.new_source_file(filename, contents);
161
162    // Avoid out-of-bounds span from lossy UTF-8 conversion.
163    if start as u32 > source.normalized_source_len.0 {
164        err.note(note);
165        return;
166    }
167
168    let span = Span::with_root_ctxt(
169        source.normalized_byte_pos(start as u32),
170        source.normalized_byte_pos(start as u32),
171    );
172    if span.is_dummy() {
173        err.note(note);
174    } else {
175        if sp.is_some() {
176            err.span_note(span, msg);
177        } else {
178            err.span(span);
179            err.span_label(span, msg);
180        }
181    }
182}
183
184/// Given a session and a `source_file`, return a parser. Returns any buffered errors from lexing
185/// the initial token stream.
186fn new_parser_from_source_file(
187    psess: &ParseSess,
188    source_file: Arc<SourceFile>,
189    strip_tokens: StripTokens,
190) -> Result<Parser<'_>, Vec<Diag<'_>>> {
191    let end_pos = source_file.end_position();
192    let stream = source_file_to_stream(psess, source_file, None, strip_tokens)?;
193    let mut parser = Parser::new(psess, stream, None);
194    if parser.token == token::Eof {
195        parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt(), None);
196    }
197    Ok(parser)
198}
199
200/// Given a source string, produces a sequence of token trees.
201///
202/// NOTE: This only strips shebangs, not frontmatter!
203pub fn source_str_to_stream(
204    psess: &ParseSess,
205    name: FileName,
206    source: String,
207    override_span: Option<Span>,
208) -> Result<TokenStream, Vec<Diag<'_>>> {
209    let source_file = psess.source_map().new_source_file(name, source);
210    // FIXME(frontmatter): Consider stripping frontmatter in a future edition. We can't strip them
211    // in the current edition since that would be breaking.
212    // See also <https://github.com/rust-lang/rust/issues/145520>.
213    // Alternatively, stop stripping shebangs here, too, if T-lang and crater approve.
214    source_file_to_stream(psess, source_file, override_span, StripTokens::Shebang)
215}
216
217/// Given a source file, produces a sequence of token trees.
218///
219/// Returns any buffered errors from parsing the token stream.
220fn source_file_to_stream<'psess>(
221    psess: &'psess ParseSess,
222    source_file: Arc<SourceFile>,
223    override_span: Option<Span>,
224    strip_tokens: StripTokens,
225) -> Result<TokenStream, Vec<Diag<'psess>>> {
226    let src = source_file.src.as_ref().unwrap_or_else(|| {
227        psess.dcx().bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot lex `source_file` without source: {0}",
                psess.source_map().filename_for_diagnostics(&source_file.name)))
    })format!(
228            "cannot lex `source_file` without source: {}",
229            psess.source_map().filename_for_diagnostics(&source_file.name)
230        ));
231    });
232
233    lexer::lex_token_trees(psess, src.as_str(), source_file.start_pos, override_span, strip_tokens)
234}
235
236/// Runs the given subparser `f` on the tokens of the given `attr`'s item.
237pub fn parse_in<'a, T>(
238    psess: &'a ParseSess,
239    tts: TokenStream,
240    name: &'static str,
241    mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
242) -> PResult<'a, T> {
243    let mut parser = Parser::new(psess, tts, Some(name));
244    let result = f(&mut parser)?;
245    if parser.token != token::Eof {
246        parser.unexpected()?;
247    }
248    Ok(result)
249}
250
251pub fn fake_token_stream_for_item(
252    psess: &ParseSess,
253    item: &ast::Item,
254    attr_to_exclude: Option<&ast::Attribute>,
255) -> TokenStream {
256    if let Some(tokens) = fake_token_stream_for_file_mod(psess, item, attr_to_exclude) {
257        return tokens;
258    }
259
260    let source = pprust::item_to_string(item);
261    let filename = FileName::macro_expansion_source_code(&source);
262    unwrap_or_emit_fatal(source_str_to_stream(psess, filename, source, Some(item.span)))
263}
264
265fn fake_token_stream_for_file_mod(
266    psess: &ParseSess,
267    item: &ast::Item,
268    attr_to_exclude: Option<&ast::Attribute>,
269) -> Option<TokenStream> {
270    let ast::ItemKind::Mod(_, _, ast::ModKind::Loaded(_, ast::Inline::No { .. }, spans)) =
271        &item.kind
272    else {
273        return None;
274    };
275
276    let attr = attr_to_exclude.expect("file modules must have an attribute to exclude");
277    {
    match (&attr.style, &ast::AttrStyle::Inner) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(attr.style, ast::AttrStyle::Inner);
278
279    let mut body_tts = Vec::new();
280    body_tts.extend(lex_token_trees_for_span(psess, spans.inner_span.until(attr.span))?);
281    body_tts.extend(lex_token_trees_for_span(
282        psess,
283        attr.span.between(spans.inner_span.shrink_to_hi()),
284    )?);
285
286    let mut wrapper_tts = Vec::new();
287    for attr in item.attrs.iter().filter(|attr| attr.style == ast::AttrStyle::Outer) {
288        attr.append_token_trees_to(&mut wrapper_tts);
289    }
290    wrapper_tts.extend(lex_token_trees_for_span(psess, item.span)?);
291    let Some(TokenTree::Token(semi, _)) = wrapper_tts.pop() else {
292        return None;
293    };
294    if semi.kind != token::Semi {
295        return None;
296    }
297    wrapper_tts.push(TokenTree::Delimited(
298        DelimSpan::from_single(semi.span),
299        DelimSpacing::new(Spacing::Alone, Spacing::Alone),
300        token::Delimiter::Brace,
301        TokenStream::new(body_tts),
302    ));
303
304    Some(TokenStream::new(wrapper_tts))
305}
306
307fn lex_token_trees_for_span(
308    psess: &ParseSess,
309    span: Span,
310) -> Option<impl Iterator<Item = TokenTree>> {
311    let src = psess.source_map().span_to_snippet(span).ok()?;
312    let stream = match lexer::lex_token_trees(psess, &src, span.lo(), None, StripTokens::Nothing) {
313        Ok(stream) => stream,
314        Err(errs) => {
315            errs.into_iter().for_each(|err| err.cancel());
316            return None;
317        }
318    };
319    Some((0..).map_while(move |index| stream.get(index).cloned()))
320}
321
322pub fn fake_token_stream_for_foreign_item(
323    psess: &ParseSess,
324    item: &ast::ForeignItem,
325) -> TokenStream {
326    let source = pprust::foreign_item_to_string(item);
327    let filename = FileName::macro_expansion_source_code(&source);
328    unwrap_or_emit_fatal(source_str_to_stream(psess, filename, source, Some(item.span)))
329}
330
331pub fn fake_token_stream_for_crate(psess: &ParseSess, krate: &ast::Crate) -> TokenStream {
332    let source = pprust::crate_to_string_for_macros(krate);
333    let filename = FileName::macro_expansion_source_code(&source);
334    unwrap_or_emit_fatal(source_str_to_stream(
335        psess,
336        filename,
337        source,
338        Some(krate.spans.inner_span),
339    ))
340}