1use crate::Diagnostic;
17use proc_macro2::{Span, TokenStream};
18use quote::quote;
19use rustpython_compiler_core::{Mode, bytecode::CodeObject, frozen};
20use std::{
21 collections::HashMap,
22 fs,
23 path::{Path, PathBuf},
24};
25use syn::{
26 self, LitByteStr, LitStr, Macro,
27 parse::{ParseStream, Parser, Result as ParseResult},
28 spanned::Spanned,
29};
30
31enum CompilationSourceKind {
32 File { base: PathBuf, rel_path: PathBuf },
34 SourceCode(String),
36 Dir { base: PathBuf, rel_path: PathBuf },
38}
39
40struct CompiledModule {
41 code: CodeObject,
42 package: bool,
43}
44
45struct CompilationSource {
46 kind: CompilationSourceKind,
47 span: (Span, Span),
48}
49
50fn read_source_file(path: &Path) -> std::io::Result<String> {
53 let mut source = fs::read_to_string(path)?;
54 if source.starts_with('\u{feff}') {
55 source.drain(..'\u{feff}'.len_utf8());
56 }
57 Ok(source)
58}
59
60pub trait Compiler {
61 fn compile(
62 &self,
63 source: &str,
64 mode: Mode,
65 module_name: &str,
66 ) -> Result<CodeObject, Box<dyn core::error::Error>>;
67}
68
69impl CompilationSource {
70 fn compile_string<D: core::fmt::Display, F: FnOnce() -> D>(
71 &self,
72 source: &str,
73 mode: Mode,
74 module_name: &str,
75 compiler: &dyn Compiler,
76 origin: F,
77 ) -> Result<CodeObject, Diagnostic> {
78 compiler.compile(source, mode, module_name).map_err(|err| {
79 Diagnostic::spans_error(
80 self.span,
81 format!("Python compile error from {}: {}", origin(), err),
82 )
83 })
84 }
85
86 fn compile(
87 &self,
88 mode: Mode,
89 module_name: &str,
90 compiler: &dyn Compiler,
91 ) -> Result<HashMap<String, CompiledModule>, Diagnostic> {
92 match &self.kind {
93 CompilationSourceKind::Dir { base, rel_path } => {
94 self.compile_dir(base, &base.join(rel_path), "", mode, compiler)
95 }
96 _ => Ok(core::iter::once((
97 module_name.to_string(),
98 CompiledModule {
99 code: self.compile_single(mode, module_name, compiler)?,
100 package: false,
101 },
102 ))
103 .collect()),
104 }
105 }
106
107 fn compile_single(
108 &self,
109 mode: Mode,
110 module_name: &str,
111 compiler: &dyn Compiler,
112 ) -> Result<CodeObject, Diagnostic> {
113 match &self.kind {
114 CompilationSourceKind::File { base, rel_path } => {
115 let path = base.join(rel_path);
116 let source = read_source_file(&path).map_err(|err| {
117 Diagnostic::spans_error(
118 self.span,
119 format!("Error reading file {path:?}: {err}"),
120 )
121 })?;
122 self.compile_string(&source, mode, module_name, compiler, || rel_path.display())
123 }
124 CompilationSourceKind::SourceCode(code) => self.compile_string(
125 &textwrap::dedent(code),
126 mode,
127 module_name,
128 compiler,
129 || "string literal",
130 ),
131 CompilationSourceKind::Dir { .. } => {
132 unreachable!("Can't use compile_single with directory source")
133 }
134 }
135 }
136
137 fn compile_dir(
138 &self,
139 base: &Path,
140 path: &Path,
141 parent: &str,
142 mode: Mode,
143 compiler: &dyn Compiler,
144 ) -> Result<HashMap<String, CompiledModule>, Diagnostic> {
145 let mut code_map = HashMap::new();
146 let paths = fs::read_dir(path)
147 .or_else(|e| {
148 if cfg!(windows)
149 && let Ok(real_path) = fs::read_to_string(path.canonicalize().unwrap())
150 {
151 return fs::read_dir(real_path.trim());
152 }
153 Err(e)
154 })
155 .map_err(|err| {
156 Diagnostic::spans_error(self.span, format!("Error listing dir {path:?}: {err}"))
157 })?;
158 for path in paths {
159 let path = path.map_err(|err| {
160 Diagnostic::spans_error(self.span, format!("Failed to list file: {err}"))
161 })?;
162 let path = path.path();
163 let file_name = path.file_name().unwrap().to_str().ok_or_else(|| {
164 Diagnostic::spans_error(self.span, format!("Invalid UTF-8 in file name {path:?}"))
165 })?;
166 if path.is_dir() {
167 let nparent = if parent.is_empty() {
168 file_name.to_string()
169 } else {
170 format!("{parent}.{file_name}")
171 };
172 code_map.extend(self.compile_dir(base, &path, &nparent, mode, compiler)?);
173 } else if file_name.ends_with(".py") {
174 let stem = path.file_stem().unwrap().to_str().unwrap();
175 let is_init = stem == "__init__";
176 let module_name = if is_init {
177 parent
178 } else if parent.is_empty() {
179 stem
180 } else {
181 &format!("{parent}.{stem}")
182 };
183
184 let compile_path = |src_path: &Path| {
185 let source = read_source_file(src_path).map_err(|err| {
186 Diagnostic::spans_error(
187 self.span,
188 format!("Error reading file {path:?}: {err}"),
189 )
190 })?;
191 self.compile_string(&source, mode, module_name, compiler, || {
192 path.strip_prefix(base).ok().unwrap_or(&path).display()
193 })
194 };
195 let code = compile_path(&path).or_else(|e| {
196 if cfg!(windows)
197 && let Ok(real_path) = fs::read_to_string(path.canonicalize().unwrap())
198 {
199 let joined = path.parent().unwrap().join(real_path.trim());
200 if joined.exists() {
201 return compile_path(&joined);
202 }
203 return Err(e);
204 }
205 Err(e)
206 });
207
208 let code = match code {
209 Ok(code) => code,
210 Err(_)
211 if stem.starts_with("badsyntax_")
212 | parent.ends_with(".encoded_modules") =>
213 {
214 continue;
216 }
217 Err(e) => return Err(e),
218 };
219
220 code_map.insert(
221 module_name.to_string(),
222 CompiledModule {
223 code,
224 package: is_init,
225 },
226 );
227 }
228 }
229 Ok(code_map)
230 }
231}
232
233impl PyCompileArgs {
234 fn parse(input: TokenStream, allow_dir: bool) -> Result<Self, Diagnostic> {
235 let mut module_name = None;
236 let mut mode = None;
237 let mut source: Option<CompilationSource> = None;
238 let mut crate_name = None;
239
240 fn assert_source_empty(source: Option<&CompilationSource>) -> Result<(), syn::Error> {
241 if let Some(source) = source {
242 Err(syn::Error::new(
243 source.span.0,
244 "Cannot have more than one source",
245 ))
246 } else {
247 Ok(())
248 }
249 }
250
251 syn::meta::parser(|meta| {
252 let ident = meta
253 .path
254 .get_ident()
255 .ok_or_else(|| meta.error("unknown arg"))?;
256 let check_str = || meta.value()?.call(parse_str);
257 let str_path = || {
258 let s = check_str()?;
259 let mut base_path = s
260 .span()
261 .unwrap()
262 .local_file()
263 .ok_or_else(|| err_span!(s, "filepath literal has no span information"))?;
264 base_path.pop();
265 Ok::<_, syn::Error>((base_path, PathBuf::from(s.value())))
266 };
267 if ident == "mode" {
268 let s = check_str()?;
269 match s.value().parse() {
270 Ok(mode_val) => mode = Some(mode_val),
271 Err(e) => bail_span!(s, "{}", e),
272 }
273 } else if ident == "module_name" {
274 module_name = Some(check_str()?.value())
275 } else if ident == "source" {
276 assert_source_empty(source.as_ref())?;
277 let code = check_str()?.value();
278 source = Some(CompilationSource {
279 kind: CompilationSourceKind::SourceCode(code),
280 span: (ident.span(), meta.input.cursor().span()),
281 });
282 } else if ident == "file" {
283 assert_source_empty(source.as_ref())?;
284 let (base, rel_path) = str_path()?;
285 source = Some(CompilationSource {
286 kind: CompilationSourceKind::File { base, rel_path },
287 span: (ident.span(), meta.input.cursor().span()),
288 });
289 } else if ident == "dir" {
290 if !allow_dir {
291 bail_span!(ident, "py_compile doesn't accept dir")
292 }
293
294 assert_source_empty(source.as_ref())?;
295 let (base, rel_path) = str_path()?;
296 source = Some(CompilationSource {
297 kind: CompilationSourceKind::Dir { base, rel_path },
298 span: (ident.span(), meta.input.cursor().span()),
299 });
300 } else if ident == "crate_name" {
301 let name = check_str()?.parse()?;
302 crate_name = Some(name);
303 } else {
304 return Err(meta.error("unknown attr"));
305 }
306 Ok(())
307 })
308 .parse2(input)?;
309
310 let source = source.ok_or_else(|| {
311 syn::Error::new(
312 Span::call_site(),
313 "Must have either file or source in py_compile!()/py_freeze!()",
314 )
315 })?;
316
317 Ok(Self {
318 source,
319 mode: mode.unwrap_or(Mode::Exec),
320 module_name: module_name.unwrap_or_else(|| "frozen".to_owned()),
321 crate_name: crate_name.unwrap_or_else(|| syn::parse_quote!(::rustpython_vm)),
322 })
323 }
324}
325
326fn parse_str(input: ParseStream<'_>) -> ParseResult<LitStr> {
327 let span = input.span();
328 if input.peek(LitStr) {
329 input.parse()
330 } else if let Ok(mac) = input.parse::<Macro>() {
331 Ok(LitStr::new(&mac.tokens.to_string(), mac.span()))
332 } else {
333 Err(syn::Error::new(span, "Expected string or stringify macro"))
334 }
335}
336
337struct PyCompileArgs {
338 source: CompilationSource,
339 mode: Mode,
340 module_name: String,
341 crate_name: syn::Path,
342}
343
344pub(crate) fn impl_py_compile(
345 input: TokenStream,
346 compiler: &dyn Compiler,
347) -> Result<TokenStream, Diagnostic> {
348 let args = PyCompileArgs::parse(input, false)?;
349
350 let crate_name = args.crate_name;
351 let code = args
352 .source
353 .compile_single(args.mode, &args.module_name, compiler)?;
354
355 let frozen = frozen::FrozenCodeObject::encode(&code);
356 let bytes = LitByteStr::new(&frozen.bytes, Span::call_site());
357
358 let output = quote! {
359 #crate_name::frozen::FrozenCodeObject { bytes: &#bytes[..] }
360 };
361
362 Ok(output)
363}
364
365pub(crate) fn impl_py_freeze(
366 input: TokenStream,
367 compiler: &dyn Compiler,
368) -> Result<TokenStream, Diagnostic> {
369 let args = PyCompileArgs::parse(input, true)?;
370
371 let crate_name = args.crate_name;
372 let code_map = args
373 .source
374 .compile(args.mode, &args.module_name, compiler)?;
375
376 let data = frozen::FrozenLib::encode(code_map.iter().map(|(k, v)| {
377 let v = frozen::FrozenModule {
378 code: frozen::FrozenCodeObject::encode(&v.code),
379 package: v.package,
380 };
381 (&**k, v)
382 }));
383 let bytes = LitByteStr::new(&data.bytes, Span::call_site());
384
385 let output = quote! {
386 #crate_name::frozen::FrozenLib::from_ref(#bytes)
387 };
388
389 Ok(output)
390}