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

[swc_ecma_transforms_typescript]: internal error: entered unreachable code: Use Program as entry #8950

Closed
Hulxv opened this issue May 13, 2024 · 1 comment · Fixed by #8952
Assignees
Milestone

Comments

@Hulxv
Copy link

Hulxv commented May 13, 2024

My case

I tried to build an internal compiler in my program that can convert from ts to js and I found that example.

Explain

When I tried to run the example I got this error for an unknown reason

thread 'main' panicked at ~/.cargo/registry/src/index.crates.io-6f17d22bba15001f/swc_ecma_transforms_typescript-0.189.1/src/typescript.rs:68:9:
internal error: entered unreachable code: Use Program as entry
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

After some debugging, I found I got this issue from this line

// Remove typescript types
let module = module.fold_with(&mut strip(top_level_mark));

The error is gone when I remove this line but the problem is the typescript types aren't removed

Source code

main.rs

use std::{env, path::Path};

use swc_common::{
    comments::SingleThreadedComments,
    errors::{ColorConfig, Handler},
    sync::Lrc,
    Globals, Mark, SourceMap, GLOBALS,
};
use swc_ecma_codegen::{text_writer::JsWriter, Emitter};
use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax, TsConfig};
use swc_ecma_transforms_base::{fixer::fixer, hygiene::hygiene, resolver};
use swc_ecma_transforms_typescript::strip;
use swc_ecma_visit::FoldWith;

fn main() {
    let cm: Lrc<SourceMap> = Default::default();

    // Real usage
    let fm = cm
        .load_file(Path::new("../../tests/web-app/App.tsx"))
        .expect("failed to load test.js");

    let input = env::args()
        .nth(1)
        .expect("please provide the path of input typescript file");

    let comments = SingleThreadedComments::default();

    let lexer = Lexer::new(
        Syntax::Typescript(TsConfig {
            tsx: input.ends_with(".tsx"),
            ..Default::default()
        }),
        Default::default(),
        StringInput::from(&*fm),
        Some(&comments),
    );

    let mut parser = Parser::new_from(lexer);

    for e in parser.take_errors() {
        eprintln!["{e:?}"]
    }

    let module = parser
        .parse_module()
        .map_err(|e| eprintln!("{e:?}"))
        .expect("failed to parse module.");

    let globals = Globals::default();
    GLOBALS.set(&globals, || {
        let unresolved_mark = Mark::new();
        let top_level_mark = Mark::new();

        // Optionally transforms decorators here before the resolver pass
        // as it might produce runtime declarations.

        // Conduct identifier scope analysis
        let module = module.fold_with(&mut resolver(unresolved_mark, top_level_mark, true));
    
        // !!! the error appears here
        // Remove typescript types
        let module = module.fold_with(&mut strip(top_level_mark));

        // Fix up any identifiers with the same name, but different contexts
        let module = module.fold_with(&mut hygiene());

        // Ensure that we have enough parenthesis.
        let module = module.fold_with(&mut fixer(Some(&comments)));

        let mut buf = vec![];
        {
            let mut emitter = Emitter {
                cfg: swc_ecma_codegen::Config::default(),
                cm: cm.clone(),
                comments: Some(&comments),
                wr: JsWriter::new(cm.clone(), "\n", &mut buf, None),
            };

            emitter.emit_module(&module).unwrap();
        }

        println!("{}", String::from_utf8(buf).expect("non-utf8?"));
    })
}

../../tests/web-app/App.tsx

import React, { useState, ReactNode } from 'react';
import { renderToString } from 'react-dom/server';

export function Hello(text: string, children: ReactNode) {
	return renderToString(
		<div>
			<script src="https://cdn.tailwindcss.com"></script>
			<h1 className="text-4xl font-bold">Hello {text}, </h1>
		</div>
	);
}

Crates

[dependencies]
swc_common = "0.33.26"
swc_ecma_ast = "0.113.2"
swc_ecma_parser = "0.144.1"
swc_ecma_transforms_typescript = "0.189.1"
swc_ecma_visit = "0.99.1"
swc = "0.275.0"
swc_ecma_codegen = "0.149.1"
swc_ecma_transforms_base = "0.138.2"
@kdy1 kdy1 added this to the Planned milestone May 13, 2024
@kdy1 kdy1 self-assigned this May 13, 2024
kdy1 added a commit that referenced this issue May 14, 2024
**Related issue:**

 - Closes #8950
@kdy1 kdy1 modified the milestones: Planned, v1.5.7 May 14, 2024
@swc-bot
Copy link
Collaborator

swc-bot commented Jun 14, 2024

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 Jun 14, 2024
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