swc-project / swc

Rust-based platform for the Web
https://swc.rs
Apache License 2.0
30.92k stars 1.21k forks source link

Cannot assign to private field with loose=true #6581

Closed ytoune closed 1 year ago

ytoune commented 1 year ago

Describe the bug

Unable to assign to private field if loose in config is set to true

Input code

class Hoge {
    #hoge: number
    constructor() {
        this.#hoge = 42
    }
}

Config

{
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": true
    },
    "target": "es2019",
    "loose": true,
    "minify": {
      "compress": false,
      "mangle": false
    }
  },
  "module": {
    "type": "es6"
  },
  "minify": false,
  "isModule": true
}

Playground link

https://play.swc.rs/?version=1.3.21&code=H4sIAAAAAAAAA0vOSSwuVvDIT09VqOblUgAC5Qwgx0ohrzQ3KbUIIpScn1dcUlSaXJJfpKEJUwcCJRmZxXpgDQq2CiZGEIlaXq5aAOAmk3JXAAAA&config=H4sIAAAAAAAAA0WOTQoCMQyF75L1LNSFYO%2FgIULNDJX%2BkWTAUnp321pw9%2FLey5dUeIsFUyEjC%2FFQUqLiBwxoySSWXVbYQKVbyie1rpEP0t4guV2uj576lIR%2B%2BQbBRbeXgbIpZCYRMDt6GRHGw9MaW0eF9DqHUee1ibxD%2BzPWnpPnKs4XviYz9TO2AAAA

Expected behavior

compiled code might look like below

constructor(){
  Object.defineProperty(this, _hoge, {
    writable: true,
    value: void 0
  });
  this[_hoge] = 42;
}

Actual behavior

compiled code

constructor(){
  Object.defineProperty(this, _hoge, {
    writable: true,
    value: void 0
  });
  _classPrivateFieldLooseBase(this, _hoge)[_hoge] = 42;
}

this behaves like

constructor(){
  this[_hoge] = void 0;
  this[_hoge][_hoge] = 42;
  // Uncaught TypeError: Cannot set properties of undefined (setting '__private_0__hoge')
}

Version

1.3.21

Additional context

No response

ytoune commented 1 year ago

this is in version 1.2.155 and above

version 1.2.154

constructor(){
  _classPrivateFieldInit(this, _hoge, {
    writable: true,
    value: void 0
  });
  _classPrivateFieldSet(this, _hoge, 42);
}
ytoune commented 1 year ago

https://github.com/swc-project/swc/blob/6008995db1ce29459e0264eb3ef282fb4a003fda/crates/swc_ecma_transforms_base/src/helpers/_class_private_field_loose_base.js#L1-L7

https://github.com/swc-project/swc/blob/4a27e6f84a9a4e99d161664fa1441b1278756023/packages/swc-helpers/src/_class_private_field_loose_base.mjs#L1-L7

swc-bot commented 1 year ago

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.