Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

_this is not defined when using swc crates #4224

Closed
mischnic opened this issue Apr 1, 2022 · 5 comments · Fixed by #4228
Closed

_this is not defined when using swc crates #4224

mischnic opened this issue Apr 1, 2022 · 5 comments · Fixed by #4228
Assignees
Milestone

Comments

@mischnic
Copy link
Contributor

mischnic commented Apr 1, 2022

From Rust (it works fine via the swc binary/REPL), preset_env references nonexisting variables.

Either I'm using swc wrong or this is a bug?

Input

class A {
    constructor() {
        this.foo = async () => {
            this.x();
        };
        this.bar = async () => {
            this.x();
        };
    }
}

console.log(A); 

Invalid Output:

var A = function A() {
    "use strict";
    _classCallCheck(this, A);
    var _this1 = this;
    this.foo = _asyncToGenerator(regeneratorRuntime.mark(function _callee() {
        return regeneratorRuntime.wrap(function _callee$(_ctx) {
            while(1)switch(_ctx.prev = _ctx.next){
                case 0:
                    _this.x();  // <---------------------- no assignment from _this1
                case 1:
                case "end":
                    return _ctx.stop();
            }
        }, _callee);
    }));
    this.bar = _asyncToGenerator(regeneratorRuntime.mark(function _callee() {
        var _this;
        return regeneratorRuntime.wrap(function _callee$(_ctx) {
            while(1)switch(_ctx.prev = _ctx.next){
                case 0:
                    _this = _this1; // <----------------- here the assignment was added
                    _this1.x();
                case 2:
                case "end":
                    return _ctx.stop();
            }
        }, _callee);
    }));
};

Code

(running with ac2357e):

use std::{path::Path, sync::Arc};

use swc::{self, config::Options};
use swc_common::{
    chain, comments::SingleThreadedComments, sync::Lrc, FileName, Globals, Mark, SourceMap,
    SyntaxContext, DUMMY_SP,
};
use swc_ecma_ast::{Decl, Ident, ImportSpecifier, Invalid, Module};
use swc_ecma_codegen::{text_writer::JsWriter, Config, Emitter};
use swc_ecma_parser::{lexer::Lexer, EsConfig, PResult, Parser, StringInput, Syntax, TsConfig};
use swc_ecma_preset_env::{preset_env, BrowserData, Mode, Targets, Version};
use swc_ecma_transforms::{
    compat::reserved_words::reserved_words,
    fixer,
    fixer::paren_remover,
    helpers, hygiene,
    optimization::simplify::{dead_branch_remover, expr_simplifier},
    react,
    resolver::resolver_with_mark,
};
use swc_ecma_transforms_compat::es2015;
use swc_ecma_visit::FoldWith;

fn main() {
    let cm = Lrc::<SourceMap>::default();
    let src = r#"
class A {
    constructor() {
        this.foo = async () => {
            this.x();
        };
        this.bar = async () => {
            this.x();
        };
    }
}

console.log(A); 
"#;
    let (module, comments) = parse(src, "test.js", &cm).unwrap();

    swc_common::GLOBALS.set(&Globals::new(), || {
        helpers::HELPERS.set(&helpers::Helpers::default(), || {
            let global_mark = Mark::fresh(Mark::root());
            let module = module.fold_with(&mut resolver_with_mark(global_mark));

            let module = module.fold_with(&mut preset_env(
                global_mark,
                Some(&comments),
                swc_ecma_preset_env::Config {
                    targets: Some(Targets::Versions(BrowserData {
                        ie: Some(Version {
                            major: 11,
                            minor: 0,
                            patch: 0,
                        }),
                        ..Default::default()
                    })),
                    shipped_proposals: true,
                    mode: Some(Mode::Entry),
                    bugfixes: true,
                    ..Default::default()
                },
                Default::default(),
            ));

            let module = module.fold_with(&mut chain!(
                reserved_words(),
                hygiene(),
                fixer(Some(&comments))
            ));

            let code = emit(&module, &comments, cm);
            println!("{}", code);
        });
    });
}

fn parse(
    code: &str,
    filename: &str,
    cm: &Lrc<SourceMap>,
) -> PResult<(Module, SingleThreadedComments)> {
    let source_file = cm.new_source_file(FileName::Real(filename.into()), code.into());
    let comments = SingleThreadedComments::default();

    let lexer = Lexer::new(
        Syntax::Es(EsConfig {
            jsx: true,
            ..Default::default()
        }),
        // Syntax::Typescript(TsConfig {
        //     tsx: true,
        //     ..Default::default()
        // }),
        Default::default(),
        StringInput::from(&*source_file),
        Some(&comments),
    );
    let mut parser = Parser::new_from(lexer);
    match parser.parse_module() {
        Err(err) => Err(err),
        Ok(module) => Ok((module, comments)),
    }
}

fn emit(module: &Module, comments: &SingleThreadedComments, cm: Lrc<SourceMap>) -> String {
    let mut buf = vec![];
    {
        let writer = Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None));
        let config = Config { minify: false };
        let mut emitter = Emitter {
            cfg: config,
            comments: Some(&comments),
            cm,
            wr: writer,
        };
        emitter.emit_module(&module).unwrap();
    }

    String::from_utf8(buf).unwrap()
}

Context

parcel-bundler/parcel#7878

@kdy1 kdy1 added this to the Planned milestone Apr 2, 2022
@kdy1
Copy link
Member

kdy1 commented Apr 2, 2022

Seem like a bug, but not sure.

@kdy1
Copy link
Member

kdy1 commented Apr 2, 2022

Oh bugfix transform was the cause.
Especially async_arrows_in_class

@kdy1 kdy1 self-assigned this Apr 2, 2022
@kdy1 kdy1 modified the milestones: Planned, v1.2.163 Apr 2, 2022
@kdy1 kdy1 closed this as completed in #4228 Apr 2, 2022
@mischnic
Copy link
Contributor Author

mischnic commented Apr 2, 2022

Thanks!

@swc-bot
Copy link
Collaborator

swc-bot commented Oct 16, 2022

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.

@swc-project swc-project locked as resolved and limited conversation to collaborators Oct 16, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

Successfully merging a pull request may close this issue.

3 participants