1#![allow(rustc::diagnostic_outside_of_impl)]
5#![allow(rustc::untranslatable_diagnostic)]
6#![feature(assert_matches)]
7#![feature(box_patterns)]
8#![feature(debug_closure_helpers)]
9#![feature(default_field_values)]
10#![feature(if_let_guard)]
11#![feature(iter_intersperse)]
12#![recursion_limit = "256"]
13use std::path::{Path, PathBuf};
16use std::str::Utf8Error;
17use std::sync::Arc;
18
19use rustc_ast as ast;
20use rustc_ast::tokenstream::{DelimSpan, TokenStream};
21use rustc_ast::{AttrItem, Attribute, MetaItemInner, token};
22use rustc_ast_pretty::pprust;
23use rustc_errors::{Diag, EmissionGuarantee, FatalError, PResult, pluralize};
24use rustc_session::parse::ParseSess;
25use rustc_span::source_map::SourceMap;
26use rustc_span::{FileName, SourceFile, Span};
27pub use unicode_normalization::UNICODE_VERSION as UNICODE_NORMALIZATION_VERSION;
28
29pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
30
31#[macro_use]
32pub mod parser;
33use parser::Parser;
34use rustc_ast::token::Delimiter;
35
36use crate::lexer::StripTokens;
37
38pub mod lexer;
39
40mod errors;
41
42rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
43
44pub fn unwrap_or_emit_fatal<T>(expr: Result<T, Vec<Diag<'_>>>) -> T {
46 match expr {
47 Ok(expr) => expr,
48 Err(errs) => {
49 for err in errs {
50 err.emit();
51 }
52 FatalError.raise()
53 }
54 }
55}
56
57pub fn new_parser_from_source_str(
62 psess: &ParseSess,
63 name: FileName,
64 source: String,
65 strip_tokens: StripTokens,
66) -> Result<Parser<'_>, Vec<Diag<'_>>> {
67 let source_file = psess.source_map().new_source_file(name, source);
68 new_parser_from_source_file(psess, source_file, strip_tokens)
69}
70
71pub fn new_parser_from_file<'a>(
77 psess: &'a ParseSess,
78 path: &Path,
79 strip_tokens: StripTokens,
80 sp: Option<Span>,
81) -> Result<Parser<'a>, Vec<Diag<'a>>> {
82 let sm = psess.source_map();
83 let source_file = sm.load_file(path).unwrap_or_else(|e| {
84 let msg = format!("couldn't read `{}`: {}", path.display(), e);
85 let mut err = psess.dcx().struct_fatal(msg);
86 if let Ok(contents) = std::fs::read(path)
87 && let Err(utf8err) = String::from_utf8(contents.clone())
88 {
89 utf8_error(
90 sm,
91 &path.display().to_string(),
92 sp,
93 &mut err,
94 utf8err.utf8_error(),
95 &contents,
96 );
97 }
98 if let Some(sp) = sp {
99 err.span(sp);
100 }
101 err.emit();
102 });
103 new_parser_from_source_file(psess, source_file, strip_tokens)
104}
105
106pub fn utf8_error<E: EmissionGuarantee>(
107 sm: &SourceMap,
108 path: &str,
109 sp: Option<Span>,
110 err: &mut Diag<'_, E>,
111 utf8err: Utf8Error,
112 contents: &[u8],
113) {
114 let start = utf8err.valid_up_to();
116 let note = format!("invalid utf-8 at byte `{start}`");
117 let msg = if let Some(len) = utf8err.error_len() {
118 format!(
119 "byte{s} `{bytes}` {are} not valid utf-8",
120 bytes = if len == 1 {
121 format!("{:?}", contents[start])
122 } else {
123 format!("{:?}", &contents[start..start + len])
124 },
125 s = pluralize!(len),
126 are = if len == 1 { "is" } else { "are" },
127 )
128 } else {
129 note.clone()
130 };
131 let contents = String::from_utf8_lossy(contents).to_string();
132 let source = sm.new_source_file(PathBuf::from(path).into(), contents);
133 let span = Span::with_root_ctxt(
134 source.normalized_byte_pos(start as u32),
135 source.normalized_byte_pos(start as u32),
136 );
137 if span.is_dummy() {
138 err.note(note);
139 } else {
140 if sp.is_some() {
141 err.span_note(span, msg);
142 } else {
143 err.span(span);
144 err.span_label(span, msg);
145 }
146 }
147}
148
149fn new_parser_from_source_file(
152 psess: &ParseSess,
153 source_file: Arc<SourceFile>,
154 strip_tokens: StripTokens,
155) -> Result<Parser<'_>, Vec<Diag<'_>>> {
156 let end_pos = source_file.end_position();
157 let stream = source_file_to_stream(psess, source_file, None, strip_tokens)?;
158 let mut parser = Parser::new(psess, stream, None);
159 if parser.token == token::Eof {
160 parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt(), None);
161 }
162 Ok(parser)
163}
164
165pub fn source_str_to_stream(
169 psess: &ParseSess,
170 name: FileName,
171 source: String,
172 override_span: Option<Span>,
173) -> Result<TokenStream, Vec<Diag<'_>>> {
174 let source_file = psess.source_map().new_source_file(name, source);
175 source_file_to_stream(psess, source_file, override_span, StripTokens::Shebang)
180}
181
182fn source_file_to_stream<'psess>(
186 psess: &'psess ParseSess,
187 source_file: Arc<SourceFile>,
188 override_span: Option<Span>,
189 strip_tokens: StripTokens,
190) -> Result<TokenStream, Vec<Diag<'psess>>> {
191 let src = source_file.src.as_ref().unwrap_or_else(|| {
192 psess.dcx().bug(format!(
193 "cannot lex `source_file` without source: {}",
194 psess.source_map().filename_for_diagnostics(&source_file.name)
195 ));
196 });
197
198 lexer::lex_token_trees(psess, src.as_str(), source_file.start_pos, override_span, strip_tokens)
199}
200
201pub fn parse_in<'a, T>(
203 psess: &'a ParseSess,
204 tts: TokenStream,
205 name: &'static str,
206 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
207) -> PResult<'a, T> {
208 let mut parser = Parser::new(psess, tts, Some(name));
209 let result = f(&mut parser)?;
210 if parser.token != token::Eof {
211 parser.unexpected()?;
212 }
213 Ok(result)
214}
215
216pub fn fake_token_stream_for_item(psess: &ParseSess, item: &ast::Item) -> TokenStream {
217 let source = pprust::item_to_string(item);
218 let filename = FileName::macro_expansion_source_code(&source);
219 unwrap_or_emit_fatal(source_str_to_stream(psess, filename, source, Some(item.span)))
220}
221
222pub fn fake_token_stream_for_crate(psess: &ParseSess, krate: &ast::Crate) -> TokenStream {
223 let source = pprust::crate_to_string_for_macros(krate);
224 let filename = FileName::macro_expansion_source_code(&source);
225 unwrap_or_emit_fatal(source_str_to_stream(
226 psess,
227 filename,
228 source,
229 Some(krate.spans.inner_span),
230 ))
231}
232
233pub fn parse_cfg_attr(
234 cfg_attr: &Attribute,
235 psess: &ParseSess,
236) -> Option<(MetaItemInner, Vec<(AttrItem, Span)>)> {
237 const CFG_ATTR_GRAMMAR_HELP: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
238 const CFG_ATTR_NOTE_REF: &str = "for more information, visit \
239 <https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute>";
240
241 match cfg_attr.get_normal_item().args {
242 ast::AttrArgs::Delimited(ast::DelimArgs { dspan, delim, ref tokens })
243 if !tokens.is_empty() =>
244 {
245 check_cfg_attr_bad_delim(psess, dspan, delim);
246 match parse_in(psess, tokens.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) {
247 Ok(r) => return Some(r),
248 Err(e) => {
249 e.with_help(format!("the valid syntax is `{CFG_ATTR_GRAMMAR_HELP}`"))
250 .with_note(CFG_ATTR_NOTE_REF)
251 .emit();
252 }
253 }
254 }
255 _ => {
256 psess.dcx().emit_err(errors::MalformedCfgAttr {
257 span: cfg_attr.span,
258 sugg: CFG_ATTR_GRAMMAR_HELP,
259 });
260 }
261 }
262 None
263}
264
265fn check_cfg_attr_bad_delim(psess: &ParseSess, span: DelimSpan, delim: Delimiter) {
266 if let Delimiter::Parenthesis = delim {
267 return;
268 }
269 psess.dcx().emit_err(errors::CfgAttrBadDelim {
270 span: span.entire(),
271 sugg: errors::MetaBadDelimSugg { open: span.open, close: span.close },
272 });
273}