Giter Site home page Giter Site logo

swc-project / swc Goto Github PK

View Code? Open in Web Editor NEW
30.0K 148.0 1.1K 302.25 MB

Rust-based platform for the Web

Home Page: https://swc.rs

License: Apache License 2.0

Rust 94.56% Shell 0.24% JavaScript 3.76% TypeScript 1.42% Python 0.03% SCSS 0.01%
ecmascript compiler rust javascript parser babel swc ecmascript-parser typescript typescript-compiler

swc's Introduction

swc

Make the web (development) faster.

downloads (@swc/core) downloads (3rd party)

undefined GitHub release (latest SemVer)

GitHub code size in bytes node-current (scoped)

Discord

SWC (stands for Speedy Web Compiler) is a super-fast TypeScript / JavaScript compiler written in Rust. It's a library for Rust and JavaScript at the same time. If you are using SWC from Rust, see rustdoc and for most users, your entry point for using the library will be parser.

Also, SWC tries to ensure that

If you select the latest version of each crates, it will work

for rust users.

MSRV of crates is currently 1.71.

To update all SWC crates you use, you can run curl https://raw.githubusercontent.com/swc-project/swc/main/scripts/update-all-swc-crates.sh | bash -s. This script will update all dependencies to the latest version and run cargo build to ensure that everything works. Note that you need

  • jq
  • cargo upgrade

command to run the script.


If you are using SWC from JavaScript, please refer to docs on the website.

Documentation

Check out the documentation in the website.

Features

Please see comparison with babel.

Performance

Please see benchmark results on the website.

Supporting swc

Sponsors

SWC is a community-driven project, and is maintained by a group of volunteers. If you'd like to help support the future of the project, please consider:

Contributing

See CONTRIBUTING.md. You may also find the architecture documentation useful (ARCHITECTURE.md).

License

SWC is primarily distributed under the terms of the Apache License (Version 2.0).

See LICENSE for details.

swc's People

Contributors

0xe avatar alexander-akait avatar arturaralin avatar austaras avatar bartlomieju avatar bors[bot] avatar brooooooklyn avatar devongovett avatar dsherret avatar g-plane avatar hyf0 avatar ironlu233 avatar iwanabethatguy avatar jridgewell avatar jserfeng avatar kdy1 avatar kwonoj avatar magic-akari avatar mischnic avatar nayeemrmn avatar nissy-dev avatar punkeel avatar realtimetodie avatar riesaex avatar sosukesuzuki avatar swc-bot avatar tmpfs avatar williamtetlow avatar wre232114 avatar xnuk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swc's Issues

Bug: swc does not import the `_interopRequireDefault` function when it is referenced

If you try compiling the following with swc:

import Foo from 'bar';

You get this:

'use strict';
var _bar = _interopRequireDefault(require('bar'));

The function _interopRequireDefault is referenced, though never defined, leading to ReferenceErrors.

There are other functions that have the same behavior:

  • _interopRequireWildcard

Expected: If swc inserts references to functions, it will define or import those functions.

Actual: swc references numerous functions that it does not define/import.

Arc<Helpers> is wrong

Injected helpers should not flow into other files.

Current behavior

input.js:

class Foo extends Bar {}

simple.js:

npx swc -d out *.js

make out/simple.js contain unnecessary helpers.

I'll fix this ASAP.

Missing comma when importing both default and named imports in single declaration

Comma is missing when importing both default and named imports in single declaration:

Input

$ cat test.js
import colors, { color } from 'patterns/colors'

Output

$ node_modules/.bin/swc test.js
import colors { color }from 'patterns/colors';

Expected

$ node_modules/.bin/swc test.js
import colors, { color }from 'patterns/colors';
$ cat node_modules/swc/package.json
{
  "name": "swc",
  "version": "1.0.3",

css support

TODOs

  • Parser
  • Transforms (See postcss)
    • minifier (P-high)
    • cssnext (P-high)
      This includes features which does not have compatability hazard.
    • AutoPrefixer (P-high)
  • scss support
    It might use libsass.

Bug: swc incorrectly un-strings object keys with periods in them

Try running swc on the following js:

const x = {
  'foo.bar': true
}

It will output

'use strict';
var x = {
        foo.bar: true
};

The foo.bar is not correct syntax. swc needs to keep string object keys that contain js special characters as strings. It's probably easier to just keep all string object keys as strings.

EcmaScript lexer is inefficient

  • It currently pushes one char at a time. It should chunk to amortize allocations.

Current code is similar to

let mut buf = String::new();
loop {
   // xxx
   buf.push(c);
}

Obviously, this almost always allocate and reallocates quite frequently.


  • It allocate needlessly while tokenizing numeric literals.

Noticeable parts are

let s = format!("{}", val);
// if it contains '8' or '9', it's decimal.
if s.contains('8') || s.contains('9') {}
// It's Legacy octal, and we should reinterpret value.
let val = u64::from_str_radix(&format!("{}", val), 8)
    .expect("Does this can really happen?");
let val = format!("{}", val)
    .parse()
     .expect("failed to parse numeric value as f64");
val = format!("{}.{}", val, minority).parse();

tagged template literal can contain invalid escape sequence

parser currently does not support parsing code like

latex`\unicode`

Note: this is valid only for es2018+
Implementor should check for the JscTarget.

This can be done by modifying code at

fn read_tmpl_token(&mut self, start_of_tpl: BytePos) -> LexResult<Token> {
let start = self.cur_pos();
// TODO: Optimize
let mut has_escape = false;
let mut cooked = String::new();
let mut raw = String::new();
while let Some(c) = self.cur() {
if c == '`' || (c == '$' && self.peek() == Some('{')) {
if start == self.cur_pos() && self.state.last_was_tpl_element() {
if c == '$' {
self.bump();
self.bump();
return Ok(tok!("${"));
} else {
self.bump();
return Ok(tok!('`'));
}
}
// TODO: Handle error
return Ok(Template {
cooked: cooked.into(),
raw: raw.into(),
has_escape,
});
}
if c == '\\' {
has_escape = true;
raw.push('\\');
let mut wrapped = Raw(Some(raw));
let ch = self.read_escaped_char(&mut wrapped)?;
raw = wrapped.0.unwrap();
if let Some(s) = ch {
cooked.extend(s);
}
} else if c.is_line_break() {
self.state.had_line_break = true;
let c = if c == '\r' && self.peek() == Some('\n') {
raw.push_str("\\r\\n");
self.bump(); // '\r'
'\n'
} else {
match c {
'\n' => raw.push_str("\n"),
'\r' => raw.push_str("\r"),
'\u{2028}' => raw.push_str("\u{2028}"),
'\u{2029}' => raw.push_str("\u{2029}"),
_ => unreachable!(),
}
c
};
self.bump();
cooked.push(c);
} else {
self.bump();
cooked.push(c);
raw.push(c);
}
}
self.error(start_of_tpl, SyntaxError::UnterminatedTpl)?
}

Dynamic import

I'd love to try this library out for Mastodon, to see if it helps with compile time, but currently I'm stuck on dynamic import() calls throwing an error.

String literal as property name not handled correctly

Hi, I've encountered a problem using swc in one of my code-bases. Feel free to close if this is known or symptomatic of an planned but unjmplemented feature.

Given this source javascript:

const o = {
    foo: 1,
    'bar@': 2,
    '@': 3
};

Expected output:

var o = {
    foo: 1,
    'bar@': 2,
    '@': 3
};

Actual output:

var o = {
    foo: 1,
    bar@: 2,
    @: 3
};

Which results in an SyntaxError: Invalid or unexpected token for @.

I am using:

$ npx swc --version
0.1.7

Which incidentally appears to be another problem since package.json is pinned to 0.1.8:

"dependencies": {
    "swc": "^1.0.3",
    "swc-cli": "^0.1.8"
  }

Usage without node.js

Is it possible to use swc from rust directly?

We're building https://github.com/superfly/fly.rs and would like to bundle code (typescript and javascript) via swc.

As far as I can tell, the node implementation is a wrapper around swc, but it should work from rust too, right?

Legacy octal escape is not permitted in strict mode

HI,

I'm getting this error when trying to compile a few test files :

C:\...>npx -p swc -p swc-cli swc *.js -o out.js
error: Legacy octal escape is not permitted in strict mode
 --> <GLOBAL.Path>:1:45
  |
1 | 'C:\Users\vrs\AppData\Roaming\npm-cache\_npx\7000;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;
C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\In
tel(R) Management Engine Components\IPT;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\Git\cmd;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\S
ystem32\OpenSSH\;C:\Program Files (x86)\Yarn\bin\;C:\Program Files\Java\jdk-11.0.1\bin;C:\Program Files (x86)\Calibre2\;C:\Program Files\nodejs\;C:\Users\vrs\AppData\Local\Microsoft\WindowsApps;C:\Users\vrs\AppData\Local\Programs\Mi
crosoft VS Code\bin;C:\Users\vrs\AppData\Roaming\npm;C:\Users\vrs\bin\Sencha\Cmd;'
  |                                             ^^

Error: internal error in Neon module: failed to parse global variable Path=`'C:\Users\vrs\AppData\Roaming\npm-cache\_npx\7000;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\windows\system32;C:\windo
ws;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\I
ntel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\Git\cmd;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOW
S\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files (x86)\Yarn\bin\;C:\Program Files\Java\jdk-11.0.1\bin;C:\Program Files (x86)\Calibre2\;C:\Program Files\nodejs\;C:\Users\vrs\Ap
pData\Local\Microsoft\WindowsApps;C:\Users\vrs\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\vrs\AppData\Roaming\npm;C:\Users\vrs\bin\Sencha\Cmd;'` as module
    at Object.transformFileSync (C:\Users\vrs\AppData\Roaming\npm-cache\_npx\7000\node_modules\swc\lib\index.js:15:43)
    at Promise (C:\Users\vrs\AppData\Roaming\npm-cache\_npx\7000\node_modules\swc-cli\lib\src\util.js:68:32)
    at new Promise (<anonymous>)
    at Object.compile (C:\Users\vrs\AppData\Roaming\npm-cache\_npx\7000\node_modules\swc-cli\lib\src\util.js:66:12)
    at C:\Users\vrs\AppData\Roaming\npm-cache\_npx\7000\node_modules\swc-cli\lib\src\file.js:155:47
    at Generator.next (<anonymous>)
    at C:\Users\vrs\AppData\Roaming\npm-cache\_npx\7000\node_modules\swc-cli\lib\src\file.js:7:71
    at new Promise (<anonymous>)
    at __awaiter (C:\Users\vrs\AppData\Roaming\npm-cache\_npx\7000\node_modules\swc-cli\lib\src\file.js:3:12)
    at C:\Users\vrs\AppData\Roaming\npm-cache\_npx\7000\node_modules\swc-cli\lib\src\file.js:148:28

Thanks in advance

'SPDY' confusing.

Hi, sorry to raise an issue about something unimportant like this, but I think having 'SPDY' in the name is a bit confusing. I thought it was related to the protocol developed by Google.

Maybe it could just be 'speedy'?

Bundler

Status

  • Bundling of es6 modules.
    • normal import
    • aliased import
    • namespaced import
      • de-globing (& tree shaking)
      • namespaced import with dynamic key
  • Tree shaking.
  • Resolve / Load` trait for extensibility
  • Chunking
  • Dynamic imports
    • Loading
  • swc integration
    • Simple optimizations
    • Transform
    • Optimize helpers (remove duplicate)
    • .swcrc integration
  • "esnext" in package.json
  • spack.config.js

This is a very hard part. I'm considering moving the source code of node-swc to this repository.

  • codegen: Multiple SourceFile

This is required to create the correct source map.

  • Bundling of non-js assets

Need to determine plugin api.

Error reporting

I don't know which features are required.

Maybe..

  • Code highlight like rustc?

TypeScript

Will this transpiler be up to date with the newest changes to TS when they occur?

Awesome project btw!

Possibility of compiling on stable Rust?

Hello! Over in the wasm-bindgen project we've got a new proposal which partly entails eventually having a JS parser built into our tooling. The JS parser would need to basically compile ES module syntax to either CommonJS or "linked manually with no modules" style syntax. The swc project seems like it perfectly fits the bill in terms of use cases here!

One hesitation that we'd currently have from using swc is that it looks like it currently requires nightly Rust and also isn't published much on crates.io. I'm curious if y'all have an idea about whether it's feasible in the near-term to compile on stable (and as a bit of a stretch goal publish on crates.io too). That'd make swc a strong possibility for us to use in wasm-bindgen as a dependency!

We're mostly just evaluating our options right now, so "not any time soon" is a totally valid answer too!

Bug: Ternary operator doesn't work inside parentheses in Typescript

swc fails to compile ternary operators inside parentheses when TypeScript is used:

(foo ? 1 : 2);
$ swc test.ts
error: Unexpected token Some(Colon)
 --> test.ts:1:10
  |
1 | (foo ? 1 : 2);
  |          ^

fatal runtime error: failed to initiate panic, error 5
Abort trap: 6

.swcrc

{
  "jsc": {
    "parser": {
      "syntax": "typescript"
    }
  }
}
$ swc --version
0.1.7
# Yarn reports packages as `[email protected]` and `[email protected]`

The same code compiles fine if "ecmascript" is used instead.

$ swc test.js
foo ? 1 : 2;

How to build with cargo?

Hi
After checkout:
I get this error trying to build swc:
cargo build --release --all-features
error: failed to parse manifest at /tmp/guix-build-swc-0.0-1.2e22397f4.drv-7/source/ecmascript/ast/Cargo.toml

Caused by:
editions are unstable

Caused by:
feature edition is required

this Cargo does not support nightly features, but if you
switch to nightly channel you can add
cargo-features = ["edition"] to enable this feature

Unignore "431ecef8c85d4d24.js" and "8386fbff927a9e0e.js".

"431ecef8c85d4d24" is about unicode xid vs unicode id.

I doubt that character is used for identifier in practice.

"8386fbff927a9e0e" is about parsing very long numeric literal.

It's about float parsing issue. ignored test and P-low because I don't think someone would type 30 zeros instead of 1e30.

Internal documentations

  • Use rustdoc for internal documents.
    • #[derive(AstNode)] derives FoldWith to bypass a rust bug.

Documentation for binary / library is postponed because it should be how-to-use example, and binary is required to do that.

Loaders for several module bundlers

I want to create loaders for SWC for several bundlers. I might ask someone to do it instead, but basically:

  • Rollup
  • Webpack Just noticed it's done

Should I create the modules for these, or will you?

TypeScript support for type-checking

I've successfully used swc to compile typescript files, that's great. I'm thoroughly impressed!

However, I noticed it compiled "wrong" typescript. Example:

function foo(): string {
}

^ is invalid typescript (the function actually returns void), but this will still compile fine with swc.

I'm assuming this is a lot more complicated to make happen. You'd have to check keep track of the type signature of every function and variables to compare and check type validity.

Optimize arguments

use(8 + 8) should be use(16)
But I don't know why it is not optimized.

Clean up

  • Sort arguments of assert_eq call.
  • Replace uses of self.input.xx() to xx!() (in lexer).
  • Document should be consistent.
  • Lexer should use Unicode ID instead of Unicode XID.

commonjs transformation not working via JS API

swc does not transform ES6 import syntax into a require() call when invoked via the JS API. (node bindings)

Reproduction

npm install swc and then:

console.log(
  require('swc').transformSync(`
    import {lodash} from 'lodash'
  `, {
    module: {
      type: 'commonjs'
    }
  }).code
);

Outputs:

import { lodash }from 'lodash';

Better codegen

Currently code generator can not print pretty code neither minified code.
It should support both. (Maybe)

Description of repository is misleading

Under the title of the repository navigation it says:

Super-fast alternative for babel

But within the README it says:

swc is rust port of babel and closure compiler.

Surely under the navigation (the first thing people see) should also mimic what the repository README states?

Handle early errors in ecmascript parser

And enable early/fail tests from test262-parser-tests.

  • (Optional) Check for unmatched labels and recover from it

This can be done by storing current labels in the parser and checking if it matches.

This should be optional as it may degrade performance.
(e.g. deno may not require such feature as they run the javascript file right away)

wasm?

Could this potentially be compiled to WebAssembly? This would allow full interop with the existing Babel packages, and would truly thrust this project into the spotlight.

Question about emitter attribute

Hi there,

This is a non-urgent question about the emitter attribute. I'm not too familiar with rust and I'm trying to understand what this code block is doing, and why it's necessary:

#[allow(unreachable_code)]
{
    return Ok(());
}

Could you explain it to me?

Thank you for the interesting project. Very excited to see where it goes!

Error when running benchmark from node-swc

bench-runner:

Error in :transform:swc
Error: Error(Msg("missing field `react`"), State { next_error: None, backtrace: None })

node: v10.15.0
rustc: 1.33.0-nightly (b2b7a063a 2019-01-01)

Please help :)

Some corner case

When I tried to compile lodash with swc, I found some problems.

ERROR in ./vendor/escape.js 2:8
Module parse failed: Unexpected token (2:8)
You may need an appropriate loader to handle this file type.
| var htmlEscapes = {
>         &: '&amp',
|         <: '&lt',
|         >: '&gt',
 @ ./src/lodash.js 43:0-38 294:16-22
 @ ./src/test.js
 @ multi ./src/test.js

ERROR in ./vendor/unescape.js 2:8
Module parse failed: Unexpected token (2:8)
You may need an appropriate loader to handle this file type.
| var htmlUnescapes = {
>         &amp;: '&',
|         &lt;: '<',
|         &gt;: '>',
 @ ./src/lodash.js 225:0-42 476:18-26
 @ ./src/test.js
 @ multi ./src/test.js

ERROR in ./vendor/.internal/Stack.js 46:32
Module parse failed: Unexpected token (46:32)
You may need an appropriate loader to handle this file type.
|         }, {
|                 key: 'delete',
>                 value: function delete(key) {
|                     var data = this.__data__;
|                     var result = data['delete'](key);
 @ ./vendor/.internal/baseClone.js 4:0-31 139:26-31
 @ ./vendor/clone.js
 @ ./src/lodash.js
 @ ./src/test.js
 @ multi ./src/test.js

ERROR in ./vendor/.internal/MapCache.js 58:32
Module parse failed: Unexpected token (58:32)
You may need an appropriate loader to handle this file type.
|         }, {
|                 key: 'delete',
>                 value: function delete(key) {
|                     var result = getMapData(this, key)['delete'](key);
|                     this.size -= result ? 1 : 0;
 @ ./vendor/.internal/SetCache.js 22:0-37 29:28-36
 @ ./vendor/.internal/baseDifference.js
 @ ./vendor/difference.js
 @ ./src/lodash.js
 @ ./src/test.js
 @ multi ./src/test.js

About reserved words, babel will add an underscore to the front, like

{
    key: 'delete',
    value: function _delete(key) {
      var result = getMapData(this, key)['delete'](key);
      this.size -= result ? 1 : 0;
      return result;
}

This project is very cool and I am looking forward to the plugin system.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.