Skip to content
7 changes: 7 additions & 0 deletions src/ast/e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ impl Default for NameOfSymbol {
pub struct Array {
pub items: ExprNodeList,
pub comma_after_spread: crate::Loc,
/// `[(a = 1)]`: an error only if this literal is a pattern.
pub parenthesized_assign: crate::Loc,
pub is_single_line: bool,
pub is_parenthesized: bool,
pub was_originally_macro: bool,
Expand All @@ -51,6 +53,7 @@ impl Default for Array {
Self {
items: bun_alloc::AstAlloc::vec(),
comma_after_spread: crate::Loc::EMPTY,
parenthesized_assign: crate::Loc::EMPTY,
is_single_line: false,
is_parenthesized: false,
was_originally_macro: false,
Expand Down Expand Up @@ -1274,6 +1277,8 @@ impl ArrayJSON {
pub struct Object {
pub properties: G::PropertyList,
pub comma_after_spread: crate::Loc,
/// `{ x: (a = 1) }`: see `Array::parenthesized_assign`.
pub parenthesized_assign: crate::Loc,
pub is_single_line: bool,
pub is_parenthesized: bool,
pub was_originally_macro: bool,
Expand All @@ -1285,6 +1290,7 @@ impl Default for Object {
Self {
properties: bun_alloc::AstAlloc::vec(),
comma_after_spread: crate::Loc::EMPTY,
parenthesized_assign: crate::Loc::EMPTY,
is_single_line: false,
is_parenthesized: false,
was_originally_macro: false,
Expand Down Expand Up @@ -1351,6 +1357,7 @@ impl Object {
pub const EMPTY: Object = Object {
properties: bun_alloc::AstAlloc::vec(),
comma_after_spread: crate::Loc::EMPTY,
parenthesized_assign: crate::Loc::EMPTY,
is_single_line: false,
is_parenthesized: false,
was_originally_macro: false,
Expand Down
2 changes: 2 additions & 0 deletions src/ast/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1878,6 +1878,7 @@ impl Data {
let item = bump.alloc(E::Array {
items,
comma_after_spread: el.comma_after_spread,
parenthesized_assign: el.parenthesized_assign,
was_originally_macro: el.was_originally_macro,
is_single_line: el.is_single_line,
is_parenthesized: el.is_parenthesized,
Expand Down Expand Up @@ -2065,6 +2066,7 @@ impl Data {
let item = bump.alloc(E::Object {
properties: el.properties.try_deep_clone_with(|p| p.deep_clone(bump))?,
comma_after_spread: el.comma_after_spread,
parenthesized_assign: el.parenthesized_assign,
is_single_line: el.is_single_line,
is_parenthesized: el.is_parenthesized,
was_originally_macro: el.was_originally_macro,
Expand Down
7 changes: 7 additions & 0 deletions src/js_parser/fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -924,6 +924,13 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
))
}

pub(crate) fn maybe_parenthesized_assign_error(&mut self, parenthesized_assign: bun_ast::Loc) {
if let Some(loc) = parenthesized_assign.to_nullable() {
self.log()
.add_error(Some(self.source), loc, b"Invalid assignment target");
}
}

pub(crate) fn maybe_comma_spread_error(&mut self, comma_after_spread: bun_ast::Loc) {
let p = self;
if comma_after_spread.is_empty() {
Expand Down
47 changes: 33 additions & 14 deletions src/js_parser/p.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3959,6 +3959,12 @@
kind: crate::parser::InvalidLocTag::Spread,
});
}
if let Some(paren) = ex.parenthesized_assign.to_nullable() {
invalid_loc.push(InvalidLoc {
loc: paren,
kind: crate::parser::InvalidLocTag::Parentheses,
});
}

if ex.is_parenthesized {
invalid_loc.push(InvalidLoc {
Expand Down Expand Up @@ -4014,6 +4020,12 @@
kind: crate::parser::InvalidLocTag::Spread,
});
}
if let Some(paren) = ex.parenthesized_assign.to_nullable() {
invalid_loc.push(InvalidLoc {
loc: paren,
kind: crate::parser::InvalidLocTag::Parentheses,
});
}

if ex.is_parenthesized {
invalid_loc.push(InvalidLoc {
Expand Down Expand Up @@ -4043,11 +4055,24 @@
continue;
}
let value = item.value.as_mut().unwrap();
let tup =
self.convert_expr_to_binding_and_initializer(value, invalid_loc, false);
let initializer = tup.expr.or(item.initializer);
let is_spread = item.kind == js_ast::g::PropertyKind::Spread
|| item.flags.contains(Flags::Property::IsSpread);
let tup =
self.convert_expr_to_binding_and_initializer(value, invalid_loc, is_spread);
// "({ ...[a] }) => 0"
if is_spread
&& let Some(binding) = &tup.binding
&& matches!(
binding.data,
js_ast::b::B::BArray(_) | js_ast::b::B::BObject(_)
)
{
invalid_loc.push(InvalidLoc {
loc: binding.loc,
kind: crate::parser::InvalidLocTag::Unknown,
});
}
let initializer = tup.expr.or(item.initializer);
let mut flags = Flags::PropertySet::empty();
if is_spread {
flags |= Flags::Property::IsSpread;
Expand Down Expand Up @@ -4104,17 +4129,11 @@
}

let bind = self.convert_expr_to_binding(expr, invalid_log);
if let Some(initial) = initializer {
let equals_range = self.source.range_of_operator_before(initial.loc, b"=");
if is_spread {
self.log().add_range_error(
Some(self.source),
equals_range,
b"A rest argument cannot have a default initializer",
);
} else {
// p.markSyntaxFeature();
}
if is_spread && let Some(initial) = initializer {
invalid_log.push(InvalidLoc {
loc: self.source.range_of_operator_before(initial.loc, b"=").loc,
kind: crate::parser::InvalidLocTag::RestInitializer,
});
}
ExprBindingTuple {
binding: bind,
Expand Down Expand Up @@ -9576,7 +9595,7 @@
/// it (e.g. via `assume_init`); on `Err`, `*out` is left untouched.
/// Taking `&mut MaybeUninit<Self>` (vs the previous `*mut Self`) makes the
/// alignment/writability precondition a type guarantee, so this fn is safe.
pub fn init(

Check warning on line 9598 in src/js_parser/p.rs

View workflow job for this annotation

GitHub Actions / mordant

`p::P::<'a, TYPESCRIPT, SCAN_ONLY>::init` is generic over `TYPESCRIPT` and `SCAN_ONLY` and is compiled 4 times in this crate, but one part of it, 41 of its 276 statements (as MIR), does not use `TYPESCRIPT` or `SCAN_ONLY`
out: &mut core::mem::MaybeUninit<Self>,
arena: &'a Bump,
log: core::ptr::NonNull<bun_ast::Log>,
Expand Down
38 changes: 37 additions & 1 deletion src/js_parser/parse/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,16 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O

let had_pure_comment_before =
self.lexer.has_pure_comment_before && !self.options.ignore_dce_annotations;
let paren_assign_before = errors
.as_deref()
.and_then(|errors| errors.parenthesized_assign);
*expr = self.parse_prefix(level, errors.as_deref_mut(), flags)?;
let paren_assign_prefix = match errors.as_deref() {
Some(errors) if errors.parenthesized_assign != paren_assign_before => {
Self::assign_ptr(expr)
}
_ => None,
};
// `errors` is reborrowed via as_deref_mut for each call site.

// There is no formal spec for "__PURE__" comments but from reverse-
Expand All @@ -95,10 +104,27 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
}
}

self.parse_suffix(expr, level, errors, flags)?;
self.parse_suffix(expr, level, errors.as_deref_mut(), flags)?;

// "[(a = 1)] = []" is an error, "[(a = {}).b] = [1]" is not. With any
// other suffix the visit pass already rejects the target.
Comment thread
robobun marked this conversation as resolved.
Resolved
if let (Some(errors), Some(prefix)) = (errors, paren_assign_prefix)
&& Self::assign_ptr(expr) != Some(prefix)
{
errors.parenthesized_assign = paren_assign_before;
}
Ok(())
}

fn assign_ptr(expr: &Expr) -> Option<*const E::Binary> {
match &expr.data {
js_ast::ExprData::EBinary(e) if e.op == js_ast::OpCode::BinAssign => {
Some(e.as_ptr().cast_const())
}
_ => None,
}
}

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
pub(crate) fn parse_yield_expr(&mut self, loc: bun_ast::Loc) -> Result<Expr, Error> {
let p = self;
// Parse a yield-from expression, which yields from an iterator
Expand Down Expand Up @@ -449,9 +475,12 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
p.latest_arrow_arg_loc = p.lexer.loc();

let mut item = Expr::EMPTY;
let parenthesized_assign = errors.parenthesized_assign;
p.parse_expr_or_bindings(Level::Comma, Some(&mut errors), &mut item)?;

if is_spread {
// "...(a = 1)" is already an invalid rest argument without the parentheses
errors.parenthesized_assign = parenthesized_assign;
item = p.new_expr(E::Spread { value: item }, loc);
}

Expand Down Expand Up @@ -577,6 +606,13 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
if is_arrow_fn || opts.force_arrow_fn {
p.maybe_comma_spread_error(comma_after_spread);
p.log_arrow_arg_errors(&mut arrow_arg_errors);
if let Some(paren) = errors.parenthesized_assign {
p.log().add_error(
Some(p.source),
paren,
b"Unexpected parentheses in binding pattern",
);
}

// Now that we've decided we're an arrow function, report binding pattern
// conversion errors
Expand Down
51 changes: 39 additions & 12 deletions src/js_parser/parse/parse_prefix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,17 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
Ok(p.new_expr(E::Super {}, loc))
}

fn pfx_t_open_paren(p: &mut Self, level: Level, flags: EFlags) -> PResult<Expr> {
fn pfx_t_open_paren(
p: &mut Self,
level: Level,
errors: Option<&mut DeferredErrors>,
flags: EFlags,
) -> PResult<Expr> {
let loc = p.lexer.loc();
p.lexer.next()?;

// Arrow functions aren't allowed in the middle of expressions
if level.gt(Level::Assign) {
let value = if level.gt(Level::Assign) {
// Allow "in" inside parentheses
let old_allow_in = p.allow_in;
p.allow_in = true;
Expand All @@ -59,17 +64,28 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
p.lexer.expect(T::TCloseParen)?;

p.allow_in = old_allow_in;
return Ok(value);
value
} else {
p.parse_paren_expr(
loc,
level,
ParenExprOpts {
is_after_question_and_before_colon: flags
== EFlags::AfterQuestionAndBeforeColon,
..Default::default()
},
)?
};

// "[(a = 1)] = []" is not the pattern "[a = 1] = []".
if let Some(errors) = errors
&& let ExprData::EBinary(bin) = &value.data
&& bin.op == OpCode::BinAssign
{
errors.parenthesized_assign = Some(loc);
}

p.parse_paren_expr(
loc,
level,
ParenExprOpts {
is_after_question_and_before_colon: flags == EFlags::AfterQuestionAndBeforeColon,
..Default::default()
},
)
Ok(value)
}

#[inline]
Expand Down Expand Up @@ -741,7 +757,10 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
p.lexer.next()?;
// Parse into a local then push.
let mut value = Expr::EMPTY;
let parenthesized_assign = self_errors.parenthesized_assign;
p.parse_expr_or_bindings(Level::Comma, Some(&mut self_errors), &mut value)?;
// "...(a = 1)" is already an invalid rest target without the parentheses
self_errors.parenthesized_assign = parenthesized_assign;
items.push(p.new_expr(E::Spread { value }, dots_loc));

// Commas are not allowed here when destructuring
Expand Down Expand Up @@ -794,6 +813,9 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
E::Array {
items: items_list,
comma_after_spread,
parenthesized_assign: self_errors
.parenthesized_assign
.unwrap_or(bun_ast::Loc::EMPTY),
is_single_line,
close_bracket_loc,
..Default::default()
Expand All @@ -819,7 +841,9 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
if p.lexer.token == T::TDotDotDot {
p.lexer.next()?;
let mut value = Expr::EMPTY;
let parenthesized_assign = self_errors.parenthesized_assign;
p.parse_expr_or_bindings(Level::Comma, Some(&mut self_errors), &mut value)?;
self_errors.parenthesized_assign = parenthesized_assign;
properties.push(G::Property {
kind: PropertyKind::Spread,
value: Some(value),
Expand Down Expand Up @@ -882,6 +906,9 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
E::Object {
properties: properties_list,
comma_after_spread,
parenthesized_assign: self_errors
.parenthesized_assign
.unwrap_or(bun_ast::Loc::EMPTY),
is_single_line,
close_brace_loc,
..Default::default()
Expand Down Expand Up @@ -1010,7 +1037,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
T::TOpenBrace => Self::pfx_t_open_brace(p, errors),
T::TLessThan => Self::pfx_t_less_than(p, level, errors, flags),
T::TImport => Self::pfx_t_import(p, level),
T::TOpenParen => Self::pfx_t_open_paren(p, level, flags),
T::TOpenParen => Self::pfx_t_open_paren(p, level, errors, flags),
T::TPrivateIdentifier => Self::pfx_t_private_identifier(p, level),
T::TIdentifier => Self::pfx_t_identifier(p, level, flags),
T::TFalse => Self::pfx_t_false(p),
Expand Down
5 changes: 5 additions & 0 deletions src/js_parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1093,6 +1093,7 @@ pub struct InvalidLoc {
#[derive(Clone, Copy, PartialEq, Eq, Default)]
pub enum InvalidLocTag {
Spread,
RestInitializer,
Parentheses,
Getter,
Setter,
Expand All @@ -1106,6 +1107,7 @@ impl InvalidLoc {
pub(crate) fn add_error(self, log: &mut bun_ast::Log, source: &bun_ast::Source) {
let text: &'static [u8] = match self.kind {
InvalidLocTag::Spread => b"Unexpected trailing comma after rest element",
InvalidLocTag::RestInitializer => b"A rest argument cannot have a default initializer",
InvalidLocTag::Parentheses => b"Unexpected parentheses in binding pattern",
InvalidLocTag::Getter => b"Unexpected getter in binding pattern",
InvalidLocTag::Setter => b"Unexpected setter in binding pattern",
Expand Down Expand Up @@ -1312,6 +1314,9 @@ pub struct DeferredErrors {
/// These are errors for expressions
pub(crate) invalid_expr_default_value: Option<bun_ast::Range>,
pub(crate) invalid_expr_after_question: Option<bun_ast::Range>,

/// `[(a = 1)]`: stored on the enclosing literal, not merged upward.
pub(crate) parenthesized_assign: Option<bun_ast::Loc>,
}

impl DeferredErrors {
Expand Down
15 changes: 14 additions & 1 deletion src/js_parser/visit/visit_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1578,6 +1578,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
let mut e_ = e.data.e_array().expect("infallible: variant checked");
if in_.assign_target != js_ast::AssignTarget::None {
p.maybe_comma_spread_error(e_.comma_after_spread);
p.maybe_parenthesized_assign_error(e_.parenthesized_assign);
}
let items = e_.items.slice_mut();
let mut spread_item_count: usize = 0;
Expand Down Expand Up @@ -1687,6 +1688,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
let mut e_ = e.data.e_object().expect("infallible: variant checked");
if in_.assign_target != js_ast::AssignTarget::None {
p.maybe_comma_spread_error(e_.comma_after_spread);
p.maybe_parenthesized_assign_error(e_.parenthesized_assign);
}

let mut has_spread = false;
Expand Down Expand Up @@ -1726,8 +1728,9 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
has_spread = true;
}

// Extract the initializer for expressions like "({ a: b = c } = d)"
// Extract the initializer for "({ a: b = c } = d)". A rest property takes none.
if in_.assign_target != js_ast::AssignTarget::None
&& property.kind != G::PropertyKind::Spread
&& property.initializer.is_none()
&& property.value.is_some()
{
Expand All @@ -1741,6 +1744,16 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
}
}

// "({ ...[a] } = d)" is a syntax error.
if in_.assign_target != js_ast::AssignTarget::None
&& property.kind == G::PropertyKind::Spread
&& let Some(value) = &property.value
&& matches!(value.data, Data::EArray(..) | Data::EObject(..))
{
p.log()
.add_error(Some(p.source), value.loc, b"Invalid assignment target");
}
Comment thread
robobun marked this conversation as resolved.
Resolved

if let Some(value) = &mut property.value {
// Propagate name from property key for decorated anonymous class expressions
// e.g., { Foo: @dec class {} } should give the class .name = "Foo"
Expand Down
Loading
Loading