Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/perry-hir/src/lower/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ impl LoweringContext {
is_external_module: false,
optional_require_try_depth: 0,
fn_ctor_env: super::fn_ctor_env::FnCtorEnv::default(),
expr_lower_depth: 0,
}
}

Expand Down
40 changes: 40 additions & 0 deletions crates/perry-hir/src/lower/lower_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,30 @@

use anyhow::{anyhow, Result};
use perry_types::{LocalId, Type};
use swc_common::Spanned;
use swc_ecma_ast as ast;

use super::*;
use crate::ir::*;
use crate::lower_types::extract_ts_type_with_ctx;

/// Maximum `lower_expr` recursion depth before lowering bails with a
/// diagnostic instead of overflowing the native stack (#5259).
///
/// Expression lowering is recursive: a left-nested `a+b+c+…` chain, an
/// `o.a.a.…a` member chain, or an `a||a||…` logical chain each recurses once
/// per operator/segment. Bundler/minifier output occasionally emits chains
/// thousands of nodes deep; left unguarded these overflow the stack and
/// SIGABRT (exit 134) with no diagnostic at all. The compiler runs its
/// collect/lower walk on a 128 MB stack (`perry-main`, see `crates/perry/
/// src/main.rs`), and the heaviest shape (member chains) consumes on the
/// order of ~16 KB of stack per level, so this ceiling keeps worst-case
/// lowering depth well under ~32 MB — far below the stack limit — while still
/// sitting far above anything hand-written code or a reasonable build emits.
/// The only inputs it rejects are the degenerate ones that would otherwise
/// crash, and they now get a clean "nested too deeply" diagnostic instead.
pub(crate) const MAX_EXPR_LOWER_DEPTH: u32 = 2000;

fn class_computed_member_registration_expr(class_name: &str, member: &ClassComputedMember) -> Expr {
match member.kind {
ClassComputedMemberKind::Method => Expr::RegisterClassComputedMethod {
Expand Down Expand Up @@ -473,6 +491,28 @@ pub(crate) fn native_module_binding_value(ctx: &LoweringContext, name: &str) ->
}

pub(crate) fn lower_expr(ctx: &mut LoweringContext, expr: &ast::Expr) -> Result<Expr> {
// #5259: guard the recursive descent. Without this, a pathologically
// nested expression (`1+1+…`, `o.a.a.…`, `a||a||…`) overflows the native
// stack and SIGABRTs with no diagnostic. The depth counter turns that into
// a clean "nested too deeply" error. It is decremented on every exit path,
// including the error returns inside `lower_expr_impl`, so a recoverable
// lowering error elsewhere doesn't leave the depth permanently inflated.
ctx.expr_lower_depth += 1;
if ctx.expr_lower_depth > MAX_EXPR_LOWER_DEPTH {
ctx.expr_lower_depth -= 1;
crate::lower_bail!(
expr.span(),
"expression nested too deeply (exceeded {} levels); split the \
chain across statements or intermediate variables",
MAX_EXPR_LOWER_DEPTH
);
}
let result = lower_expr_impl(ctx, expr);
ctx.expr_lower_depth -= 1;
result
}

fn lower_expr_impl(ctx: &mut LoweringContext, expr: &ast::Expr) -> Result<Expr> {
match expr {
ast::Expr::Lit(lit) => lower_lit(lit),
ast::Expr::Ident(ident) => {
Expand Down
6 changes: 6 additions & 0 deletions crates/perry-hir/src/lower/lowering_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -609,4 +609,10 @@ pub struct LoweringContext {
/// object literals, counters). Built once per module in
/// `lower_module_full`; consumed by `const_fold_fn`.
pub(crate) fn_ctor_env: super::fn_ctor_env::FnCtorEnv,
/// Current recursion depth of `lower_expr` (#5259). Incremented on entry,
/// decremented on exit. Once it exceeds `MAX_EXPR_LOWER_DEPTH`, lowering
/// bails with a clean "nested too deeply" diagnostic instead of letting a
/// pathologically-nested expression chain (bundler/minifier output like
/// `1+1+…+1` or `o.a.a.…a`) overflow the native stack and SIGABRT.
pub(crate) expr_lower_depth: u32,
}
70 changes: 70 additions & 0 deletions crates/perry-hir/src/lower/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,3 +257,73 @@ fn test_lower_namespace_var_lookup() {
assert_eq!(ctx.lookup_namespace_var("Utils", "missing"), None);
assert_eq!(ctx.lookup_namespace_var("Other", "helper"), None);
}

/// Run `f` on a thread with the same large (128 MB) stack the real compiler
/// uses for its collect/lower walk (`perry-main`, see `crates/perry/src/
/// main.rs`). The default cargo-test harness thread is only ~2 MB, which is
/// far too small to parse or lower the multi-thousand-node chains these
/// `#5259` tests build — without this, parsing/lowering them would overflow
/// the *test* stack before the depth guard ever fires.
fn run_with_large_stack<F: FnOnce() + Send + 'static>(f: F) {
std::thread::Builder::new()
.stack_size(128 * 1024 * 1024)
.spawn(f)
.expect("spawn large-stack thread")
.join()
.expect("test body panicked");
}

/// #5259: deeply-nested expression chains must surface a diagnostic instead
/// of overflowing the native stack and SIGABRT-ing the whole process. Each
/// shape (binary `1+1+…`, member `o.a.a.…`, logical `a||a||…`) recurses once
/// per node in `lower_expr`; past `MAX_EXPR_LOWER_DEPTH` lowering bails with a
/// "nested too deeply" error rather than recursing further.
fn assert_too_deep(source: String) {
run_with_large_stack(move || {
let module =
perry_parser::parse_typescript(&source, "deep.ts").expect("source should parse fine");
let err = super::lower_module(&module, "deep", "deep.ts")
.expect_err("deeply-nested expression must be rejected, not lowered");
let msg = format!("{err}");
assert!(
msg.contains("nested too deeply"),
"expected a depth diagnostic, got: {msg}"
);
});
}

#[test]
fn test_lower_rejects_deep_binary_chain() {
let n = (super::lower_expr::MAX_EXPR_LOWER_DEPTH as usize) * 3;
let chain: Vec<&str> = vec!["1"; n];
assert_too_deep(format!("var x = {};\n", chain.join("+")));
}

#[test]
fn test_lower_rejects_deep_member_chain() {
let n = (super::lower_expr::MAX_EXPR_LOWER_DEPTH as usize) * 3;
assert_too_deep(format!("var o = {{}};\nvar x = o{};\n", ".a".repeat(n)));
}

#[test]
fn test_lower_rejects_deep_logical_chain() {
let n = (super::lower_expr::MAX_EXPR_LOWER_DEPTH as usize) * 3;
let chain: Vec<&str> = vec!["a"; n];
assert_too_deep(format!("var a = 0;\nvar x = {};\n", chain.join("||")));
}

/// A chain comfortably under the ceiling still lowers cleanly — the guard
/// must not reject ordinary (if large) expressions.
#[test]
fn test_lower_accepts_chain_under_limit() {
run_with_large_stack(|| {
let n = (super::lower_expr::MAX_EXPR_LOWER_DEPTH as usize) / 2;
let chain: Vec<&str> = vec!["1"; n];
let source = format!("var x = {};\n", chain.join("+"));
let module = perry_parser::parse_typescript(&source, "ok.ts").expect("parses");
assert!(
super::lower_module(&module, "ok", "ok.ts").is_ok(),
"a chain under the depth ceiling must lower without error"
);
});
}
Loading