neo_devpack_solidity/frontend/frontend_guarded_parse.rs
1/// Stack budget for the dedicated parsing thread used by
2/// [`parse_solidity_guarded`].
3///
4/// `solang_parser`'s recursive-descent grammar recurses once per nesting
5/// level of the input, so a hostile (or generated) source such as
6/// `return 1 +1 +1 ...` a few thousand terms deep overflows the default
7/// ~8 MiB main-thread stack and aborts the whole process (SIGABRT) before
8/// any error can be reported. 256 MiB raises the depth ceiling by ~32x —
9/// far beyond anything a legitimate contract reaches — while staying a
10/// hard bound (the memory is only reserved, not committed, until used).
11const PARSE_THREAD_STACK_BYTES: usize = 256 * 1024 * 1024;
12
13/// Run `solang_parser::parse(source, 0)` on a worker thread with a large
14/// bounded stack, joining failures back as ordinary parse diagnostics.
15///
16/// The compiler's own recursive AST walks are already `stacker`-guarded
17/// (see `src/ir/expressions/dispatch/entry.rs`), but the parser entry point
18/// runs *before* those guards and `solang_parser` recurses on its own
19/// internal stack. Every call site that parses Solidity source MUST go
20/// through this helper — CLI single-file (`extract_imports`), standard-json
21/// import resolution, and `parse_source` — so the nesting-depth ceiling
22/// stays consistent across entry points.
23///
24/// A parser panic (rather than a returned `Err`) is converted into a normal
25/// error diagnostic instead of unwinding into — or aborting — the caller.
26pub fn parse_solidity_guarded(
27 source: &str,
28) -> Result<(solang_parser::pt::SourceUnit, Vec<Comment>), Vec<Diagnostic>> {
29 std::thread::scope(|scope| {
30 let worker = std::thread::Builder::new()
31 .name("solang-parse".to_string())
32 .stack_size(PARSE_THREAD_STACK_BYTES)
33 .spawn_scoped(scope, || parse(source, 0));
34
35 match worker {
36 Ok(handle) => handle.join().unwrap_or_else(|panic| {
37 let detail = panic
38 .downcast_ref::<&str>()
39 .map(|s| (*s).to_string())
40 .or_else(|| panic.downcast_ref::<String>().cloned())
41 .unwrap_or_else(|| "unknown parser panic".to_string());
42 Err(vec![Diagnostic::parser_error(
43 Loc::File(0, 0, 0),
44 format!("internal parser error: {detail}"),
45 )])
46 }),
47 // Spawning a thread only fails under extreme resource
48 // exhaustion; fall back to parsing on the current thread
49 // (the pre-helper behavior) rather than refusing to compile.
50 Err(_) => parse(source, 0),
51 }
52 })
53}