swc-project/swc · error

failed to parse AssignTarget

Error message

failed to parse AssignTarget

What it means

Inside `parse_input_type` (crates/swc_ecma_quote_macros/src/ret_type.rs), when the `quote!` output type is `AssignTarget`, the macro parses the quoted string as a `Pat` and converts it with `AssignTarget::try_from(p)`. That `TryFrom` (crates/swc_ecma_ast/src/expr.rs:1519) only accepts `Pat::Ident`, `Pat::Array`, `Pat::Object`, `Pat::Invalid`, and `Pat::Expr` variants that are themselves valid `SimpleAssignTarget`s. Any other pattern returns Err and this `expect` panics during macro expansion.

Source

Thrown at crates/swc_ecma_quote_macros/src/ret_type.rs:45

    if let Some(ty) = extract_generic("Option", ty) {
        if input_str.is_empty() {
            return Ok(BoxWrapper(Box::new(None::<swc_ecma_ast::Expr>)));
        }

        let node = parse_input_type(input_str, ty).context("failed to parse `T` in Option<T>")?;
        return Ok(BoxWrapper(Box::new(Some(node))));
    }

    if let Type::Path(p) = ty {
        if let Some(ident) = p.path.get_ident() {
            match &*ident.to_string() {
                "Expr" => return parse(input_str, &mut |p| p.parse_expr().map(|v| *v)),
                "Pat" => return parse(input_str, &mut |p| p.parse_pat()),
                "Stmt" => return parse(input_str, &mut |p| p.parse_stmt_list_item()),
                "AssignTarget" => {
                    return parse(input_str, &mut |p| {
                        Ok(AssignTarget::try_from(p.parse_pat()?)
                            .expect("failed to parse AssignTarget"))
                    })
                }
                "ModuleItem" => return parse(input_str, &mut |p| p.parse_module_item()),
                _ => {}
            }
        }
    }

    bail!("Unknown quote type: {ty:?}");
}

fn parse<T>(
    input_str: &str,
    op: &mut dyn FnMut(&mut Parser<Lexer>) -> PResult<T>,
) -> Result<BoxWrapper, Error>
where
    T: ToCode,
{

View on GitHub (pinned to 5176682b65)

Solutions

  1. Quote only a valid assignment target: a plain identifier (`"a"`), a member expression (`"a.b"`, `"a[b]"`), or a destructuring pattern (`"[a, b]"`, `"({ a })").
  2. Remove default values and rest elements from the quoted string (`"a = 1"` and "...rest" are not assignable targets in the Pat form this macro accepts).
  3. For call results or literals on the left-hand side, that code is invalid JavaScript anyway; fix the template to match real assignment syntax.
  4. If you need an arbitrary pattern, use `quote!(Pat as "...")` and convert to AssignTarget yourself where you can handle the Err.

Example fix

// before
let target = quote!(AssignTarget as "a = 1"); // Pat::Assign rejected by TryFrom<Pat>

// after
let target = quote!(AssignTarget as "a");
Defensive patterns

Strategy: type-guard

Type guard

// A quoted string is safe for `quote!(AssignTarget as "...")` only if it is
// an identifier, member access, or destructuring pattern.
fn is_assign_target_snippet(src: &str) -> bool {
    let s = src.trim();
    // reject defaults ("a = 1") and top-level rest ("...r")
    if s.contains("= ") || s.starts_with("...") {
        return false;
    }
    matches!(
        s,
        _ if s.chars().next().map_or(false, |c| c.is_alphabetic() || c == '_' || c == '[' || s.starts_with("({"))
    )
}

Prevention

When it happens

Trigger: `quote!(AssignTarget as "a = 1")` (Pat::Assign, a pattern with default), `quote!(AssignTarget as "...rest")` (Pat::Rest), or an expression pattern that is not a simple assignment target such as `quote!(AssignTarget as "foo()")`, `"123"`, or `"a + b"` (SimpleAssignTarget::try_from rejects call/literal/binary expressions).

Common situations: Transform authors templating the left-hand side of an assignment expression (`AssignExpr { left: quote!(AssignTarget as "..."), .. }`) and pasting a full assignment, a rest element, or a non-reference expression into the quoted string. The panic happens at compile time of the transform crate.

Understand the failure class

Related errors


AI-assisted analysis of swc-project/swc@5176682b65 (2026-08-17). Data as JSON: /api/errors/7b5f4fb9ba54e7d5. Report an issue: GitHub.