├── .gitattributes
├── .github
└── workflows
│ ├── bench.yaml
│ ├── cli.yaml
│ └── nodejs.yaml
├── .gitignore
├── .rustfmt.toml
├── Cargo.toml
├── README.md
├── bench
├── .gitignore
├── _input
│ ├── angular.js
│ ├── antd.js
│ ├── d3.js
│ ├── jquery.js
│ ├── lodash.js
│ ├── plotly.js
│ ├── react.js
│ ├── terser.js
│ ├── three.js
│ ├── typescript.js
│ └── vue.js
├── build
├── esbuild
│ ├── .gitignore
│ ├── build
│ ├── go.mod
│ └── main.go
├── graph
├── minify-js
│ ├── .gitignore
│ ├── Cargo.toml
│ ├── build
│ └── src
│ │ └── main.rs
└── run
├── cli
├── .gitignore
├── Cargo.toml
└── src
│ └── main.rs
├── format
├── nodejs
├── .gitignore
├── .no-postinstall
├── Cargo.toml
├── index.d.ts
├── index.js
├── package.json
├── postinstall.js
└── src
│ └── lib.rs
├── notes
├── Lexical lifetimes.md
├── Name minification.md
├── Parentheses.md
└── Textual compression.md
├── rust
├── .gitignore
├── Cargo.toml
├── LICENSE
├── README.md
└── src
│ ├── emit
│ ├── mod.rs
│ └── tests
│ │ └── mod.rs
│ ├── lib.rs
│ └── minify
│ ├── advanced_if.rs
│ ├── ctx.rs
│ ├── lexical_lifetimes.rs
│ ├── mod.rs
│ ├── name.rs
│ ├── pass1.rs
│ ├── pass2.rs
│ └── pass3.rs
└── version
/.gitattributes:
--------------------------------------------------------------------------------
1 | /bench/_input/*.js linguist-vendored
2 |
--------------------------------------------------------------------------------
/.github/workflows/bench.yaml:
--------------------------------------------------------------------------------
1 | name: Run benchmark and upload results
2 |
3 | on:
4 | push:
5 | tags:
6 | - "v*"
7 | workflow_dispatch:
8 |
9 | jobs:
10 | bench:
11 | runs-on: ubuntu-20.04
12 | steps:
13 | - uses: actions/checkout@v1
14 |
15 | - name: Get version
16 | id: version
17 | shell: bash
18 | run: echo ::set-output name=VERSION::"$([[ "$GITHUB_REF" == refs/tags/v* ]] && echo ${GITHUB_REF#refs/tags/v} || echo '0.0.0')"
19 |
20 | - name: Set up Rust
21 | uses: actions-rs/toolchain@v1
22 | with:
23 | toolchain: stable
24 | profile: minimal
25 | default: true
26 |
27 | - name: Set up Go
28 | uses: actions/setup-go@v2
29 | with:
30 | go-version: "^1.14.0"
31 |
32 | - name: Install gnuplot
33 | run: sudo apt install -yqq gnuplot
34 |
35 | - name: Build bench
36 | working-directory: ./bench
37 | run: ./build
38 |
39 | - name: Set up Backblaze B2 CLI
40 | uses: wilsonzlin/setup-b2@v3
41 |
42 | - name: Run bench and upload results
43 | working-directory: ./bench
44 | run: |
45 | b2 authorize-account ${{ secrets.B2_KEY_ID }} ${{ secrets.B2_APPLICATION_KEY }}
46 | ./run
47 | ./graph
48 | b2 sync ./graphs/ b2://${{ secrets.B2_BUCKET_NAME }}/minify-js/bench/${{ steps.version.outputs.VERSION }}/
49 | b2 sync ./results/ b2://${{ secrets.B2_BUCKET_NAME }}/minify-js/bench/${{ steps.version.outputs.VERSION }}/
50 |
--------------------------------------------------------------------------------
/.github/workflows/cli.yaml:
--------------------------------------------------------------------------------
1 | name: Build and upload CLI
2 |
3 | on:
4 | push:
5 | tags:
6 | - "v*"
7 | workflow_dispatch:
8 |
9 | jobs:
10 | cli:
11 | runs-on: ${{ matrix.os }}
12 | strategy:
13 | matrix:
14 | os: [macos-11.0, ubuntu-20.04, windows-2019]
15 | include:
16 | - os: macos-11.0
17 | ARCH: macos-x86_64
18 | MIME: application/octet-stream
19 | EXT: ""
20 | - os: ubuntu-20.04
21 | ARCH: linux-x86_64
22 | MIME: application/octet-stream
23 | EXT: ""
24 | - os: windows-2019
25 | ARCH: windows-x86_64
26 | MIME: application/vnd.microsoft.portable-executable
27 | EXT: ".exe"
28 | steps:
29 | - uses: actions/checkout@v1
30 |
31 | - name: Get version
32 | id: version
33 | shell: bash
34 | run: echo ::set-output name=VERSION::"$([[ "$GITHUB_REF" == refs/tags/v* ]] && echo ${GITHUB_REF#refs/tags/v} || echo '0.0.0')"
35 |
36 | - name: Set up Rust
37 | uses: actions-rs/toolchain@v1
38 | with:
39 | toolchain: stable
40 | profile: minimal
41 | default: true
42 |
43 | - name: Build CLI
44 | working-directory: ./cli
45 | run: cargo build --release -vvv
46 |
47 | - name: Upload to B2
48 | uses: wilsonzlin/b2-upload-action@v1.0.0
49 | with:
50 | bucket: ${{ secrets.B2_BUCKET_NAME }}
51 | uploadKey: minify-js/cli/${{ steps.version.outputs.VERSION }}/${{ matrix.ARCH }}/minify-js${{ matrix.EXT }}
52 | keyId: ${{ secrets.B2_KEY_ID }}
53 | applicationKey: ${{ secrets.B2_APPLICATION_KEY }}
54 | file: ./target/release/minify-js-cli${{ matrix.EXT }}
55 | contentType: ${{ matrix.MIME }}
56 |
--------------------------------------------------------------------------------
/.github/workflows/nodejs.yaml:
--------------------------------------------------------------------------------
1 | name: Build and publish Node.js package
2 |
3 | on:
4 | push:
5 | tags:
6 | - "v*"
7 | workflow_dispatch:
8 |
9 | jobs:
10 | build:
11 | runs-on: ${{ matrix.os }}
12 | strategy:
13 | matrix:
14 | os: [macos-11.0, ubuntu-20.04, windows-2019]
15 | steps:
16 | - uses: actions/checkout@v1
17 |
18 | - name: Get version
19 | id: version
20 | shell: bash
21 | run: echo ::set-output name=VERSION::"$([[ "$GITHUB_REF" == refs/tags/v* ]] && echo ${GITHUB_REF#refs/tags/v} || echo '0.0.0')"
22 |
23 | - name: Set up Node.js
24 | if: runner.name != 'macos-arm64'
25 | uses: actions/setup-node@master
26 | with:
27 | node-version: 18.x
28 |
29 | - name: Set up Rust
30 | uses: actions-rs/toolchain@v1
31 | with:
32 | toolchain: stable
33 | profile: minimal
34 | default: true
35 |
36 | - name: Build native module
37 | working-directory: ./nodejs
38 | id: module
39 | shell: bash
40 | run: |
41 | npm install
42 | npm run build-release
43 | echo ::set-output name=BINARY_NAME::"$(node -e 'console.log([process.platform, process.arch].join("__"))')"
44 |
45 | - name: Upload to B2
46 | uses: wilsonzlin/b2-upload-action@v1.0.0
47 | with:
48 | bucket: ${{ secrets.B2_BUCKET_NAME }}
49 | uploadKey: minify-js/nodejs/${{ steps.version.outputs.VERSION }}/${{ steps.module.outputs.BINARY_NAME }}.node
50 | keyId: ${{ secrets.B2_KEY_ID }}
51 | applicationKey: ${{ secrets.B2_APPLICATION_KEY }}
52 | file: ./nodejs/index.node
53 |
54 | package:
55 | runs-on: ubuntu-20.04
56 | needs: build
57 | steps:
58 | - uses: actions/checkout@v1
59 | - name: Get version
60 | id: version
61 | shell: bash
62 | run: echo ::set-output name=VERSION::"$([[ "$GITHUB_REF" == refs/tags/v* ]] && echo ${GITHUB_REF#refs/tags/v} || echo '0.0.0')"
63 | - name: Set up Node.js
64 | uses: actions/setup-node@master
65 | with:
66 | node-version: 18.x
67 | - name: Pack and publish package
68 | working-directory: ./nodejs
69 | run: |
70 | cat << 'EOF' > .npmrc
71 | package-lock=false
72 | //registry.npmjs.org/:_authToken=${{ secrets.NPM_AUTH_TOKEN }}
73 | EOF
74 | # npm refuses to work with symlinks.
75 | cp ../README.md .
76 | if [[ "${{ steps.version.outputs.VERSION }}" != "0.0.0" ]]; then
77 | npm publish --access public
78 | fi
79 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /Cargo.lock
2 | /target/
3 |
--------------------------------------------------------------------------------
/.rustfmt.toml:
--------------------------------------------------------------------------------
1 | fn_single_line = false
2 | force_explicit_abi = true
3 | format_macro_bodies = true
4 | format_macro_matchers = true
5 | group_imports = "One"
6 | hard_tabs = false
7 | hex_literal_case = "Lower"
8 | imports_granularity = "Item"
9 | imports_layout = "Horizontal"
10 | merge_derives = true
11 | overflow_delimited_expr = true
12 | remove_nested_parens = true
13 | reorder_impl_items = true
14 | reorder_imports = true
15 | reorder_modules = true
16 | tab_spaces = 2
17 | trailing_semicolon = true
18 | use_field_init_shorthand = true
19 | wrap_comments = false
20 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [workspace]
2 | members = [
3 | "bench/minify-js",
4 | "cli",
5 | "nodejs",
6 | "rust",
7 | ]
8 |
9 | [profile.release]
10 | codegen-units = 1
11 | lto = true
12 | opt-level = 3
13 | strip = true
14 |
15 | [profile.release.package."*"]
16 | codegen-units = 1
17 | opt-level = 3
18 |
19 | [profile.release-with-debug]
20 | inherits = "release"
21 | debug = true
22 | strip = "none"
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # minify-js
2 |
3 | Extremely fast JavaScript minifier, written in Rust.
4 |
5 | ## Goals
6 |
7 | - Fully written in Rust for maximum compatibility with Rust programs and derivatives (FFI, WASM, embedded, etc.).
8 | - Maximises performance on a single CPU core for simple efficient scaling and easy compatible integration.
9 | - Minification of individual inputs/files only; no bundling or transforming.
10 | - Prefer minimal complexity and faster performance over maximum configurability and minimal extra compression.
11 |
12 | ## Performance
13 |
14 | Comparison with esbuild, run on [common libraries](./bench).
15 |
16 | 
17 |
18 | ## Features
19 |
20 | - Fast parsing powered by SIMD instructions and lookup tables.
21 | - Data is backed by a fast reusable bump allocation arena.
22 | - Supports JSX.
23 | - Analyses scopes and variable visibilities.
24 | - Minifies identifiers.
25 | - Omits semicolons, spaces, parentheses, and braces where possible.
26 | - Transforms functions to arrow functions when `new`, `this`, `arguments`, and `prototype` aren't used.
27 | - Transforms `if` statements to expressions.
28 |
29 | ## Usage
30 |
31 | ### CLI
32 |
33 | Precompiled binaries are available for Linux, macOS, and Windows.
34 |
35 | [Linux x64](https://static.wilsonl.in/minify-js/cli/0.6.0/linux-x86_64/minify-js) |
36 | [macOS x64](https://static.wilsonl.in/minify-js/cli/0.6.0/macos-x86_64/minify-js) |
37 | [Windows x64](https://static.wilsonl.in/minify-js/cli/0.6.0/windows-x86_64/minify-js.exe)
38 |
39 | Use the `--help` argument for more details.
40 |
41 | ```bash
42 | minify-js --output /path/to/output.min.js /path/to/src.js
43 | ```
44 |
45 | ### Rust
46 |
47 | Add the dependency:
48 |
49 | ```toml
50 | [dependencies]
51 | minify-js = "0.6.0"
52 | ```
53 |
54 | Call the method:
55 |
56 | ```rust
57 | use minify_js::{Session, TopLevelMode, minify};
58 |
59 | let mut code: &[u8] = b"const main = () => { let my_first_variable = 1; };";
60 | let session = Session::new();
61 | let mut out = Vec::new();
62 | minify(&session, TopLevelMode::Global, code, &mut out).unwrap();
63 | assert_eq!(out.as_slice(), b"const main=()=>{let a=1}");
64 | ```
65 |
66 | ### Node.js
67 |
68 | Install the dependency:
69 |
70 | ```bash
71 | npm i @minify-js/node
72 | ```
73 |
74 | Call the method:
75 |
76 | ```typescript
77 | import {minify} from "@minify-js/node";
78 |
79 | const src = Buffer.from("let x = 1;", "utf-8");
80 | const min = minify(src);
81 | ```
82 |
83 | ## In progress
84 |
85 | - Combine and reorder declarations.
86 | - Evaluation and folding of constant expressions.
87 | - Parse and erase TypeScript syntax.
88 | - Removal of unreachable, unused, and redundant code.
89 | - Inlining single-use declarations.
90 | - Replacing if statements with conditional and logical expressions.
91 | - Returning an explicit error on illegal code e.g. multiple declarations/exports with identical names.
92 | - Much more inline, high level, and usage documentation.
93 | - Support import and export string names e.g. `import { "a-b" as "c-d" } from "x"`.
94 | - Simplify pattern parsing and minification.
95 | - Micro-optimisations:
96 | - Unwrap string literal computed members, then identifier or number string members.
97 | - Replace `x === null || x === undefined` with `x == null`, where `x` is side-effect free.
98 | - Replace `typeof x === "undefined"` with `x === undefined`.
99 | - Using shorthand properties.
100 | - Replace `void x` with `x, undefined`.
101 | - Replace `return undefined` with `return`.
102 | - Replace `const` with `let`.
103 | - Hoist `let` and `const`.
104 | - Unwrapping blocks.
105 | - Unwrapping paretheses, altering expressions as necessary.
106 | - `if (...) return a; else if (...) return b; else return c` => `return (...) ? a : (...) ? b : c`.
107 |
--------------------------------------------------------------------------------
/bench/.gitignore:
--------------------------------------------------------------------------------
1 | /graphs/
2 | /results/
3 |
--------------------------------------------------------------------------------
/bench/build:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | set -Eeuo pipefail
4 |
5 | shopt -s nullglob
6 |
7 | pushd "$(dirname "$0")" >/dev/null
8 |
9 | for candidate in esbuild minify-js; do
10 | echo "$candidate"
11 | "./$candidate/build"
12 | done
13 |
14 | popd >/dev/null
15 |
--------------------------------------------------------------------------------
/bench/esbuild/.gitignore:
--------------------------------------------------------------------------------
1 | /go.sum
2 | /run
3 |
--------------------------------------------------------------------------------
/bench/esbuild/build:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | set -Eeuo pipefail
4 |
5 | pushd "$(dirname "$0")" >/dev/null
6 |
7 | go mod tidy
8 | go mod download
9 | go build -o run
10 |
11 | popd >/dev/null
12 |
--------------------------------------------------------------------------------
/bench/esbuild/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/wilsonzlin/minify-js/bench/esbuild
2 |
3 | go 1.18
4 |
5 | require github.com/evanw/esbuild v0.14.46
6 |
7 | require golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365 // indirect
8 |
--------------------------------------------------------------------------------
/bench/esbuild/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io/ioutil"
6 | "os"
7 | "runtime"
8 | "strconv"
9 | "time"
10 |
11 | "github.com/evanw/esbuild/pkg/api"
12 | )
13 |
14 | func main() {
15 | runtime.GOMAXPROCS(1)
16 |
17 | filePath := os.Args[1]
18 | input, err := ioutil.ReadFile(filePath)
19 | if err != nil {
20 | panic(err)
21 | }
22 |
23 | iterations, err := strconv.ParseUint(os.Args[2], 10, 64)
24 | if err != nil {
25 | panic(err)
26 | }
27 |
28 | start := time.Now()
29 | var output_len int
30 | for i := uint64(0); i < iterations; i++ {
31 | result := api.Transform(string(input), api.TransformOptions{
32 | LegalComments: api.LegalCommentsNone,
33 | Loader: api.LoaderJS,
34 | LogLevel: api.LogLevelError,
35 | MinifyIdentifiers: true,
36 | MinifySyntax: true,
37 | MinifyWhitespace: true,
38 | Sourcemap: api.SourceMapNone,
39 | TreeShaking: api.TreeShakingTrue,
40 | })
41 |
42 | if len(result.Errors) != 0 {
43 | panic(result.Errors[0])
44 | }
45 |
46 | output_len = len(result.Code)
47 | }
48 | elapsed_ns := time.Since(start).Nanoseconds()
49 | fmt.Printf("%d %d\n", output_len, elapsed_ns)
50 | }
51 |
--------------------------------------------------------------------------------
/bench/graph:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | set -Eeuxo pipefail
4 |
5 | pushd "$(dirname "$0")" >/dev/null
6 |
7 | rm -rf graphs
8 | mkdir graphs
9 |
10 | gnuplot << 'EOD'
11 | set terminal svg enhanced background rgb "white"
12 | set output "graphs/average-sizes.svg"
13 |
14 | set title font "Arial,18"
15 | set title "Average minified size"
16 | set key off
17 | set xtics font "Arial,14"
18 | set format y "%g%%"
19 |
20 | set style fill solid
21 | set boxwidth 0.5 relative
22 | set yrange [0:*]
23 |
24 | set linetype 1 lc rgb "#bcbcbc"
25 | set linetype 2 lc rgb "#2e61bd"
26 | plot "results/average-sizes.txt" u 1:3:($1+1):xtic(2) with boxes linecolor variable
27 | EOD
28 |
29 | gnuplot << 'EOD'
30 | set terminal svg enhanced background rgb "white"
31 | set output "graphs/total-times.svg"
32 |
33 | set title font "Arial,18"
34 | set title "Total minification time"
35 | set key off
36 | set xtics font "Arial,14"
37 | set format y "%g s"
38 | set yrange [0:*]
39 |
40 | set style fill solid
41 | set boxwidth 0.5 relative
42 |
43 | set linetype 1 lc rgb "#bcbcbc"
44 | set linetype 2 lc rgb "#2e61bd"
45 | plot "results/total-times.txt" u 1:3:($1+1):xtic(2) with boxes linecolor variable
46 | EOD
47 |
48 | popd >/dev/null
49 |
--------------------------------------------------------------------------------
/bench/minify-js/.gitignore:
--------------------------------------------------------------------------------
1 | /Cargo.lock
2 | /run
3 | /target/
4 |
--------------------------------------------------------------------------------
/bench/minify-js/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "minify-js-bench"
3 | publish = false
4 | version = "0.0.1"
5 | edition = "2021"
6 |
7 | [dependencies]
8 | minify-js = { path = "../../rust" }
9 |
--------------------------------------------------------------------------------
/bench/minify-js/build:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | set -Eeuo pipefail
4 |
5 | pushd "$(dirname "$0")" >/dev/null
6 |
7 | bin_path="$(cargo build --profile release-with-debug --message-format=json | jq -r '.executable | select(. != null)')"
8 | ln -fsv "$bin_path" ./run
9 |
10 | popd >/dev/null
11 |
--------------------------------------------------------------------------------
/bench/minify-js/src/main.rs:
--------------------------------------------------------------------------------
1 | use minify_js::minify;
2 | use minify_js::Session;
3 | use minify_js::TopLevelMode;
4 | use std::env;
5 | use std::fs::File;
6 | use std::io::Read;
7 | use std::time::Instant;
8 |
9 | fn main() {
10 | let args: Vec = env::args().collect();
11 | let mut code = Vec::new();
12 | File::open(&args[1])
13 | .expect("open file")
14 | .read_to_end(&mut code)
15 | .expect("read file");
16 |
17 | let iterations = u64::from_str_radix(&args[2], 10).expect("parse iterations argument");
18 | let mut output_len = 0;
19 | let mut output = Vec::new();
20 | let started = Instant::now();
21 | let session = Session::new();
22 | for _ in 0..iterations {
23 | output.clear();
24 | minify(&session, TopLevelMode::Global, &code, &mut output).expect("minify");
25 | output_len = output.len();
26 | }
27 | let elapsed_ns = started.elapsed().as_nanos();
28 |
29 | println!("{} {}", output_len, elapsed_ns);
30 | }
31 |
--------------------------------------------------------------------------------
/bench/run:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | set -Eeuo pipefail
4 |
5 | shopt -s nullglob
6 |
7 | pushd "$(dirname "$0")" >/dev/null
8 |
9 | candidates=('esbuild' 'minify-js')
10 | candidate_output_min_lens=(0 0)
11 | candidate_output_times=(0 0)
12 | inputs=(_input/*)
13 | src_len_sum=0
14 |
15 | for input in ${inputs[@]}; do
16 | src_len=$(wc -c < "$PWD/$input")
17 | src_len_sum=$(( src_len_sum + src_len ))
18 | done
19 |
20 | for candidate_idx in ${!candidates[@]}; do
21 | candidate=${candidates[$candidate_idx]}
22 | for input in ${inputs[@]}; do
23 | raw=$("./$candidate/run" "$PWD/$input" 10)
24 | res=($raw)
25 | min_len=${res[0]}
26 | time_ns=${res[1]}
27 | candidate_output_min_lens[$candidate_idx]=$(( candidate_output_min_lens[candidate_idx] + min_len ))
28 | candidate_output_times[$candidate_idx]=$(( candidate_output_times[candidate_idx] + time_ns ))
29 | done
30 | done
31 |
32 | rm -rf results
33 | mkdir results
34 | for candidate_idx in ${!candidates[@]}; do
35 | candidate=${candidates[$candidate_idx]}
36 |
37 | min_len_sum=${candidate_output_min_lens[$candidate_idx]}
38 | avg_min_pct=$(bc -l <<< "($min_len_sum/$src_len_sum) * 100")
39 | echo -e "$candidate_idx\t$candidate\t$avg_min_pct" >> results/average-sizes.txt
40 |
41 | time_ns_sum=${candidate_output_times[$candidate_idx]}
42 | time_sec_sum=$(bc -l <<< "$time_ns_sum / 1000000000")
43 | echo -e "$candidate_idx\t$candidate\t$time_sec_sum" >> results/total-times.txt
44 | done
45 |
46 | popd >/dev/null
47 |
--------------------------------------------------------------------------------
/cli/.gitignore:
--------------------------------------------------------------------------------
1 | /Cargo.lock
2 | /target/
3 |
--------------------------------------------------------------------------------
/cli/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | authors = ["Wilson Lin "]
3 | description = "Extremely fast JS minifier"
4 | edition = "2021"
5 | name = "minify-js-cli"
6 | publish = false
7 | version = "0.6.0"
8 |
9 | [dependencies]
10 | minify-js = { path = "../rust" }
11 | structopt = "0.3"
12 |
--------------------------------------------------------------------------------
/cli/src/main.rs:
--------------------------------------------------------------------------------
1 | use minify_js::minify;
2 | use minify_js::Session;
3 | use minify_js::TopLevelMode;
4 | use std::fs::File;
5 | use std::io::stdin;
6 | use std::io::stdout;
7 | use std::io::Read;
8 | use std::io::Write;
9 | use structopt::StructOpt;
10 |
11 | #[derive(StructOpt)]
12 | #[structopt(name = "minify-js", about = "Extremely fast JS minifier")]
13 | // WARNING: Keep descriptions in sync with Cfg.
14 | struct Cli {
15 | /// File to minify; omit for stdin.
16 | #[structopt(parse(from_os_str))]
17 | input: Option,
18 |
19 | /// Output destination; omit for stdout.
20 | #[structopt(short, long, parse(from_os_str))]
21 | output: Option,
22 |
23 | /// Whether file is a module or global script.
24 | #[structopt(short, long)]
25 | mode: TopLevelMode,
26 | }
27 |
28 | fn main() {
29 | let args = Cli::from_args();
30 | let mut input = Vec::new();
31 | let mut input_file: Box = match args.input {
32 | Some(p) => Box::new(File::open(p).expect("open input file")),
33 | None => Box::new(stdin()),
34 | };
35 | input_file.read_to_end(&mut input).expect("read input");
36 | let mut output = Vec::new();
37 | let session = Session::new();
38 | minify(&session, args.mode, &input, &mut output).expect("minify");
39 | match args.output {
40 | Some(p) => File::create(p)
41 | .expect("open output file")
42 | .write_all(&output),
43 | None => stdout().write_all(&output),
44 | }
45 | .expect("write output");
46 | }
47 |
--------------------------------------------------------------------------------
/format:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | set -Eeuxo pipefail
4 |
5 | pushd "$(dirname "$0")" >/dev/null
6 |
7 | npx prettier@2.3.2 -w 'version' '.github/**/*.yaml' 'nodejs/*.{js,json,ts}'
8 |
9 | cargo +nightly fmt
10 |
11 | popd >/dev/null
12 |
--------------------------------------------------------------------------------
/nodejs/.gitignore:
--------------------------------------------------------------------------------
1 | /Cargo.lock
2 | /index.node
3 | /package-lock.json
4 | /target/
5 | node_modules/
6 | npm-debug.log*
7 |
--------------------------------------------------------------------------------
/nodejs/.no-postinstall:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wilsonzlin/minify-js/77dae36c6e0a0f068ffd5c55ccc57c207c8cc017/nodejs/.no-postinstall
--------------------------------------------------------------------------------
/nodejs/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "minify-js-node"
3 | publish = false
4 | version = "0.6.0"
5 | description = "Node.js bindings for minify-js"
6 | authors = ["Wilson Lin "]
7 | edition = "2021"
8 |
9 | [lib]
10 | crate-type = ["cdylib"]
11 |
12 | [dependencies]
13 | minify-js = { version = "0.6.0", path = "../rust" }
14 |
15 | [dependencies.neon]
16 | version = "0.10"
17 | default-features = false
18 | features = ["napi-1"]
19 |
--------------------------------------------------------------------------------
/nodejs/index.d.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Minifies a Buffer containing UTF-8 JavaScript code.
3 | *
4 | * @param src - Source JS code
5 | * @returns Minified JS code
6 | */
7 | export function minify(topLevelType: "global" | "module", src: Buffer): Buffer;
8 |
--------------------------------------------------------------------------------
/nodejs/index.js:
--------------------------------------------------------------------------------
1 | // This wrapper file exists to allow importing from ESM contexts, as Node.js does not allow importing ".node" modules directly from ESM.
2 |
3 | module.exports = require("./index.node");
4 |
--------------------------------------------------------------------------------
/nodejs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@minify-js/node",
3 | "description": "Extremely fast JavaScript minifier, written in Rust",
4 | "main": "index.js",
5 | "files": [
6 | "src/**",
7 | "Cargo.toml",
8 | "index.d.ts",
9 | "index.js",
10 | "README.md",
11 | "postinstall.js"
12 | ],
13 | "version": "0.6.0",
14 | "types": "index.d.ts",
15 | "scripts": {
16 | "build": "cargo-cp-artifact --artifact cdylib minify-js-node index.node -- cargo build --message-format=json-render-diagnostics",
17 | "build-debug": "npm run build --",
18 | "build-release": "npm run build -- --release",
19 | "clean": "shx rm -rf target index.node",
20 | "postinstall": "node postinstall.js"
21 | },
22 | "repository": {
23 | "type": "git",
24 | "url": "git+https://github.com/wilsonzlin/minify-js.git"
25 | },
26 | "author": {
27 | "email": "npm@wilsonl.in",
28 | "name": "Wilson Lin",
29 | "url": "https://wilsonl.in/"
30 | },
31 | "license": "MIT",
32 | "bugs": {
33 | "url": "https://github.com/wilsonzlin/minify-js/issues"
34 | },
35 | "engines": {
36 | "node": ">= 8.6.0"
37 | },
38 | "homepage": "https://github.com/wilsonzlin/minify-js#readme",
39 | "dependencies": {
40 | "cargo-cp-artifact": "^0.1"
41 | },
42 | "devDependencies": {
43 | "@types/node": "^14.6.0",
44 | "shx": "^0.3.4"
45 | },
46 | "keywords": [
47 | "compress",
48 | "compressor",
49 | "ecmascript",
50 | "fast",
51 | "javascript",
52 | "js",
53 | "minifier",
54 | "minify"
55 | ]
56 | }
57 |
--------------------------------------------------------------------------------
/nodejs/postinstall.js:
--------------------------------------------------------------------------------
1 | const fs = require("fs");
2 | const https = require("https");
3 | const path = require("path");
4 | const pkg = require("./package.json");
5 | const cp = require("child_process");
6 |
7 | const MAX_DOWNLOAD_ATTEMPTS = 4;
8 |
9 | const binaryName = [process.platform, process.arch].join("__");
10 | const binaryPath = path.join(__dirname, "index.node");
11 |
12 | const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
13 |
14 | class StatusError extends Error {
15 | constructor(status) {
16 | super(`Bad status of ${status}`);
17 | this.status = status;
18 | }
19 | }
20 |
21 | const fetch = (url) =>
22 | new Promise((resolve, reject) => {
23 | const stream = https.get(url, (resp) => {
24 | if (!resp.statusCode || resp.statusCode < 200 || resp.statusCode > 299) {
25 | return reject(new StatusError(resp.statusCode));
26 | }
27 | const parts = [];
28 | resp.on("data", (chunk) => parts.push(chunk));
29 | resp.on("end", () => resolve(Buffer.concat(parts)));
30 | });
31 | stream.on("error", reject);
32 | });
33 |
34 | const downloadNativeBinary = async () => {
35 | for (let attempt = 0; ; attempt++) {
36 | let binary;
37 | try {
38 | binary = await fetch(
39 | `https://static.wilsonl.in/minify-js/nodejs/${pkg.version}/${binaryName}.node`
40 | );
41 | } catch (e) {
42 | if (
43 | e instanceof StatusError &&
44 | e.status !== 404 &&
45 | attempt < MAX_DOWNLOAD_ATTEMPTS
46 | ) {
47 | await wait(Math.random() * 2500 + 500);
48 | continue;
49 | }
50 | throw e;
51 | }
52 |
53 | fs.writeFileSync(binaryPath, binary);
54 | break;
55 | }
56 | };
57 |
58 | if (
59 | !fs.existsSync(path.join(__dirname, ".no-postinstall")) &&
60 | !fs.existsSync(binaryPath)
61 | ) {
62 | downloadNativeBinary().then(
63 | () => console.log(`Downloaded ${pkg.name}`),
64 | (err) => {
65 | console.error(
66 | `Failed to download ${pkg.name}, will build from source: ${err}`
67 | );
68 | const out = cp.spawnSync("npm", ["run", "build-release"], {
69 | cwd: __dirname,
70 | stdio: ["ignore", "inherit", "inherit"],
71 | });
72 | process.exitCode = out.exitCode;
73 | if (out.error) {
74 | throw out.error;
75 | }
76 | }
77 | );
78 | }
79 |
--------------------------------------------------------------------------------
/nodejs/src/lib.rs:
--------------------------------------------------------------------------------
1 | use minify_js::Session;
2 | use neon::prelude::*;
3 | use neon::types::buffer::TypedArray;
4 | use std::str::FromStr;
5 |
6 | fn minify(mut cx: FunctionContext) -> JsResult {
7 | let top_level_mode_raw = cx.argument::(0).map(|v| v.value(&mut cx))?;
8 | let top_level_mode = match minify_js::TopLevelMode::from_str(&top_level_mode_raw) {
9 | Ok(m) => m,
10 | Err(_) => return cx.throw_type_error("invalid top-level mode"),
11 | };
12 | let src = cx.argument::(1)?;
13 | let mut out = Vec::new();
14 | // TODO Allow reuse by creating a JS function that creates a native object.
15 | let session = Session::new();
16 | let res = match minify_js::minify(&session, top_level_mode, src.as_slice(&mut cx), &mut out) {
17 | Ok(()) => Ok(JsBuffer::external(&mut cx, out)),
18 | // We can't call `cx.throw_error` here as `cx` is already borrowed, so we create the error string and then throw later.
19 | Err(err) => Err(format!("{:?}", err)),
20 | };
21 | match res {
22 | Ok(res) => Ok(res),
23 | Err(msg) => cx.throw_error(msg),
24 | }
25 | }
26 |
27 | #[neon::main]
28 | fn main(mut cx: ModuleContext) -> NeonResult<()> {
29 | cx.export_function("minify", minify)?;
30 | Ok(())
31 | }
32 |
--------------------------------------------------------------------------------
/notes/Lexical lifetimes.md:
--------------------------------------------------------------------------------
1 | # Lexical lifetimes
2 |
3 | - Assignments are like new variables that already optimally reuse a variable slot.
4 | - It's why we're trying to analyse lifetimes: so we can reduce the amount of var decls. In the same way, the reverse is true.
5 | - This is useful for loops, as their lifetime is related to their assignment (whereas others only care about uses). If the first assignment (not declaration, as it could be declared outside but not used outside) is inside the loop and before any use, then it is local to the loop. Otherwise, we may incorrectly assume lifetime ends within loop and assign its var to something else, cobbling the value between iterations.
6 | - If the first appearance isn't an unconditional assignment, it means it depends on a value from some previous iteration or before the loop or a nested `if`/`for`/etc. If it is, then we can safely reuse its assigned variable and clobber any existing value because it won't care what it is anyway.
7 | - Therefore, if the first appearance isn't assignment, make its lifetime end after the loop, no matter where it appears last in the loop. Obviously if it appears after the loop then none of this applies.
8 | - This also detects pointless unused assignments.
9 |
10 | - Assignments except `=` (e.g. `+=`, `??=`) are usages first and then assignments second (and then usages again). `=` are assignments first and then usages second (but the RHS may reference the variable as a usage).
11 | - Handle destructuring carefully. Destructuring may be pointless if we end up minifying names as we're unlikely to be able to use shorthands. Therefore, it may be optimal to transform destructurings into multiple individual assignments, which would also give opportunities to split them into hoistable var decls and assignment expressions.
12 | - Usages from nested closures count as infinite lifetime. This includes classes, as even class property initialisations re-evaluate the variable on each constructor call.
13 |
14 | ```js
15 | var {foo: [bar, {baz}]} = obj;
16 | // Name minification only:
17 | var {foo: [a, {baz: b}]} = obj;
18 | // Unpacked:
19 | var a = obj.foo,
20 | b = a[0],
21 | c = a[1],
22 | d = c.baz;
23 | ```
24 |
25 | When branching, if a lifetime starts and/or ends in a branch, then optimal minimum set of groups is different per branch. However, this is quite tricky to code for. Consider that the optimal algorithm is global, but we're only allowed to modify the parts of the solution within the branch; everything else must remain locked in. Therefore, for simplicity, we'll just use the maximum lifetime value of all branches for a symbol, which is not optimal but good enough.
26 |
27 | Lifetime values have no meaning by themselves; they are only useful when compared to other values.
28 |
29 | - For each symbol assignment (IdentifierPattern), incr top of stack and start new lifetime on symbol if existing lifetime end is before.
30 | - For each symbol usage (IdentifierExpr) not in a loop, incr top of stack.
31 | - For each symbol usage (IdentifierExpr) in a loop, check current lifetime's end:
32 | - If same level, it means there was an unconditional assignment in the same loop somewhere before. Incr top of stack.
33 | - Otherwise, don't modify stack, and instead use the current loop's end lifetime as its lifetime.
34 | - For each conditional, incr top of stack. For each branch, push stack 0.
35 | - For each loop, incr top of stack. Before entering, push stack 0. Mark as in loop. After exiting, incr top of stack again. Therefore, a loop has two lifetime values: start and end.
36 |
37 | ```js
38 | function foo() {
39 | var a, b = f(a), c = 2;
40 |
41 | a = 1;
42 | f(a);
43 |
44 | if (true) {
45 | let d = 1;
46 | a = 2;
47 | var e = 2;
48 | } else {
49 | a = 4;
50 | e = 3;
51 | }
52 |
53 | if (true) {
54 | e = 4;
55 | return;
56 | }
57 | f(e);
58 |
59 | for (;;) {
60 | var x = 2;
61 | a = a + 1;
62 | b++;
63 | c = 2;
64 | }
65 |
66 | f(b);
67 | }
68 | ```
69 |
70 | ```js
71 | // Example of how assignments start new lifetimes.
72 | var a, b;
73 |
74 | a = a + (b = 2 * 4) // Lifetimes don't overlap, can technically become `a = a + (a = 2 * 4)`.
75 |
76 | a = (b = 2 * 4) + a // Lifetimes overlap, can't be reduced to one (unless we do nifty optimisations around reordering).
77 | ```
78 |
79 | ```js
80 | // Example of how assignments start lifetimes. If not, this `x` would have unnecessarily long lifetime.
81 | x = 1;
82 | foo();
83 | bar();
84 | baz();
85 | x = 2;
86 | ```
87 |
88 | ```js
89 | // Mental puzzle.
90 | if (foo) {
91 | for (;;) {
92 | if (bar) {
93 | for (;;) {
94 | x = 1;
95 | }
96 | x = 1;
97 | }
98 | x = 1;
99 | }
100 | x = 1;
101 | }
102 | ```
103 |
104 | ```js
105 | // Example of how usages in nested closures are unknowable and so must be infinite.
106 | var x = 1;
107 | (() => {
108 | if (Math.random() < 0.5) {
109 | x = 2;
110 | } else {
111 | setInterval(() => {
112 | x++;
113 | }, 1000);
114 | }
115 | })();
116 | var y = 2;
117 | ```
118 |
--------------------------------------------------------------------------------
/notes/Name minification.md:
--------------------------------------------------------------------------------
1 | # Name minification
2 |
3 | ## Algorithm
4 |
5 | - For each symbol usage:
6 | - For each scope starting from the current up to and including the top-most:
7 | - If symbol is declared in the scope, break.
8 | - Mark symbol as inherited on the scope.
9 |
10 | ### Clear example
11 |
12 | ```js
13 | // Inherited: bar, baz, top0, top1, top2.
14 | let foo;
15 | foo; bar; baz; top0;
16 | {
17 | // Inherited: foo, baz, top1, top2.
18 | let bar;
19 | foo; bar; baz; top1;
20 | {
21 | // Inherited: foo, bar, top2.
22 | let baz;
23 | foo; bar; baz; top2;
24 | }
25 | }
26 | ```
27 |
28 | ### More obfusicated example
29 |
30 | ```js
31 | // Inherited: e, d, c, b, a.
32 | let f;
33 | f; e; d; c;
34 | {
35 | // Inherited: f, d, b, a.
36 | let e;
37 | f; e; d; b;
38 | {
39 | // Inherited: f, e, a.
40 | let d;
41 | f; e; d; a;
42 | }
43 | }
44 | ```
45 |
--------------------------------------------------------------------------------
/notes/Parentheses.md:
--------------------------------------------------------------------------------
1 | # Parentheses
2 |
3 | ## When are parentheses needed outside of standard operator precedence rules?
4 |
5 | ### When a comma would not be interpreted as a comma expression
6 |
7 | - Call arguments: `fn(a, (1, 2))`.
8 | - Variable intialisers: `let x = 1, y = (2, 3), z = 4`.
9 | - Return expression of arrow function (because it has lower precedence): `() => (1, 2)`.
10 | - Array and object literals: `[1, (2, 3)]`, `{a: 1, b: (2, 3)}`.
11 |
12 | ### When an expression would be misinterpreted as a statement
13 |
14 | - Object destructuring without declaration or literal (misinterpreted as block): `({prop1: var1, prop2: [var2, var3]} = {})`, `() => ({a: 1})`.
15 | - Function expression (misinterpreted as declaration, which has ramifications on IIFE and visibility): `(function decl() {})()`.
16 |
--------------------------------------------------------------------------------
/notes/Textual compression.md:
--------------------------------------------------------------------------------
1 | # Textual compression
2 |
3 | We do not perform any textual compression:
4 |
5 | - They make minification much more expensive and complex.
6 | - They have a runtime cost due to indirection and escaping engine optimisations.
7 | - They almost always worsen compression (e.g. gzip, Brotli) and those algorithms already perform the same functionality.
8 | - They pollute the scope and increase the amount of variables, which can reduce name minification effectiveness.
9 | - They are tricky to get correct, since they often (can) alter symbols and execution stacks and orders.
10 |
11 | Some forms include:
12 |
13 | - Aliasing of reused well-knowns.
14 | - Aliasing repeated identical literal values.
15 | - Aliasing frequently accessed properties and called methods.
16 | - Using Object.assign.
17 | - Replacing `typeof` and `instanceof` with functions.
18 | - Replacing common statement patterns with helper functions.
19 |
20 | Aliasing repeated constants (including built-in variables and properties) was dropped in commit [ff48b8b](https://github.com/wilsonzlin/minify-js/commit/ff48b8b).
21 |
--------------------------------------------------------------------------------
/rust/.gitignore:
--------------------------------------------------------------------------------
1 | /Cargo.lock
2 | /target/
3 |
--------------------------------------------------------------------------------
/rust/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | authors = ["Wilson Lin "]
3 | categories = ["compression", "command-line-utilities", "development-tools::build-utils", "web-programming"]
4 | description = "Extremely fast JavaScript minifier"
5 | edition = "2021"
6 | homepage = "https://github.com/wilsonzlin/minify-js"
7 | include = ["/src/**/*", "/Cargo.toml", "/LICENSE", "/README.md"]
8 | keywords = ["javascript", "compress", "minifier", "js", "ecmascript"]
9 | license = "Apache-2.0"
10 | name = "minify-js"
11 | readme = "README.md"
12 | repository = "https://github.com/wilsonzlin/minify-js"
13 | version = "0.6.0"
14 |
15 | [dependencies]
16 | aho-corasick = "0.7"
17 | lazy_static = "1.4"
18 | parse-js = "0.21"
19 |
20 | [features]
21 | serialize = ["parse-js/serialize"]
22 |
--------------------------------------------------------------------------------
/rust/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
--------------------------------------------------------------------------------
/rust/README.md:
--------------------------------------------------------------------------------
1 | ../README.md
--------------------------------------------------------------------------------
/rust/src/emit/mod.rs:
--------------------------------------------------------------------------------
1 | use aho_corasick::AhoCorasick;
2 | use lazy_static::lazy_static;
3 | use parse_js::ast::ArrayElement;
4 | use parse_js::ast::ClassMember;
5 | use parse_js::ast::ClassOrObjectMemberKey;
6 | use parse_js::ast::ClassOrObjectMemberValue;
7 | use parse_js::ast::ExportNames;
8 | use parse_js::ast::ForInOfStmtHeaderLhs;
9 | use parse_js::ast::ForStmtHeader;
10 | use parse_js::ast::ForThreeInit;
11 | use parse_js::ast::LiteralTemplatePart;
12 | use parse_js::ast::NodeData;
13 | use parse_js::ast::ObjectMemberType;
14 | use parse_js::ast::Syntax;
15 | use parse_js::ast::VarDeclMode;
16 | use parse_js::operator::OperatorName;
17 | use parse_js::operator::OPERATORS;
18 | use parse_js::session::SessionVec;
19 | use std::collections::HashMap;
20 | use std::io::Write;
21 |
22 | #[cfg(test)]
23 | mod tests;
24 |
25 | lazy_static! {
26 | pub static ref BINARY_OPERATOR_SYNTAX: HashMap = {
27 | let mut map = HashMap::::new();
28 | // Excluded: Call, Conditional.
29 | map.insert(OperatorName::Addition, "+");
30 | map.insert(OperatorName::Assignment, "=");
31 | map.insert(OperatorName::AssignmentAddition, "+=");
32 | map.insert(OperatorName::AssignmentBitwiseAnd, "&=");
33 | map.insert(OperatorName::AssignmentBitwiseLeftShift, "<<=");
34 | map.insert(OperatorName::AssignmentBitwiseOr, "|=");
35 | map.insert(OperatorName::AssignmentBitwiseRightShift, ">>=");
36 | map.insert(OperatorName::AssignmentBitwiseUnsignedRightShift, ">>>=");
37 | map.insert(OperatorName::AssignmentBitwiseXor, "^=");
38 | map.insert(OperatorName::AssignmentDivision, "/=");
39 | map.insert(OperatorName::AssignmentExponentiation, "**=");
40 | map.insert(OperatorName::AssignmentLogicalAnd, "&&=");
41 | map.insert(OperatorName::AssignmentLogicalOr, "||=");
42 | map.insert(OperatorName::AssignmentMultiplication, "*=");
43 | map.insert(OperatorName::AssignmentNullishCoalescing, "??=");
44 | map.insert(OperatorName::AssignmentRemainder, "%=");
45 | map.insert(OperatorName::AssignmentSubtraction, "-=");
46 | map.insert(OperatorName::BitwiseAnd, "&");
47 | map.insert(OperatorName::BitwiseLeftShift, "<<");
48 | map.insert(OperatorName::BitwiseOr, "|");
49 | map.insert(OperatorName::BitwiseRightShift, ">>");
50 | map.insert(OperatorName::BitwiseUnsignedRightShift, ">>>");
51 | map.insert(OperatorName::BitwiseXor, "^");
52 | map.insert(OperatorName::Comma, ",");
53 | map.insert(OperatorName::Division, "/");
54 | map.insert(OperatorName::Equality, "==");
55 | map.insert(OperatorName::Exponentiation, "**");
56 | map.insert(OperatorName::GreaterThan, ">");
57 | map.insert(OperatorName::GreaterThanOrEqual, ">=");
58 | map.insert(OperatorName::In, " in ");
59 | map.insert(OperatorName::Inequality, "!=");
60 | map.insert(OperatorName::Instanceof, " instanceof ");
61 | map.insert(OperatorName::LessThan, "<");
62 | map.insert(OperatorName::LessThanOrEqual, "<=");
63 | map.insert(OperatorName::LogicalAnd, "&&");
64 | map.insert(OperatorName::LogicalOr, "||");
65 | map.insert(OperatorName::MemberAccess, ".");
66 | map.insert(OperatorName::Multiplication, "*");
67 | map.insert(OperatorName::NullishCoalescing, "??");
68 | map.insert(OperatorName::OptionalChainingMemberAccess, "?.");
69 | map.insert(OperatorName::OptionalChainingComputedMemberAccess, "?.[");
70 | map.insert(OperatorName::OptionalChainingCall, "?.(");
71 | map.insert(OperatorName::Remainder, "%");
72 | map.insert(OperatorName::StrictEquality, "===");
73 | map.insert(OperatorName::StrictInequality, "!==");
74 | map.insert(OperatorName::Subtraction, "-");
75 | map.insert(OperatorName::Typeof, " typeof ");
76 | map
77 | };
78 |
79 | pub static ref UNARY_OPERATOR_SYNTAX: HashMap = {
80 | let mut map = HashMap::::new();
81 | // Excluded: Postfix{Increment,Decrement}.
82 | map.insert(OperatorName::Await, "await ");
83 | map.insert(OperatorName::BitwiseNot, "~");
84 | map.insert(OperatorName::Delete, "delete ");
85 | map.insert(OperatorName::LogicalNot, "!");
86 | map.insert(OperatorName::New, "new ");
87 | map.insert(OperatorName::PrefixDecrement, "--");
88 | map.insert(OperatorName::PrefixIncrement, "++");
89 | map.insert(OperatorName::Typeof, "typeof ");
90 | map.insert(OperatorName::UnaryNegation, "-");
91 | map.insert(OperatorName::UnaryPlus, "+");
92 | map.insert(OperatorName::Void, "void ");
93 | map.insert(OperatorName::Yield, "yield ");
94 | map.insert(OperatorName::YieldDelegated, "yield*");
95 | map
96 | };
97 |
98 | static ref TEMPLATE_LITERAL_ESCAPE_MAT: AhoCorasick = AhoCorasick::new(&[
99 | b"\\",
100 | b"`",
101 | b"$",
102 | ]);
103 | }
104 |
105 | const TEMPLATE_LITERAL_ESCAPE_REP: &[&[u8]] = &[b"\\\\", b"\\`", b"\\$"];
106 |
107 | // Returns whether or not the value is a property.
108 | fn emit_class_or_object_member<'a>(
109 | out: &mut Vec,
110 | key: &'a ClassOrObjectMemberKey,
111 | value: &'a ClassOrObjectMemberValue,
112 | value_delimiter: &'static [u8],
113 | ) -> bool {
114 | let is_computed_key = match key {
115 | ClassOrObjectMemberKey::Computed(_) => true,
116 | _ => false,
117 | };
118 | match value {
119 | ClassOrObjectMemberValue::Getter { .. } => {
120 | out.extend_from_slice(b"get");
121 | if !is_computed_key {
122 | out.extend_from_slice(b" ");
123 | };
124 | }
125 | ClassOrObjectMemberValue::Setter { .. } => {
126 | out.extend_from_slice(b"set");
127 | if !is_computed_key {
128 | out.extend_from_slice(b" ");
129 | };
130 | }
131 | ClassOrObjectMemberValue::Method {
132 | is_async,
133 | generator,
134 | ..
135 | } => {
136 | if *is_async {
137 | out.extend_from_slice(b"async");
138 | }
139 | if *generator {
140 | out.extend_from_slice(b"*");
141 | } else if *is_async {
142 | out.extend_from_slice(b" ");
143 | }
144 | }
145 | _ => {}
146 | };
147 | match key {
148 | ClassOrObjectMemberKey::Direct(name) => {
149 | out.extend_from_slice(name.as_slice());
150 | }
151 | ClassOrObjectMemberKey::Computed(expr) => {
152 | out.extend_from_slice(b"[");
153 | emit_js(out, *expr);
154 | out.extend_from_slice(b"]");
155 | }
156 | };
157 | match value {
158 | ClassOrObjectMemberValue::Getter { body } => {
159 | out.extend_from_slice(b"()");
160 | emit_js(out, *body);
161 | }
162 | ClassOrObjectMemberValue::Method {
163 | signature, body, ..
164 | } => {
165 | out.extend_from_slice(b"(");
166 | emit_js(out, *signature);
167 | out.extend_from_slice(b")");
168 | emit_js(out, *body);
169 | }
170 | ClassOrObjectMemberValue::Property { initializer } => {
171 | if let Some(v) = initializer {
172 | out.extend_from_slice(value_delimiter);
173 | let is_comma = is_comma_expression(&v.stx);
174 | if is_comma {
175 | out.extend_from_slice(b"(");
176 | };
177 | emit_js(out, *v);
178 | if is_comma {
179 | out.extend_from_slice(b")");
180 | };
181 | };
182 | }
183 | ClassOrObjectMemberValue::Setter { body, parameter } => {
184 | out.extend_from_slice(b"(");
185 | emit_js(out, *parameter);
186 | out.extend_from_slice(b")");
187 | emit_js(out, *body);
188 | }
189 | };
190 |
191 | match value {
192 | ClassOrObjectMemberValue::Property { .. } => true,
193 | _ => false,
194 | }
195 | }
196 |
197 | fn emit_class<'a>(
198 | out: &mut Vec,
199 | name: &Option<&mut NodeData<'a>>,
200 | extends: &Option<&mut NodeData<'a>>,
201 | members: &SessionVec<'a, ClassMember<'a>>,
202 | ) -> () {
203 | out.extend_from_slice(b"class");
204 | if let Some(n) = name {
205 | out.extend_from_slice(b" ");
206 | emit_js(out, n);
207 | }
208 | if let Some(s) = extends {
209 | out.extend_from_slice(b" extends ");
210 | emit_js(out, s);
211 | }
212 | out.extend_from_slice(b"{");
213 | let mut last_member_was_property = false;
214 | for (i, m) in members.iter().enumerate() {
215 | if i > 0 && last_member_was_property {
216 | out.extend_from_slice(b";");
217 | }
218 | if m.statik {
219 | out.extend_from_slice(b"static ");
220 | }
221 | last_member_was_property = emit_class_or_object_member(out, &m.key, &m.value, b"=");
222 | }
223 | out.extend_from_slice(b"}");
224 | }
225 |
226 | fn emit_import_or_export_statement_trailer<'a>(
227 | out: &mut Vec,
228 | names: Option<&ExportNames<'a>>,
229 | from: Option<&'a str>,
230 | ) -> () {
231 | match names {
232 | Some(ExportNames::All(alias)) => {
233 | out.extend_from_slice(b"*");
234 | if let Some(alias) = alias {
235 | out.extend_from_slice(b"as ");
236 | emit_js(out, *alias);
237 | if from.is_some() {
238 | out.extend_from_slice(b" ");
239 | }
240 | };
241 | }
242 | Some(ExportNames::Specific(names)) => {
243 | out.extend_from_slice(b"{");
244 | for (i, e) in names.iter().enumerate() {
245 | if i > 0 {
246 | out.extend_from_slice(b",");
247 | }
248 | out.extend_from_slice(e.target.as_slice());
249 | // TODO Omit if identical to `target`.
250 | out.extend_from_slice(b" as ");
251 | emit_js(out, e.alias);
252 | }
253 | out.extend_from_slice(b"}");
254 | }
255 | None => {}
256 | };
257 | if let Some(from) = from {
258 | out.extend_from_slice(b"from\"");
259 | // TODO Escape?
260 | out.extend_from_slice(from.as_bytes());
261 | out.extend_from_slice(b"\"");
262 | };
263 | }
264 |
265 | // NOTE: We no longer support outputting to a generic Write, as that incurs significant performance overhead (even with a BufWriter>) and our parser is not streaming anyway.
266 | // WARNING: We use this function for testing minification passes (it's easier than trying to write up and then match/compare trees), so all emit logic should be deterministic and not alter/deviate from the tree in any way (i.e. it's a genuine exact unopinionated/objective unmodified reflection of the tree).
267 | pub fn emit_js<'a>(out: &mut Vec, n: &NodeData<'a>) -> () {
268 | emit_js_under_operator(out, n, None);
269 | }
270 |
271 | #[derive(Clone, Copy, PartialEq, Eq)]
272 | enum LeafNodeType {
273 | EmptyStmt,
274 | Other,
275 | Block,
276 | }
277 |
278 | fn get_leaf_node_type<'a>(n: &NodeData<'a>) -> LeafNodeType {
279 | match &n.stx {
280 | Syntax::WhileStmt { body, .. } | Syntax::ForStmt { body, .. } => get_leaf_node_type(*body),
281 | Syntax::LabelStmt { statement, .. } => get_leaf_node_type(*statement),
282 | Syntax::IfStmt {
283 | consequent,
284 | alternate,
285 | ..
286 | } => match alternate {
287 | Some(n) => get_leaf_node_type(*n),
288 | None => get_leaf_node_type(*consequent),
289 | },
290 | Syntax::BlockStmt { .. } => LeafNodeType::Block,
291 | Syntax::EmptyStmt {} => LeafNodeType::EmptyStmt,
292 | Syntax::TryStmt { .. } => LeafNodeType::Block,
293 | Syntax::SwitchStmt { .. } => LeafNodeType::Block,
294 | _ => LeafNodeType::Other,
295 | }
296 | }
297 |
298 | // It's important to use this function:
299 | // - Omit semicolons where possible.
300 | // - Insert semicolon after last statement if its leaf is a `if`, `for`, `while`, or `with` statement with an empty statement as its body e.g. `if (x) label: for (;;) while (x)` but not `if (x) for (;;) label: while (x) {}` or `if (x) for (;;) label: while (x) return`.
301 | fn emit_statements<'a>(out: &mut Vec, statements: &[&mut NodeData<'a>]) -> () {
302 | // Since we skip over some statements, the last actual statement may not be the last in the list.
303 | let mut last_statement: Option<&NodeData<'a>> = None;
304 | for n in statements {
305 | if let Syntax::EmptyStmt {} = n.stx {
306 | continue;
307 | };
308 | if let Some(n) = last_statement {
309 | match &n.stx {
310 | Syntax::BlockStmt { .. }
311 | | Syntax::ClassDecl { .. }
312 | | Syntax::EmptyStmt {}
313 | | Syntax::FunctionDecl { .. }
314 | | Syntax::SwitchStmt { .. }
315 | | Syntax::TryStmt { .. } => {}
316 | _ => out.extend_from_slice(b";"),
317 | }
318 | }
319 | emit_js(out, *n);
320 | last_statement = Some(*n);
321 | }
322 | if let Some(n) = last_statement {
323 | if get_leaf_node_type(n) == LeafNodeType::EmptyStmt {
324 | out.extend_from_slice(b";");
325 | }
326 | }
327 | }
328 |
329 | fn is_comma_expression<'a>(stx: &Syntax<'a>) -> bool {
330 | match stx {
331 | Syntax::BinaryExpr { operator, .. } => *operator == OperatorName::Comma,
332 | _ => false,
333 | }
334 | }
335 |
336 | fn leftmost_expression<'a, 'b>(stx: &'b Syntax<'a>) -> &'b Syntax<'a> {
337 | match stx {
338 | Syntax::ComputedMemberExpr { object, .. } => leftmost_expression(&object.stx),
339 | Syntax::MemberExpr { left, .. } | Syntax::BinaryExpr { left, .. } => {
340 | leftmost_expression(&left.stx)
341 | }
342 | _ => stx,
343 | }
344 | }
345 |
346 | /*
347 | For `do while (...)` and `if else (...)`, when does a semicolon need to be inserted after ``?
348 |
349 | # Requires semicolon:
350 | - do a + b; while (a)
351 | - do return; while (a)
352 | - do label: return a + b; while (a)
353 | - do continue; while (a)
354 | - do for (;;) while (y) if (z); while (a)
355 |
356 | # Does not require semicolon, would cause malformed syntax:
357 | - do {} while (a)
358 | - do if (x) {} while (a)
359 | - do for (;;) while (y) if (z) {} while (a);
360 | */
361 |
362 | fn emit_js_under_operator<'a>(
363 | out: &mut Vec,
364 | node: &NodeData<'a>,
365 | parent_operator_precedence: Option,
366 | ) -> () {
367 | match &node.stx {
368 | Syntax::EmptyStmt {} => {}
369 | Syntax::LiteralBigIntExpr { .. } => {
370 | // TODO This is invalid as `loc` may not be valid (e.g. newly created node during transform).
371 | out.extend_from_slice(node.loc.as_slice());
372 | }
373 | Syntax::LiteralRegexExpr { .. } => {
374 | // TODO This is invalid as `loc` may not be valid (e.g. newly created node during transform).
375 | out.extend_from_slice(node.loc.as_slice());
376 | }
377 | Syntax::LiteralBooleanExpr { value } => {
378 | match *value {
379 | true => out.extend_from_slice(b"!0"),
380 | false => out.extend_from_slice(b"!1"),
381 | };
382 | }
383 | Syntax::LiteralNumberExpr { value } => {
384 | // TODO Possibly invalid.
385 | write!(out, "{}", value).unwrap();
386 | }
387 | Syntax::LiteralStringExpr { value } => {
388 | // TODO Possibly not optimal, could use `'` or `"` instead.
389 | out.extend_from_slice(b"`");
390 | TEMPLATE_LITERAL_ESCAPE_MAT
391 | .stream_replace_all(value.as_bytes(), &mut *out, TEMPLATE_LITERAL_ESCAPE_REP)
392 | .unwrap();
393 | out.extend_from_slice(b"`");
394 | }
395 | Syntax::LiteralTemplateExpr { parts } => {
396 | out.extend_from_slice(b"`");
397 | for p in parts {
398 | match p {
399 | LiteralTemplatePart::Substitution(sub) => {
400 | out.extend_from_slice(b"${");
401 | emit_js(out, *sub);
402 | out.extend_from_slice(b"}");
403 | }
404 | LiteralTemplatePart::String(str) => {
405 | // TODO Escape.
406 | out.extend_from_slice(str.as_bytes());
407 | }
408 | }
409 | }
410 | out.extend_from_slice(b"`");
411 | }
412 | Syntax::VarDecl {
413 | mode, declarators, ..
414 | } => {
415 | // We split all `export var/let/const` into a declaration and an export at the end, so drop the `export`.
416 | out.extend_from_slice(match mode {
417 | VarDeclMode::Const => b"const",
418 | VarDeclMode::Let => b"let",
419 | VarDeclMode::Var => b"var",
420 | });
421 | out.extend_from_slice(b" ");
422 | for (i, decl) in declarators.iter().enumerate() {
423 | if i > 0 {
424 | out.extend_from_slice(b",");
425 | }
426 | emit_js(out, decl.pattern);
427 | if let Some(expr) = &decl.initializer {
428 | out.extend_from_slice(b"=");
429 | // This is only really done for the Comma operator, which is the only operator below Assignment.
430 | let operator = &OPERATORS[&OperatorName::Assignment];
431 | emit_js_under_operator(out, *expr, Some(operator.precedence));
432 | };
433 | }
434 | }
435 | Syntax::IdentifierPattern { name } => {
436 | out.extend_from_slice(name.as_slice());
437 | }
438 | Syntax::ArrayPattern { elements, rest } => {
439 | out.extend_from_slice(b"[");
440 | for (i, e) in elements.iter().enumerate() {
441 | if i > 0 {
442 | out.extend_from_slice(b",");
443 | }
444 | if let Some(e) = e {
445 | emit_js(out, e.target);
446 | if let Some(v) = &e.default_value {
447 | out.extend_from_slice(b"=");
448 | emit_js(out, *v);
449 | }
450 | };
451 | }
452 | if let Some(r) = rest {
453 | if !elements.is_empty() {
454 | out.extend_from_slice(b",");
455 | }
456 | out.extend_from_slice(b"...");
457 | emit_js(out, *r);
458 | };
459 | out.extend_from_slice(b"]");
460 | }
461 | Syntax::ObjectPattern { properties, rest } => {
462 | out.extend_from_slice(b"{");
463 | for (i, e) in properties.iter().enumerate() {
464 | if i > 0 {
465 | out.extend_from_slice(b",");
466 | }
467 | emit_js(out, *e);
468 | }
469 | if let Some(r) = rest {
470 | if !properties.is_empty() {
471 | out.extend_from_slice(b",");
472 | }
473 | out.extend_from_slice(b"...");
474 | emit_js(out, *r);
475 | };
476 | out.extend_from_slice(b"}");
477 | }
478 | Syntax::ClassOrFunctionName { name } => {
479 | out.extend_from_slice(name.as_slice());
480 | }
481 | Syntax::FunctionSignature { parameters } => {
482 | for (i, p) in parameters.iter().enumerate() {
483 | if i > 0 {
484 | out.extend_from_slice(b",");
485 | };
486 | emit_js(out, *p);
487 | }
488 | }
489 | Syntax::ClassDecl {
490 | export,
491 | export_default,
492 | name,
493 | extends,
494 | members,
495 | } => {
496 | // We split all `export class/function` into a declaration and an export at the end, so drop the `export`.
497 | // The exception is for unnamed functions and classes.
498 | if *export && name.is_none() {
499 | debug_assert!(*export_default);
500 | out.extend_from_slice(b"export default ");
501 | }
502 | emit_class(out, name, extends, members);
503 | }
504 | Syntax::FunctionDecl {
505 | export,
506 | export_default,
507 | is_async,
508 | generator,
509 | name,
510 | signature,
511 | body,
512 | } => {
513 | // We split all `export class/function` into a declaration and an export at the end, so drop the `export`.
514 | // The exception is for unnamed functions and classes.
515 | if *export && name.is_none() {
516 | debug_assert!(*export_default);
517 | out.extend_from_slice(b"export default ");
518 | }
519 | if *is_async {
520 | out.extend_from_slice(b"async ");
521 | }
522 | out.extend_from_slice(b"function");
523 | if *generator {
524 | out.extend_from_slice(b"*");
525 | } else if name.is_some() {
526 | out.extend_from_slice(b" ");
527 | };
528 | if let Some(name) = name {
529 | emit_js(out, *name);
530 | }
531 | out.extend_from_slice(b"(");
532 | emit_js(out, *signature);
533 | out.extend_from_slice(b")");
534 | emit_js(out, *body);
535 | }
536 | Syntax::ParamDecl {
537 | rest,
538 | pattern,
539 | default_value,
540 | } => {
541 | if *rest {
542 | out.extend_from_slice(b"...");
543 | };
544 | emit_js(out, *pattern);
545 | if let Some(v) = default_value {
546 | out.extend_from_slice(b"=");
547 | emit_js(out, *v);
548 | }
549 | }
550 | Syntax::ArrowFunctionExpr {
551 | parenthesised,
552 | is_async,
553 | signature,
554 | body,
555 | } => {
556 | // See FunctionExpr.
557 | // TODO Omit parentheses if possible.
558 | if *parenthesised {
559 | out.extend_from_slice(b"(");
560 | }
561 | if *is_async {
562 | out.extend_from_slice(b"async");
563 | }
564 | let can_omit_parentheses = if let Syntax::FunctionSignature { parameters } = &signature.stx {
565 | !is_async
566 | && parameters.len() == 1
567 | && match ¶meters[0].stx {
568 | Syntax::ParamDecl {
569 | default_value,
570 | pattern,
571 | rest,
572 | } => {
573 | !rest
574 | && default_value.is_none()
575 | && match &pattern.stx {
576 | Syntax::IdentifierPattern { .. } => true,
577 | _ => false,
578 | }
579 | }
580 | _ => false,
581 | }
582 | } else {
583 | false
584 | };
585 | if !can_omit_parentheses {
586 | out.extend_from_slice(b"(");
587 | };
588 | emit_js(out, *signature);
589 | if !can_omit_parentheses {
590 | out.extend_from_slice(b")");
591 | };
592 | out.extend_from_slice(b"=>");
593 | let must_parenthesise_body = match &body.stx {
594 | expr if is_comma_expression(expr) => true,
595 | // `{a: b}.b`, `{a: b} + 1`, etc. need to be wrapped.
596 | // TODO Refine and verify.
597 | expr => match leftmost_expression(expr) {
598 | Syntax::LiteralObjectExpr { .. } => true,
599 | _ => false,
600 | },
601 | };
602 | if must_parenthesise_body {
603 | out.extend_from_slice(b"(");
604 | };
605 | emit_js(out, *body);
606 | if must_parenthesise_body {
607 | out.extend_from_slice(b")");
608 | };
609 | // TODO Omit parentheses if possible.
610 | if *parenthesised {
611 | out.extend_from_slice(b")");
612 | };
613 | }
614 | Syntax::BinaryExpr {
615 | parenthesised,
616 | operator: operator_name,
617 | left,
618 | right,
619 | } => {
620 | let operator = &OPERATORS[operator_name];
621 | let must_parenthesise = match parent_operator_precedence {
622 | Some(po) if po > operator.precedence => true,
623 | Some(po) if po == operator.precedence => *parenthesised,
624 | // Needed to prevent an expression statement with an assignment to an object pattern from being interpreted as a block when unwrapped.
625 | // TODO Omit when possible.
626 | None if *operator_name == OperatorName::Assignment => *parenthesised,
627 | _ => false,
628 | };
629 | if must_parenthesise {
630 | out.extend_from_slice(b"(");
631 | };
632 | emit_js_under_operator(out, *left, Some(operator.precedence));
633 | out.extend_from_slice(
634 | BINARY_OPERATOR_SYNTAX
635 | .get(operator_name)
636 | .unwrap()
637 | .as_bytes(),
638 | );
639 | match operator_name {
640 | OperatorName::Addition | OperatorName::Subtraction => {
641 | // Prevent potential confict with following unary operator e.g. `a+ +b` => `a++b`.
642 | // TODO Omit when possible.
643 | out.extend_from_slice(b" ");
644 | }
645 | _ => {}
646 | };
647 | emit_js_under_operator(out, *right, Some(operator.precedence));
648 | if must_parenthesise {
649 | out.extend_from_slice(b")");
650 | };
651 | }
652 | Syntax::CallExpr {
653 | optional_chaining,
654 | parenthesised,
655 | callee,
656 | arguments,
657 | } => {
658 | let operator = &OPERATORS[&OperatorName::Call];
659 | let must_parenthesise = match parent_operator_precedence {
660 | Some(po) if po > operator.precedence => true,
661 | Some(po) if po == operator.precedence => *parenthesised,
662 | // We need to keep parentheses to prevent function expressions from being misinterpreted as a function declaration, which cannot be part of an expression e.g. IIFE.
663 | // TODO Omit parentheses if possible.
664 | None => *parenthesised,
665 | _ => false,
666 | };
667 | if must_parenthesise {
668 | out.extend_from_slice(b"(");
669 | }
670 | emit_js_under_operator(out, *callee, Some(operator.precedence));
671 | if *optional_chaining {
672 | out.extend_from_slice(b"?.");
673 | }
674 | out.extend_from_slice(b"(");
675 | for (i, a) in arguments.iter().enumerate() {
676 | if i > 0 {
677 | out.extend_from_slice(b",");
678 | }
679 | emit_js(out, *a);
680 | }
681 | out.extend_from_slice(b")");
682 | // TODO Omit parentheses if possible.
683 | if must_parenthesise {
684 | out.extend_from_slice(b")");
685 | }
686 | }
687 | Syntax::ConditionalExpr {
688 | parenthesised,
689 | test,
690 | consequent,
691 | alternate,
692 | } => {
693 | let operator = &OPERATORS[&OperatorName::Conditional];
694 | let must_parenthesise = match parent_operator_precedence {
695 | Some(po) if po > operator.precedence => true,
696 | Some(po) if po == operator.precedence => *parenthesised,
697 | _ => false,
698 | };
699 | if must_parenthesise {
700 | out.extend_from_slice(b"(");
701 | };
702 | emit_js_under_operator(out, *test, Some(operator.precedence));
703 | out.extend_from_slice(b"?");
704 | emit_js_under_operator(out, *consequent, Some(operator.precedence));
705 | out.extend_from_slice(b":");
706 | emit_js_under_operator(out, *alternate, Some(operator.precedence));
707 | if must_parenthesise {
708 | out.extend_from_slice(b")");
709 | };
710 | }
711 | Syntax::FunctionExpr {
712 | parenthesised,
713 | is_async,
714 | generator,
715 | name,
716 | signature,
717 | body,
718 | } => {
719 | // We need to keep parentheses to prevent function expressions from being misinterpreted as a function declaration, which cannot be part of an expression e.g. IIFE.
720 | // TODO Omit parentheses if possible.
721 | if *parenthesised {
722 | out.extend_from_slice(b"(");
723 | }
724 | if *is_async {
725 | out.extend_from_slice(b"async ");
726 | }
727 | out.extend_from_slice(b"function");
728 | if *generator {
729 | out.extend_from_slice(b"*");
730 | };
731 | if let Some(name) = name {
732 | if !generator {
733 | out.extend_from_slice(b" ");
734 | };
735 | emit_js(out, *name);
736 | };
737 | out.extend_from_slice(b"(");
738 | emit_js(out, *signature);
739 | out.extend_from_slice(b")");
740 | emit_js(out, *body);
741 | // TODO Omit parentheses if possible.
742 | if *parenthesised {
743 | out.extend_from_slice(b")");
744 | }
745 | }
746 | Syntax::IdentifierExpr { name } => {
747 | out.extend_from_slice(name.as_slice());
748 | }
749 | Syntax::ImportExpr { module } => {
750 | out.extend_from_slice(b"import(");
751 | emit_js(out, *module);
752 | out.extend_from_slice(b")");
753 | }
754 | Syntax::ImportMeta {} => {
755 | out.extend_from_slice(b"import.meta");
756 | }
757 | Syntax::JsxAttribute { name, value } => {
758 | emit_js(out, *name);
759 | if let Some(value) = value {
760 | out.extend_from_slice(b"=");
761 | emit_js(out, *value);
762 | }
763 | }
764 | Syntax::JsxElement {
765 | name,
766 | attributes,
767 | children,
768 | } => {
769 | out.extend_from_slice(b"<");
770 | if let Some(name) = name {
771 | emit_js(out, *name);
772 | }
773 | for attr in attributes {
774 | out.extend_from_slice(b" ");
775 | emit_js(out, *attr);
776 | }
777 | if children.is_empty() {
778 | out.extend_from_slice(b"/>");
779 | } else {
780 | out.extend_from_slice(b">");
781 | for child in children {
782 | emit_js(out, *child);
783 | }
784 | out.extend_from_slice(b"");
785 | if let Some(name) = name {
786 | emit_js(out, *name);
787 | }
788 | out.extend_from_slice(b">");
789 | }
790 | }
791 | Syntax::JsxExpressionContainer { value } => {
792 | out.extend_from_slice(b"{");
793 | emit_js(out, *value);
794 | out.extend_from_slice(b"}");
795 | }
796 | Syntax::JsxMemberExpression { base, path } => {
797 | emit_js(out, *base);
798 | for c in path {
799 | out.extend_from_slice(b".");
800 | out.extend_from_slice(c.as_slice());
801 | }
802 | }
803 | Syntax::JsxName { namespace, name } => {
804 | if let Some(namespace) = namespace {
805 | out.extend_from_slice(namespace.as_slice());
806 | out.extend_from_slice(b":");
807 | }
808 | out.extend_from_slice(name.as_slice());
809 | }
810 | Syntax::JsxSpreadAttribute { value } => {
811 | out.extend_from_slice(b"{...");
812 | emit_js(out, *value);
813 | out.extend_from_slice(b"}");
814 | }
815 | Syntax::JsxText { value } => {
816 | out.extend_from_slice(value.as_slice());
817 | }
818 | Syntax::LiteralArrayExpr { elements } => {
819 | out.extend_from_slice(b"[");
820 | for (i, e) in elements.iter().enumerate() {
821 | if i > 0 {
822 | out.extend_from_slice(b",");
823 | };
824 | match e {
825 | ArrayElement::Single(expr) => {
826 | emit_js(out, *expr);
827 | }
828 | ArrayElement::Rest(expr) => {
829 | out.extend_from_slice(b"...");
830 | emit_js(out, *expr);
831 | }
832 | ArrayElement::Empty => {}
833 | };
834 | }
835 | out.extend_from_slice(b"]");
836 | }
837 | Syntax::LiteralObjectExpr { members } => {
838 | out.extend_from_slice(b"{");
839 | for (i, e) in members.iter().enumerate() {
840 | if i > 0 {
841 | out.extend_from_slice(b",");
842 | }
843 | emit_js(out, *e);
844 | }
845 | out.extend_from_slice(b"}");
846 | }
847 | Syntax::LiteralNull {} => {
848 | out.extend_from_slice(b"null");
849 | }
850 | Syntax::UnaryExpr {
851 | parenthesised,
852 | operator: operator_name,
853 | argument,
854 | } => {
855 | let operator = OPERATORS.get(operator_name).unwrap();
856 | let must_parenthesise = match parent_operator_precedence {
857 | Some(po) if po > operator.precedence => true,
858 | Some(po) if po == operator.precedence => *parenthesised,
859 | _ => false,
860 | };
861 | if must_parenthesise {
862 | out.extend_from_slice(b"(");
863 | };
864 | out.extend_from_slice(UNARY_OPERATOR_SYNTAX.get(operator_name).unwrap().as_bytes());
865 | emit_js_under_operator(out, *argument, Some(operator.precedence));
866 | if must_parenthesise {
867 | out.extend_from_slice(b")");
868 | };
869 | }
870 | Syntax::UnaryPostfixExpr {
871 | parenthesised,
872 | operator: operator_name,
873 | argument,
874 | } => {
875 | let operator = OPERATORS.get(operator_name).unwrap();
876 | let must_parenthesise = match parent_operator_precedence {
877 | Some(po) if po > operator.precedence => true,
878 | Some(po) if po == operator.precedence => *parenthesised,
879 | _ => false,
880 | };
881 | if must_parenthesise {
882 | out.extend_from_slice(b"(");
883 | };
884 | emit_js_under_operator(out, *argument, Some(operator.precedence));
885 | out.extend_from_slice(match operator_name {
886 | OperatorName::PostfixDecrement => b"--",
887 | OperatorName::PostfixIncrement => b"++",
888 | _ => unreachable!(),
889 | });
890 | if must_parenthesise {
891 | out.extend_from_slice(b")");
892 | };
893 | }
894 | Syntax::BlockStmt { body } => {
895 | out.extend_from_slice(b"{");
896 | emit_statements(out, &body);
897 | out.extend_from_slice(b"}");
898 | }
899 | Syntax::BreakStmt { label } => {
900 | out.extend_from_slice(b"break");
901 | if let Some(label) = label {
902 | out.extend_from_slice(b" ");
903 | out.extend_from_slice(label.as_slice());
904 | };
905 | }
906 | Syntax::ContinueStmt { label } => {
907 | out.extend_from_slice(b"continue");
908 | if let Some(label) = label {
909 | out.extend_from_slice(b" ");
910 | out.extend_from_slice(label.as_slice());
911 | };
912 | }
913 | Syntax::DebuggerStmt {} => {
914 | out.extend_from_slice(b"debugger");
915 | }
916 | Syntax::ComputedMemberExpr {
917 | optional_chaining,
918 | object,
919 | member,
920 | ..
921 | } => {
922 | emit_js_under_operator(
923 | out,
924 | *object,
925 | Some(OPERATORS[&OperatorName::ComputedMemberAccess].precedence),
926 | );
927 | if *optional_chaining {
928 | out.extend_from_slice(b"?.");
929 | };
930 | out.extend_from_slice(b"[");
931 | emit_js(out, *member);
932 | out.extend_from_slice(b"]");
933 | }
934 | Syntax::ExportDefaultExprStmt { expression } => {
935 | out.extend_from_slice(b"export default ");
936 | emit_js(out, *expression);
937 | }
938 | Syntax::ExportListStmt { names, from } => {
939 | out.extend_from_slice(b"export");
940 | emit_import_or_export_statement_trailer(out, Some(names), *from);
941 | }
942 | Syntax::ExpressionStmt { expression } => {
943 | emit_js(out, *expression);
944 | }
945 | Syntax::IfStmt {
946 | test,
947 | consequent,
948 | alternate,
949 | } => {
950 | out.extend_from_slice(b"if(");
951 | emit_js(out, *test);
952 | out.extend_from_slice(b")");
953 | emit_js(out, *consequent);
954 | if let Some(alternate) = alternate {
955 | if get_leaf_node_type(*consequent) == LeafNodeType::Block {
956 | // Do nothing.
957 | } else {
958 | out.extend_from_slice(b";");
959 | };
960 | out.extend_from_slice(b"else");
961 | if let Syntax::BlockStmt { .. } = &alternate.stx {
962 | // Do nothing.
963 | } else {
964 | out.extend_from_slice(b" ");
965 | };
966 | emit_js(out, *alternate);
967 | };
968 | }
969 | Syntax::ForStmt { header, body } => {
970 | out.extend_from_slice(b"for");
971 | match header {
972 | ForStmtHeader::Three {
973 | init,
974 | condition,
975 | post,
976 | } => {
977 | out.extend_from_slice(b"(");
978 | match init {
979 | ForThreeInit::None => {}
980 | ForThreeInit::Expression(n) | ForThreeInit::Declaration(n) => emit_js(out, *n),
981 | };
982 | out.extend_from_slice(b";");
983 | if let Some(n) = condition {
984 | emit_js(out, *n);
985 | };
986 | out.extend_from_slice(b";");
987 | if let Some(n) = post {
988 | emit_js(out, *n);
989 | };
990 | }
991 | ForStmtHeader::InOf {
992 | of,
993 | lhs,
994 | rhs,
995 | await_,
996 | } => {
997 | if *await_ {
998 | out.extend_from_slice(b" await");
999 | }
1000 | out.extend_from_slice(b"(");
1001 | match lhs {
1002 | ForInOfStmtHeaderLhs::Declaration(n) | ForInOfStmtHeaderLhs::Pattern(n) => {
1003 | emit_js(out, *n);
1004 | }
1005 | };
1006 | if *of {
1007 | out.extend_from_slice(b" of ");
1008 | } else {
1009 | out.extend_from_slice(b" in ");
1010 | }
1011 | emit_js(out, *rhs);
1012 | }
1013 | };
1014 | out.extend_from_slice(b")");
1015 | emit_js(out, *body);
1016 | }
1017 | Syntax::ImportStmt {
1018 | default,
1019 | names,
1020 | module,
1021 | } => {
1022 | out.extend_from_slice(b"import");
1023 | if let Some(default) = default {
1024 | out.extend_from_slice(b" ");
1025 | emit_js(out, *default);
1026 | if names.is_some() {
1027 | out.extend_from_slice(b",");
1028 | } else {
1029 | out.extend_from_slice(b" ");
1030 | };
1031 | };
1032 | emit_import_or_export_statement_trailer(out, names.as_ref(), Some(module));
1033 | }
1034 | Syntax::ReturnStmt { value } => {
1035 | out.extend_from_slice(b"return");
1036 | if let Some(value) = value {
1037 | // TODO Omit space if possible.
1038 | out.extend_from_slice(b" ");
1039 | emit_js(out, *value);
1040 | };
1041 | }
1042 | Syntax::ThisExpr {} => {
1043 | out.extend_from_slice(b"this");
1044 | }
1045 | Syntax::ThrowStmt { value } => {
1046 | out.extend_from_slice(b"throw ");
1047 | emit_js(out, *value);
1048 | }
1049 | Syntax::TopLevel { body } => {
1050 | emit_statements(out, &body);
1051 | }
1052 | Syntax::TryStmt {
1053 | wrapped,
1054 | catch,
1055 | finally,
1056 | } => {
1057 | out.extend_from_slice(b"try");
1058 | emit_js(out, *wrapped);
1059 | if let Some(c) = catch {
1060 | emit_js(out, *c);
1061 | }
1062 | if let Some(f) = finally {
1063 | out.extend_from_slice(b"finally");
1064 | emit_js(out, *f);
1065 | };
1066 | }
1067 | Syntax::WhileStmt { condition, body } => {
1068 | out.extend_from_slice(b"while(");
1069 | emit_js(out, *condition);
1070 | out.extend_from_slice(b")");
1071 | emit_js(out, *body);
1072 | }
1073 | Syntax::DoWhileStmt { condition, body } => {
1074 | out.extend_from_slice(b"do");
1075 | if let Syntax::BlockStmt { .. } = &body.stx {
1076 | // Do nothing.
1077 | } else {
1078 | out.extend_from_slice(b" ");
1079 | };
1080 | emit_js(out, *body);
1081 | if get_leaf_node_type(*body) == LeafNodeType::Block {
1082 | // Do nothing.
1083 | } else {
1084 | out.extend_from_slice(b";");
1085 | };
1086 | out.extend_from_slice(b"while(");
1087 | emit_js(out, *condition);
1088 | out.extend_from_slice(b")");
1089 | }
1090 | Syntax::SwitchStmt { test, branches } => {
1091 | out.extend_from_slice(b"switch(");
1092 | emit_js(out, *test);
1093 | out.extend_from_slice(b"){");
1094 | for (i, b) in branches.iter().enumerate() {
1095 | if i > 0 {
1096 | out.extend_from_slice(b";");
1097 | };
1098 | emit_js(out, *b);
1099 | }
1100 | out.extend_from_slice(b"}");
1101 | }
1102 | Syntax::CatchBlock { parameter, body } => {
1103 | out.extend_from_slice(b"catch");
1104 | if let Some(p) = parameter {
1105 | out.extend_from_slice(b"(");
1106 | emit_js(out, *p);
1107 | out.extend_from_slice(b")");
1108 | }
1109 | emit_js(out, *body);
1110 | }
1111 | Syntax::SwitchBranch { case, body } => {
1112 | match case {
1113 | Some(case) => {
1114 | // TODO Omit space if possible.
1115 | out.extend_from_slice(b"case ");
1116 | emit_js(out, *case);
1117 | out.extend_from_slice(b":");
1118 | }
1119 | None => {
1120 | out.extend_from_slice(b"default:");
1121 | }
1122 | }
1123 | emit_statements(out, &body);
1124 | }
1125 | Syntax::ObjectPatternProperty {
1126 | key,
1127 | target,
1128 | default_value,
1129 | shorthand,
1130 | } => {
1131 | match key {
1132 | ClassOrObjectMemberKey::Direct(name) => {
1133 | out.extend_from_slice(name.as_slice());
1134 | }
1135 | ClassOrObjectMemberKey::Computed(expr) => {
1136 | out.extend_from_slice(b"[");
1137 | emit_js(out, *expr);
1138 | out.extend_from_slice(b"]");
1139 | }
1140 | };
1141 | if !*shorthand {
1142 | out.extend_from_slice(b":");
1143 | emit_js(out, *target);
1144 | };
1145 | if let Some(v) = default_value {
1146 | out.extend_from_slice(b"=");
1147 | emit_js(out, *v);
1148 | };
1149 | }
1150 | Syntax::ObjectMember { typ } => {
1151 | match typ {
1152 | ObjectMemberType::Valued { key, value } => {
1153 | emit_class_or_object_member(out, key, value, b":");
1154 | }
1155 | ObjectMemberType::Shorthand { identifier } => {
1156 | emit_js(out, *identifier);
1157 | }
1158 | ObjectMemberType::Rest { value } => {
1159 | out.extend_from_slice(b"...");
1160 | emit_js(out, *value);
1161 | }
1162 | };
1163 | }
1164 | Syntax::MemberExpr {
1165 | parenthesised,
1166 | optional_chaining,
1167 | left,
1168 | right,
1169 | ..
1170 | } => {
1171 | let operator_name = &if *optional_chaining {
1172 | OperatorName::OptionalChainingMemberAccess
1173 | } else {
1174 | OperatorName::MemberAccess
1175 | };
1176 | let operator = &OPERATORS[operator_name];
1177 | let must_parenthesise = match parent_operator_precedence {
1178 | Some(po) if po > operator.precedence => true,
1179 | Some(po) if po == operator.precedence => *parenthesised,
1180 | _ => false,
1181 | };
1182 | if must_parenthesise {
1183 | out.extend_from_slice(b"(");
1184 | };
1185 | emit_js_under_operator(out, *left, Some(operator.precedence));
1186 | out.extend_from_slice(
1187 | BINARY_OPERATOR_SYNTAX
1188 | .get(operator_name)
1189 | .unwrap()
1190 | .as_bytes(),
1191 | );
1192 | out.extend_from_slice(right.as_slice());
1193 | if must_parenthesise {
1194 | out.extend_from_slice(b")");
1195 | };
1196 | }
1197 | Syntax::ClassExpr {
1198 | parenthesised,
1199 | name,
1200 | extends,
1201 | members,
1202 | } => {
1203 | // We need to keep parentheses to prevent class expressions from being misinterpreted as a class declaration, which cannot be part of an expression.
1204 | // TODO Omit parentheses if possible.
1205 | if *parenthesised {
1206 | out.extend_from_slice(b"(");
1207 | }
1208 | emit_class(out, name, extends, members);
1209 | // TODO Omit parentheses if possible.
1210 | if *parenthesised {
1211 | out.extend_from_slice(b")");
1212 | }
1213 | }
1214 | Syntax::LabelStmt { name, statement } => {
1215 | out.extend_from_slice(name.as_slice());
1216 | out.extend_from_slice(b":");
1217 | emit_js(out, *statement);
1218 | }
1219 | Syntax::CallArg { spread, value } => {
1220 | if *spread {
1221 | out.extend_from_slice(b"...");
1222 | }
1223 | emit_js(out, *value);
1224 | }
1225 | Syntax::SuperExpr {} => {
1226 | out.extend_from_slice(b"super");
1227 | }
1228 | Syntax::_TakenNode {} => unreachable!(),
1229 | };
1230 | }
1231 |
--------------------------------------------------------------------------------
/rust/src/emit/tests/mod.rs:
--------------------------------------------------------------------------------
1 | use crate::emit::emit_js;
2 | use crate::minify::minify_js;
3 | use crate::TopLevelMode;
4 | use parse_js::lex::Lexer;
5 | use parse_js::parse::Parser;
6 | use parse_js::session::Session;
7 | use parse_js::symbol::SymbolGenerator;
8 |
9 | fn check(top_level_mode: TopLevelMode, src: &str, expected: &str) -> () {
10 | let session = Session::new();
11 | let mut parser = Parser::new(Lexer::new(src.as_bytes()));
12 | let node = parser
13 | .parse_top_level(&session, SymbolGenerator::new(), top_level_mode)
14 | .unwrap();
15 | let mut out = Vec::new();
16 | minify_js(&session, node);
17 | emit_js(&mut out, node);
18 | assert_eq!(
19 | unsafe { std::str::from_utf8_unchecked(out.as_slice()) },
20 | expected
21 | );
22 | }
23 |
24 | #[test]
25 | fn test_emit_global() {
26 | check(
27 | TopLevelMode::Global,
28 | r#"
29 | /* Test code */
30 | function * gen () {
31 | yield * "hello world!";
32 | }
33 | !() => {
34 | com.java.names.long
35 | module.functions
36 |
37 | function this_is_a_function_decl_not_expr() {
38 | this_is_a_function_decl_not_expr()
39 | }
40 |
41 | var the = 1, quick, { brown, _: [ fox, jumped, , , ...over ], ...lazy } = i;
42 |
43 | (( {the} = this_is_a_function_decl_not_expr, [quick] = 2 ) => {
44 | {
45 | let brown = this_is_a_function_decl_not_expr(fox);
46 | }
47 | the,quick,brown,fox
48 | ;
49 | return
50 | 1.2.toString()
51 | })();;;
52 |
53 | const lorem = ({}) => {}
54 | const ipsum = (a) => (1,2), dolor = (1/7)/(2/7)
55 | }()
56 | "#,
57 | "\
58 | function*gen(){yield*`hello world!`}\
59 | !()=>{\
60 | var a=(()=>{a()});\
61 | com.java.names.long;\
62 | module.functions;\
63 | var b=1,c,{brown:d,_:[e,f,,,...g],...h}=i;\
64 | (({the:b}=a,[c]=2)=>{{let b=a(e)}b,c,d,e;return})();\
65 | const j=({})=>{};\
66 | const k=a=>(1,2),l=(1/7)/(2/7)\
67 | }()\
68 | ",
69 | )
70 | }
71 |
72 | #[test]
73 | fn test_emit_module() {
74 | check(
75 | TopLevelMode::Module,
76 | r#"
77 | import React, {
78 | useState as reactUseState,
79 | useEffect as reactUseEffect,
80 | createElement,
81 | memo as reactMemo
82 | } from "react";
83 | import {default as ReactDOM} from "react-dom";
84 |
85 | const x = 1;
86 |
87 | export const {meaning} = {meaning: 42}, life = 10;
88 | console.log("meaning", meaning);
89 |
90 | export default function ship() {};
91 | console.log(ship(life));
92 |
93 | ReactDOM.hello();
94 |
95 | export {
96 | reactUseState as use_state,
97 | reactUseEffect,
98 | };
99 | "#,
100 | "\
101 | import a,{useState as b,useEffect as c,createElement as d,memo as e}from\"react\";\
102 | import{default as f}from\"react-dom\";\
103 | const g=1;\
104 | const {meaning:h}={meaning:42},i=10;\
105 | console.log(`meaning`,h);\
106 | function j(){}\
107 | console.log(j(i));\
108 | f.hello();\
109 | export{h as meaning,i as life,j as default,b as use_state,c as reactUseEffect}\
110 | ",
111 | );
112 | check(
113 | TopLevelMode::Module,
114 | r#"
115 | export const x = 1;
116 | export default function(){}
117 | "#,
118 | "\
119 | const a=1;\
120 | export default function(){}\
121 | export{a as x}\
122 | ",
123 | );
124 | check(
125 | TopLevelMode::Module,
126 | r#"
127 | export * from "react";
128 | export default class{}
129 | "#,
130 | "\
131 | export*from\"react\";\
132 | export default class{}\
133 | ",
134 | );
135 | }
136 |
137 | #[test]
138 | fn test_emit_private_member() {
139 | check(
140 | TopLevelMode::Global,
141 | r#"
142 | class A {
143 | set = 1;
144 | await
145 | #hello;
146 | #goodbye = 1;
147 |
148 | ring() {
149 | console.log(this.#hello);
150 | }
151 | }
152 | "#,
153 | "\
154 | class A{\
155 | set=1;\
156 | await;\
157 | #hello;\
158 | #goodbye=1;\
159 | ring(){console.log(this.#hello)}\
160 | }\
161 | ",
162 | );
163 | }
164 |
165 | #[test]
166 | fn test_emit_arrow_function_return_expression() {
167 | check(
168 | TopLevelMode::Global,
169 | r#"
170 | () => {
171 | return 1;
172 | }
173 | "#,
174 | "()=>1",
175 | );
176 | check(
177 | TopLevelMode::Global,
178 | r#"
179 | () => {
180 | return {};
181 | }
182 | "#,
183 | "()=>({})",
184 | );
185 | check(
186 | TopLevelMode::Global,
187 | r#"
188 | () => ({});
189 | "#,
190 | "()=>({})",
191 | );
192 | }
193 |
194 | #[test]
195 | fn test_emit_nested_blockless_statements() {
196 | check(
197 | TopLevelMode::Global,
198 | r#"
199 | function fn(a, b) {
200 | if (a)
201 | if (b)
202 | try {
203 | c()
204 | } catch (c) {
205 | e(f)
206 | }
207 | else g = h
208 | }
209 | "#,
210 | "var fn=((a,b)=>{if(a)if(b)try{c()}catch(a){e(f)}else g=h})",
211 | );
212 | }
213 |
214 | #[test]
215 | fn test_emit_jsx() {
216 | check(
217 | TopLevelMode::Module,
218 | r#"
219 | import CompImp from "./comp";
220 |
221 | let U = {a:"div"};
222 |
223 | const CompLocal = () => ;
224 |
225 | render();
226 | "#,
227 | r#"import A from"./comp";let a={a:`div`};const B=()=>;render()"#,
228 | );
229 | }
230 |
231 | #[test]
232 | fn test_advanced_if_minification() {
233 | check(
234 | TopLevelMode::Global,
235 | r#"
236 | function foo(arg) {
237 | if (arg) {
238 | 1; 2; 3; 4;
239 | if (cond) {
240 | 5;
241 | }
242 | 6; 7;
243 | }
244 | }
245 | "#,
246 | r#"var foo=(a=>{a&&(1,2,3,4,cond&&5,6,7)})"#,
247 | );
248 | check(
249 | TopLevelMode::Global,
250 | r#"
251 | function foo(arg) {
252 | if (arg) {
253 | 1; 2; 3; 4;
254 | if (cond) {
255 | return 5;
256 | }
257 | 6; 7;
258 | return 8;
259 | }
260 | }
261 | "#,
262 | r#"var foo=(a=>{if(a)return 1,2,3,4,cond?5:(6,7,8)})"#,
263 | );
264 | check(
265 | TopLevelMode::Global,
266 | r#"
267 | function foo(arg) {
268 | if (arg) {
269 | 1; 2; 3; 4;
270 | if (cond) {
271 | return 5;
272 | }
273 | 6; 7;
274 | return 8;
275 | } else {
276 | 9; 10;
277 | return 11;
278 | }
279 | }
280 | "#,
281 | r#"var foo=(a=>{if(a)return 1,2,3,4,cond?5:(6,7,8);9;10;return 11})"#,
282 | );
283 | check(
284 | TopLevelMode::Global,
285 | r#"
286 | function foo(arg) {
287 | if (arg) {
288 | var x = 1;
289 | if (cond) {
290 | var y = 2;
291 | return y;
292 | } else {
293 | return x;
294 | }
295 | } else {
296 | var z = 3;
297 | return z;
298 | }
299 | }
300 | "#,
301 | r#"var foo=(a=>{var d,c;if(!a)return d=3,d;var b=1;if(cond)return c=2,c;return b})"#,
302 | );
303 | }
304 |
--------------------------------------------------------------------------------
/rust/src/lib.rs:
--------------------------------------------------------------------------------
1 | use emit::emit_js;
2 | use minify::minify_js;
3 | use parse_js::ast::Node;
4 | use parse_js::parse;
5 |
6 | mod emit;
7 | mod minify;
8 |
9 | pub use parse_js::error::SyntaxError;
10 | pub use parse_js::parse::toplevel::TopLevelMode;
11 | pub use parse_js::session::Session;
12 |
13 | /// Emits UTF-8 JavaScript code from a parsed AST in a minified way. This allows custom introspections and transforms on the tree before emitting it to code.
14 | ///
15 | /// # Arguments
16 | ///
17 | /// * `node` - The root node from the parsed AST.
18 | /// * `output` - Destination to write output JavaScript code.
19 | pub fn emit<'a>(node: Node<'a>, output: &mut Vec) -> () {
20 | emit_js(output, node);
21 | }
22 |
23 | /// Minifies UTF-8 JavaScript code, represented as an array of bytes.
24 | ///
25 | /// # Arguments
26 | ///
27 | /// * `session` - Session to use as backing arena memory. Can be reused across calls and cleared at any time allowed by the Rust lifetime checker.
28 | /// * `top_level_mode` - How to parse the provided code.
29 | /// * `source` - A vector of bytes representing the source code to minify.
30 | /// * `output` - Destination to write minified output JavaScript code.
31 | ///
32 | /// # Examples
33 | ///
34 | /// ```
35 | /// use minify_js::{Session, TopLevelMode, minify};
36 | ///
37 | /// let mut code: &[u8] = b"const main = () => { let my_first_variable = 1; };";
38 | /// let session = Session::new();
39 | /// let mut out = Vec::new();
40 | /// minify(&session, TopLevelMode::Global, code, &mut out).unwrap();
41 | /// assert_eq!(out.as_slice(), b"const main=()=>{let a=1}");
42 | /// ```
43 | pub fn minify<'a>(
44 | session: &'a Session,
45 | top_level_mode: TopLevelMode,
46 | source: &'a [u8],
47 | output: &mut Vec,
48 | ) -> Result<(), SyntaxError<'a>> {
49 | let parsed = parse(session, source, top_level_mode)?;
50 | minify_js(session, parsed);
51 | emit(parsed, output);
52 | Ok(())
53 | }
54 |
--------------------------------------------------------------------------------
/rust/src/minify/advanced_if.rs:
--------------------------------------------------------------------------------
1 | use parse_js::ast::new_node;
2 | use parse_js::ast::Node;
3 | use parse_js::ast::NodeData;
4 | use parse_js::ast::Syntax;
5 | use parse_js::ast::VarDeclMode;
6 | use parse_js::operator::OperatorName;
7 | use parse_js::session::Session;
8 | use parse_js::session::SessionVec;
9 | use parse_js::source::SourceRange;
10 | use parse_js::symbol::Scope;
11 |
12 | // If statement optimisation:
13 | // - `if (a) { b }` => `a && b` if `b` can be reduced to a single expression.
14 | // - `if (a) { b } else { c }` => `a ? b : c` if `b` and `c` can be reduced to a single expression.
15 | // - `if (a) { b; return c }` => `if (a) return b, c` if `b` can be reduced to a single expression.
16 | // The last form is more for normalisation: it doesn't minify much by itself (it still remains a statement), but allows a containing `if` to optimise `if (a) { b; return c } d; return e` into `return a ? (b, c) : (d, e)` if `b` and `d` can be reduced to a single expression. Otherwise, we wouldn't be able to minify the containing `if`.
17 | // Note that it's not possible for both branches to return, as a previous pass should have already unwrapped the unnecessary block. We also normalise it such that if only `else` returns, it's flipped, and then the `else` can be unwrapped.
18 | //
19 | // Expected normalisations before performing this optimisation:
20 | // - Removing as many non-expression statements as possible:
21 | // - Removing EmptyStmt and DebuggerStmt nodes.
22 | // - Hoisting as many VarDecl nodes as possible (or even removing them if unused or optimised away e.g. lexical lifetimes).
23 | // - Removing empty IfStmt and TryStmt nodes.
24 | // - Dropping dead code.
25 | // - Unwrapping unnecessary BlockStmt nodes.
26 | // - Performing this advanced IfStmt optimisation (yes, this optimisation recursively depends on itself).
27 | // - Normalising IfStmt such that either no branch returns or the consequent branch returns and there is no `else`.
28 | //
29 | // We only perform advanced statement analysis and transformation to expression in `if` and `else` blocks as that will allow opportunities to transform `if` into logical expressions. This isn't useful elsewhere, as a sequence of expression statements is the same size as a sequence of expressions separated by commas, so the fact it's an expression is not being leveraged.
30 |
31 | // We first perform some analysis to see if it's even worthwhile to perform this optimisation.
32 | pub fn analyse_if_branch<'a>(stx: &Syntax<'a>) -> bool {
33 | let Syntax::BlockStmt { body } = stx else {
34 | // We should have already normalised all `if` branches into a block if they were single statements, so this should not be possible.
35 | unreachable!();
36 | };
37 | let mut block_returned = false;
38 | let mut if_returned = false;
39 | for stmt in body.iter() {
40 | match &stmt.stx {
41 | Syntax::VarDecl {
42 | mode, declarators, ..
43 | } => {
44 | match mode {
45 | // We can make `var` declarations into expressions by hoisting the declaration part and leaving behind an assignment expression (if an initialiser exists).
46 | // TODO Support non-identifier patterns, although they may not be worth minifying if we have to hoist and therefore duplicate the variable names.
47 | VarDeclMode::Var => {
48 | if declarators.iter().any(|d| match d.pattern.stx {
49 | Syntax::IdentifierPattern { .. } => false,
50 | _ => true,
51 | }) {
52 | return false;
53 | }
54 | }
55 | // TODO We currently disallow if `let` or `const`, however there is a complex approach we could consider in the future: they're scoped to the block, so we can either wrap our optimised expression in a block or create a unique variable in the nearest closure and hoist it like `var`. Since the former means we're still left with a (block) statement, we choose the latter, but that means we can't do this if we're in the global scope as we're not allowed to introduce global variables (even if they're very unlikely to collide in reality). We'd have to replace all usages of these variables, however.
56 | VarDeclMode::Const | VarDeclMode::Let => return false,
57 | };
58 | }
59 | Syntax::ExpressionStmt { .. } => {}
60 | Syntax::ReturnStmt { .. } => block_returned = true,
61 | // Since we perform this optimisation bottom-up, any IfStmt should already be optimised, so if they were optimised and still exist as a statement, they should only have exactly one statement of `return` in `if` and `else`.
62 | Syntax::IfStmt {
63 | consequent: NodeData {
64 | stx: Syntax::ReturnStmt { .. },
65 | ..
66 | },
67 | alternate: None,
68 | ..
69 | } => if_returned = true,
70 | // Debugger and empty statements should already be removed.
71 | _ => return false,
72 | };
73 | }
74 | // We must only be left with at most one return statement (i.e. unconditional, although value can be conditional). Essentially, this means that if we have an `if (x) return`, we must have a block-level return, as otherwise we cannot represent it as a single `return`.
75 | !if_returned || block_returned
76 | }
77 |
78 | pub struct ProcessedIfBranch<'a> {
79 | pub expression: Node<'a>,
80 | pub hoisted_vars: SessionVec<'a, SourceRange<'a>>,
81 | // If true, it means that it's not an expression, but a single return statement with the expression as the return value.
82 | pub returns: bool,
83 | }
84 |
85 | fn process_if_branch_block<'a, 'b>(
86 | session: &'a Session,
87 | scope: Scope<'a>,
88 | body: &'b mut [Node<'a>],
89 | ) -> ProcessedIfBranch<'a> {
90 | let mut returns = false;
91 | let mut hoisted_vars: SessionVec<'a, SourceRange<'a>> = session.new_vec();
92 | let mut expressions: SessionVec<'a, Node<'a>> = session.new_vec();
93 | let mut i = 0;
94 | while i < body.len() {
95 | let loc = body[i].loc;
96 | let scope = body[i].scope;
97 | match &mut body[i].stx {
98 | Syntax::ExpressionStmt { expression } => {
99 | expressions.push(expression.take(session));
100 | }
101 | Syntax::ReturnStmt { value } => {
102 | returns = true;
103 | expressions.push(match value {
104 | Some(value) => value.take(session),
105 | None => new_node(session, scope, loc, Syntax::IdentifierExpr {
106 | name: SourceRange::from_slice(b"undefined"),
107 | }),
108 | });
109 | }
110 | Syntax::VarDecl {
111 | declarators,
112 | mode: VarDeclMode::Var,
113 | ..
114 | } => {
115 | for decl in declarators.iter_mut() {
116 | let target = decl.pattern.take(session);
117 | let Syntax::IdentifierPattern { name } = target.stx else {
118 | unreachable!();
119 | };
120 | hoisted_vars.push(name);
121 | if let Some(init) = &mut decl.initializer {
122 | let right = init.take(session);
123 | expressions.push(new_node(
124 | session,
125 | scope,
126 | name + init.loc,
127 | Syntax::BinaryExpr {
128 | parenthesised: false,
129 | operator: OperatorName::Assignment,
130 | left: target,
131 | right,
132 | },
133 | ));
134 | }
135 | }
136 | }
137 | Syntax::IfStmt {
138 | test,
139 | consequent:
140 | NodeData {
141 | stx: Syntax::ReturnStmt { value },
142 | loc: ret_loc,
143 | ..
144 | },
145 | alternate: None,
146 | } => {
147 | returns = true;
148 |
149 | // Take before we reborrow mutably for process_if_branch_block.
150 | let test = test.take(session);
151 | let consequent = value.as_mut().map(|v| v.take(session)).unwrap_or(new_node(
152 | session,
153 | scope,
154 | *ret_loc,
155 | Syntax::IdentifierExpr {
156 | name: SourceRange::from_slice(b"undefined"),
157 | },
158 | ));
159 |
160 | let mut remaining = process_if_branch_block(session, scope, &mut body[i + 1..]);
161 | assert!(remaining.returns);
162 | hoisted_vars.append(&mut remaining.hoisted_vars);
163 | let alternate = remaining.expression;
164 | expressions.push(new_node(session, scope, loc, Syntax::ConditionalExpr {
165 | parenthesised: false,
166 | test,
167 | consequent,
168 | alternate,
169 | }));
170 | break;
171 | }
172 | _ => unreachable!(),
173 | };
174 | i += 1;
175 | }
176 |
177 | ProcessedIfBranch {
178 | expression: expressions
179 | .into_iter()
180 | .reduce(|left, right| {
181 | new_node(session, scope, left.loc + right.loc, Syntax::BinaryExpr {
182 | parenthesised: false,
183 | operator: OperatorName::Comma,
184 | left,
185 | right,
186 | })
187 | })
188 | .unwrap(),
189 | hoisted_vars,
190 | returns,
191 | }
192 | }
193 |
194 | pub fn process_if_branch<'a, 'b>(
195 | session: &'a Session,
196 | scope: Scope<'a>,
197 | branch: &'b mut NodeData<'a>,
198 | ) -> ProcessedIfBranch<'a> {
199 | let Syntax::BlockStmt { body } = &mut branch.stx else {
200 | // We should have already normalised all `if` branches into a block if they were single statements, so this should not be possible.
201 | unreachable!()
202 | };
203 | process_if_branch_block(session, scope, body)
204 | }
205 |
--------------------------------------------------------------------------------
/rust/src/minify/ctx.rs:
--------------------------------------------------------------------------------
1 | use super::lexical_lifetimes::LexicalLifetime;
2 | use parse_js::ast::Node;
3 | use parse_js::session::Session;
4 | use parse_js::session::SessionHashMap;
5 | use parse_js::session::SessionHashSet;
6 | use parse_js::session::SessionVec;
7 | use parse_js::source::SourceRange;
8 | use parse_js::symbol::Identifier;
9 | use parse_js::symbol::Scope;
10 | use parse_js::symbol::Symbol;
11 | use std::cmp::max;
12 | use std::cmp::min;
13 |
14 | // Our additional state that's associated with each Symbol.
15 | pub struct MinifySymbol<'a> {
16 | pub minified_name: Option>,
17 | pub is_used_as_jsx_component: bool,
18 | pub has_usage: bool,
19 | // If this is true, and this symbol is associated with a function, don't transform the function into an arrow function, even if it doesn't use `this`.
20 | pub is_used_as_constructor: bool,
21 | // Similar to `is_used_as_constructor`, although a weaker signal, since the presence of `prototype` is highly likely to mean it's a constructor function, but not as certain as `new`.
22 | pub has_prototype: bool,
23 | pub lexical_lifetime_start: LexicalLifetime<'a>,
24 | pub lexical_lifetime_end: LexicalLifetime<'a>,
25 | }
26 |
27 | impl<'a> MinifySymbol<'a> {
28 | pub fn new(session: &'a Session) -> Self {
29 | Self {
30 | minified_name: None,
31 | is_used_as_jsx_component: false,
32 | has_usage: false,
33 | is_used_as_constructor: false,
34 | has_prototype: false,
35 | lexical_lifetime_start: LexicalLifetime::new_infinite(session),
36 | lexical_lifetime_end: LexicalLifetime::new_zero(session),
37 | }
38 | }
39 |
40 | pub fn update_lifetime(&mut self, lifetime: LexicalLifetime<'a>) {
41 | if lifetime < self.lexical_lifetime_start {
42 | self.lexical_lifetime_start = lifetime.clone();
43 | };
44 | if lifetime > self.lexical_lifetime_end {
45 | self.lexical_lifetime_end = lifetime.clone();
46 | };
47 | }
48 | }
49 |
50 | // Our additional state that's associated with each Scope.
51 | pub struct MinifyScope<'a> {
52 | // Variables that are declared by an ancestor (not own) scope (or is not declared anywhere and assumed to be global), and used by code in own or any descendant scope.
53 | pub inherited_vars: SessionHashSet<'a, Identifier<'a>>,
54 | // Function declarations within this closure-like scope that must be hoisted to declarations at the very beginning of this closure's code (so we can transform them to `var` and still have them work correctly). There may be multiple closures with the same name, nested deep with many blocks and branches, which is why we use a map; the last visited (lexical) declaration wins. Note that this is only populated if this scope is a closure; function declarations don't hoist to blocks.
55 | // Since they could be deep and anywhere, we must take them and move them into this map; we can't just look at a BlockStmt's children as they may not always be there.
56 | pub hoisted_functions: SessionHashMap<'a, Identifier<'a>, Node<'a>>,
57 | // `var` declarations in this closure that need to be moved to allow for some optimisation.
58 | pub hoisted_vars: SessionVec<'a, Identifier<'a>>,
59 | }
60 |
61 | impl<'a> MinifyScope<'a> {
62 | pub fn new(session: &'a Session) -> MinifyScope<'a> {
63 | MinifyScope {
64 | inherited_vars: session.new_hashset(),
65 | hoisted_functions: session.new_hashmap(),
66 | hoisted_vars: session.new_vec(),
67 | }
68 | }
69 | }
70 |
71 | pub struct Ctx<'a, 'b> {
72 | pub session: &'a Session,
73 | pub symbols: &'b mut SessionHashMap<'a, Symbol, MinifySymbol<'a>>,
74 | pub scopes: &'b mut SessionHashMap<'a, Scope<'a>, MinifyScope<'a>>,
75 | }
76 |
77 | impl<'a, 'b> Ctx<'a, 'b> {
78 | // See [notes/Name minification.md] for the algorithm in more detail.
79 | pub fn track_variable_usage(&mut self, scope: Scope<'a>, name: Identifier<'a>) {
80 | let mut cur = Some(scope);
81 | while let Some(scope) = cur {
82 | if let Some(sym) = scope.get_symbol(name) {
83 | self
84 | .symbols
85 | .entry(sym)
86 | .or_insert_with(|| MinifySymbol::new(self.session))
87 | .has_usage = true;
88 | break;
89 | };
90 | self
91 | .scopes
92 | .entry(scope)
93 | .or_insert_with(|| MinifyScope::new(self.session))
94 | .inherited_vars
95 | .insert(name);
96 | cur = scope.parent();
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/rust/src/minify/lexical_lifetimes.rs:
--------------------------------------------------------------------------------
1 | use super::ctx::Ctx;
2 | use super::ctx::MinifySymbol;
3 | use core::mem::discriminant;
4 | use parse_js::ast::NodeData;
5 | use parse_js::ast::Syntax;
6 | use parse_js::session::Session;
7 | use parse_js::session::SessionVec;
8 | use parse_js::visit::JourneyControls;
9 | use parse_js::visit::Visitor;
10 | use std::cmp::Ordering;
11 |
12 | #[derive(PartialEq, Eq, PartialOrd, Ord, Clone)]
13 | pub struct LexicalLifetime<'a>(SessionVec<'a, u32>);
14 |
15 | impl<'a> LexicalLifetime<'a> {
16 | pub fn new_zero(session: &'a Session) -> Self {
17 | let mut vec = session.new_vec();
18 | vec.push(0);
19 | Self(vec)
20 | }
21 |
22 | pub fn new_infinite(session: &'a Session) -> Self {
23 | let mut vec = session.new_vec();
24 | vec.push(u32::MAX);
25 | Self(vec)
26 | }
27 |
28 | pub fn bump(&mut self) {
29 | *self.0.last_mut().unwrap() += 1;
30 | }
31 |
32 | pub fn fork(&mut self) {
33 | self.0.push(0);
34 | }
35 |
36 | pub fn is_sibling_of(&self, other: &Self) -> bool {
37 | let lvl = self.0.len();
38 | lvl == other.0.len() && (lvl == 1 || self.0[lvl - 2] == other.0[lvl - 2])
39 | }
40 | }
41 |
42 | pub struct LexicalLifetimesPass<'a, 'b> {
43 | pub ctx: Ctx<'a, 'b>,
44 | pub stack: LexicalLifetime<'a>,
45 | pub in_loop: bool,
46 | }
47 |
48 | impl<'a, 'b> LexicalLifetimesPass<'a, 'b> {
49 | pub fn new(ctx: Ctx<'a, 'b>) -> Self {
50 | let stack = LexicalLifetime::new_zero(ctx.session);
51 | Self {
52 | ctx,
53 | stack,
54 | in_loop: false,
55 | }
56 | }
57 |
58 | fn fork_stack(&mut self) -> LexicalLifetime<'a> {
59 | let orig = self.stack.clone();
60 | self.stack.fork();
61 | orig
62 | }
63 |
64 | fn join_stack(&mut self, orig: &LexicalLifetime<'a>) {
65 | self.stack = orig.clone();
66 | }
67 |
68 | fn bump_stack(&mut self) -> &mut LexicalLifetime<'a> {
69 | self.stack.bump();
70 | &mut self.stack
71 | }
72 |
73 | fn visit_conditional(
74 | &mut self,
75 | test: &mut NodeData<'a>,
76 | consequent: &mut NodeData<'a>,
77 | alternate: Option<&mut NodeData<'a>>,
78 | ctl: &mut JourneyControls,
79 | ) {
80 | self.visit(test);
81 |
82 | // Conditionals get their own lifetime value, and then each branch is a fork (i.e. subelements).
83 | let if_stack = self.bump_stack().clone();
84 | self.fork_stack();
85 | self.visit(consequent);
86 | self.join_stack(&if_stack);
87 | if let Some(alternate) = alternate {
88 | self.fork_stack();
89 | self.visit(alternate);
90 | self.join_stack(&if_stack);
91 | };
92 |
93 | ctl.skip();
94 | }
95 | }
96 |
97 | impl<'a, 'b> Visitor<'a> for LexicalLifetimesPass<'a, 'b> {
98 | fn on_syntax_down(&mut self, node: &mut NodeData<'a>, ctl: &mut JourneyControls) -> () {
99 | let usage_scope = node.scope;
100 | let Some(usage_closure_scope) = usage_scope.find_self_or_ancestor(|s| s.is_closure_or_class())
101 | else {
102 | // TODO Assert we're at the top level.
103 | return;
104 | };
105 | // We could reset the stack when entering a closure and restore on exit, but this isn't strictly necessary since values are still distinct even if we continue to use existing stack. It also avoids some complexity and performance costs.
106 | match &mut node.stx {
107 | Syntax::IdentifierExpr { name } => {
108 | if let Some((decl_scope, symbol)) = usage_scope.find_symbol_with_scope(*name) {
109 | let decl_closure_scope = decl_scope
110 | .find_self_or_ancestor(|s| s.is_closure())
111 | .unwrap();
112 | let lifetime = if decl_closure_scope == usage_closure_scope {
113 | self.bump_stack().clone()
114 | } else {
115 | // We're in a nested closure or class.
116 | LexicalLifetime::new_infinite(self.ctx.session)
117 | };
118 | self
119 | .ctx
120 | .symbols
121 | .entry(symbol)
122 | .or_insert_with(|| MinifySymbol::new(self.ctx.session))
123 | .update_lifetime(lifetime);
124 | }
125 | }
126 | Syntax::IdentifierPattern { name } => {
127 | // TODO
128 | }
129 | Syntax::IfStmt {
130 | test,
131 | consequent,
132 | alternate,
133 | ..
134 | } => {
135 | // This appears pointless but is to workaround the fact that Rust won't allow `*alternate` or `alternate.as_ref().map(|t| *t)` or `alternate.as_mut().map(|t| *t)`.
136 | match alternate {
137 | Some(alt) => self.visit_conditional(test, consequent, Some(alt), ctl),
138 | None => self.visit_conditional(test, consequent, None, ctl),
139 | };
140 | }
141 | Syntax::ConditionalExpr {
142 | test,
143 | consequent,
144 | alternate,
145 | ..
146 | } => {
147 | self.visit_conditional(test, consequent, Some(alternate), ctl);
148 | }
149 | Syntax::ForStmt { header, body } => {
150 | // TODO
151 | }
152 | Syntax::WhileStmt { condition, body } => {
153 | // TODO
154 | }
155 | Syntax::DoWhileStmt { condition, body } => {
156 | // TODO
157 | }
158 | _ => {}
159 | };
160 | }
161 | }
162 |
--------------------------------------------------------------------------------
/rust/src/minify/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod advanced_if;
2 | pub mod ctx;
3 | pub mod lexical_lifetimes;
4 | pub mod name;
5 | pub mod pass1;
6 | pub mod pass2;
7 | pub mod pass3;
8 |
9 | use self::ctx::Ctx;
10 | use self::ctx::MinifyScope;
11 | use self::ctx::MinifySymbol;
12 | use self::name::minify_names;
13 | use self::pass1::Pass1;
14 | use self::pass2::Pass2;
15 | use self::pass3::Pass3;
16 | use parse_js::ast::new_node;
17 | use parse_js::ast::ExportName;
18 | use parse_js::ast::ExportNames;
19 | use parse_js::ast::NodeData;
20 | use parse_js::ast::Syntax;
21 | use parse_js::session::Session;
22 | use parse_js::symbol::Scope;
23 | use parse_js::symbol::Symbol;
24 | use parse_js::visit::Visitor;
25 |
26 | pub fn minify_js<'a>(session: &'a Session, top_level_node: &mut NodeData<'a>) -> () {
27 | let top_level_scope = top_level_node.scope;
28 |
29 | // Our custom data/state associated with a Symbol.
30 | let mut symbols = session.new_hashmap::();
31 | // Our custom data/state associated with a Scope.
32 | let mut scopes = session.new_hashmap::, MinifyScope<'a>>();
33 | // Exports: what they refer to and what they're named.
34 | let mut export_bindings = Vec::new();
35 |
36 | Pass1 {
37 | ctx: Ctx {
38 | scopes: &mut scopes,
39 | session,
40 | symbols: &mut symbols,
41 | },
42 | }
43 | .visit(top_level_node);
44 |
45 | Pass2 {
46 | ctx: Ctx {
47 | scopes: &mut scopes,
48 | session,
49 | symbols: &mut symbols,
50 | },
51 | }
52 | .visit(top_level_node);
53 |
54 | minify_names(session, top_level_scope, &mut scopes, &mut symbols);
55 |
56 | Pass3 {
57 | session,
58 | export_bindings: &mut export_bindings,
59 | symbols: &mut symbols,
60 | scopes: &mut scopes,
61 | }
62 | .visit(top_level_node);
63 |
64 | let mut export_names = session.new_vec();
65 | for e in export_bindings.iter() {
66 | let target_symbol = top_level_scope
67 | .find_symbol(e.target)
68 | .expect(format!("failed to find top-level export `{:?}`", e.target).as_str());
69 | export_names.push(ExportName {
70 | target: symbols[&target_symbol].minified_name.unwrap(),
71 | alias: new_node(
72 | session,
73 | top_level_scope,
74 | e.alias,
75 | Syntax::IdentifierPattern { name: e.alias },
76 | ),
77 | });
78 | }
79 |
80 | if !export_names.is_empty() {
81 | let final_export_stmt = new_node(
82 | session,
83 | top_level_scope,
84 | top_level_node.loc.at_end(),
85 | Syntax::ExportListStmt {
86 | names: ExportNames::Specific(export_names),
87 | from: None,
88 | },
89 | );
90 | match &mut top_level_node.stx {
91 | Syntax::TopLevel { body } => {
92 | body.push(final_export_stmt);
93 | }
94 | _ => unreachable!(),
95 | }
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/rust/src/minify/name.rs:
--------------------------------------------------------------------------------
1 | use super::ctx::MinifyScope;
2 | use super::ctx::MinifySymbol;
3 | use parse_js::char::ID_CONTINUE_CHARSTR;
4 | use parse_js::char::ID_START_CHARSTR;
5 | use parse_js::lex::KEYWORD_STRS;
6 | use parse_js::session::Session;
7 | use parse_js::session::SessionHashMap;
8 | use parse_js::session::SessionHashSet;
9 | use parse_js::session::SessionVec;
10 | use parse_js::source::SourceRange;
11 | use parse_js::symbol::Identifier;
12 | use parse_js::symbol::Scope;
13 | use parse_js::symbol::Symbol;
14 |
15 | // Generator of minified names. Works by generating the next smallest possible name (starting from `a`), and then repeats until it finds one that is not a keyword or would conflict with an inherited variable (a variable that is in scope **and** used by code that we would otherwise shadow).
16 | pub struct MinifiedNameGenerator<'a> {
17 | session: &'a Session,
18 | // Index of each character of the last generated name, in reverse order (i.e. first character is last element) for optimised extension.
19 | state: SessionVec<'a, usize>,
20 | }
21 |
22 | impl<'a> MinifiedNameGenerator<'a> {
23 | pub fn new(session: &'a Session) -> MinifiedNameGenerator<'a> {
24 | MinifiedNameGenerator {
25 | session,
26 | state: session.new_vec(),
27 | }
28 | }
29 |
30 | fn transition_to_next_possible_minified_name(&mut self) -> SessionVec<'a, u8> {
31 | let n = &mut self.state;
32 | let mut overflow = true;
33 | for i in 0..n.len() {
34 | let charset = if i == n.len() - 1 {
35 | ID_START_CHARSTR
36 | } else {
37 | ID_CONTINUE_CHARSTR
38 | };
39 | if n[i] == charset.len() - 1 {
40 | n[i] = 0;
41 | } else {
42 | n[i] += 1;
43 | overflow = false;
44 | break;
45 | };
46 | }
47 | if overflow {
48 | n.push(0);
49 | };
50 |
51 | let mut name = self.session.new_vec(); // TODO Capacity
52 | for (i, idx) in n.iter().enumerate() {
53 | let charset = if i == n.len() - 1 {
54 | ID_START_CHARSTR
55 | } else {
56 | ID_CONTINUE_CHARSTR
57 | };
58 | name.push(charset[*idx]);
59 | }
60 | name.reverse();
61 | name
62 | }
63 |
64 | // TODO This needs optimisation, in case inherited_vars has a long sequence of used minified names (likely).
65 | pub fn generate_next_available_minified_name(
66 | &mut self,
67 | inherited_vars: &SessionHashSet>,
68 | ) -> Identifier<'a> {
69 | loop {
70 | let name = self.transition_to_next_possible_minified_name();
71 | if KEYWORD_STRS.contains_key(name.as_slice()) {
72 | continue;
73 | };
74 | let name = self
75 | .session
76 | .get_allocator()
77 | .alloc_slice_copy(name.as_slice());
78 | let as_ident = SourceRange::new(name, 0, name.len());
79 | if inherited_vars.contains(&as_ident) {
80 | continue;
81 | };
82 | return as_ident;
83 | }
84 | }
85 | }
86 |
87 | // This should be run after Pass2 and before Pass3 visitor runs.
88 | // The Pass1 pass collects all usages of variables to determine inherited variables for each scope, so we can know what minified names can be safely used (see `MinifiedNameGenerator`). This function will then go through each declaration in each scope and generate and update their corresponding `MinifySymbol.minified_name`.
89 | // Some pecularities to note: globals aren't minified (whether declared or not), so when blacklisting minified names, they are directly disallowed. However, all other variables will be minified, so we need to blacklist their minified name, not their original name. This is why this function processes scopes top-down (from the root), as we need to know the minified names of ancestor variables first before we can blacklist them.
90 | pub fn minify_names<'a>(
91 | session: &'a Session,
92 | scope: Scope<'a>,
93 | minify_scopes: &mut SessionHashMap<'a, Scope<'a>, MinifyScope<'a>>,
94 | minify_symbols: &mut SessionHashMap<'a, Symbol, MinifySymbol<'a>>,
95 | ) {
96 | // It's possible that the entry doesn't exist, if there were no inherited variables during the first pass.
97 | let minify_scope = minify_scopes
98 | .entry(scope)
99 | .or_insert_with(|| MinifyScope::new(session));
100 | // Our `inherited_vars` contains original names; we need to retrieve their minified names.
101 | let mut minified_inherited_vars = session.new_hashset();
102 | for &original_inherited_var in minify_scope.inherited_vars.iter() {
103 | match scope.find_symbol(original_inherited_var) {
104 | None => {
105 | // Global (undeclared or declared).
106 | minified_inherited_vars.insert(original_inherited_var);
107 | }
108 | Some(sym) => {
109 | let min_sym = minify_symbols.get(&sym).unwrap();
110 | let min_name = min_sym.minified_name.unwrap();
111 | minified_inherited_vars.insert(min_name);
112 | }
113 | };
114 | }
115 | // Yes, we start from the very beginning in case there are possible gaps/opportunities due to inherited variables on ancestors.
116 | let mut next_min_name = MinifiedNameGenerator::new(session);
117 | for &sym_name in scope.symbol_names().iter() {
118 | let sym = scope.get_symbol(sym_name).unwrap();
119 | let min_sym = minify_symbols
120 | .entry(sym)
121 | .or_insert_with(|| MinifySymbol::new(session));
122 | assert!(min_sym.minified_name.is_none());
123 | if min_sym.is_used_as_jsx_component {
124 | // We'll process these in another iteration, as there's fewer characters allowed for the identifier start, and we don't want to skip past valid identifiers for non-JSX-component names.
125 | continue;
126 | };
127 | min_sym.minified_name =
128 | Some(next_min_name.generate_next_available_minified_name(&minified_inherited_vars));
129 | }
130 | for &sym_name in scope.symbol_names().iter() {
131 | let sym = scope.get_symbol(sym_name).unwrap();
132 | let min_sym = minify_symbols.get_mut(&sym).unwrap();
133 | if !min_sym.is_used_as_jsx_component {
134 | continue;
135 | };
136 | // TODO This is very slow and dumb.
137 | let mut min_name;
138 | loop {
139 | min_name = next_min_name.generate_next_available_minified_name(&minified_inherited_vars);
140 | if !min_name.as_slice()[0].is_ascii_lowercase() {
141 | break;
142 | };
143 | }
144 | min_sym.minified_name = Some(min_name)
145 | }
146 | for &c in scope.children().iter() {
147 | minify_names(session, c, minify_scopes, minify_symbols);
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/rust/src/minify/pass1.rs:
--------------------------------------------------------------------------------
1 | use super::advanced_if::analyse_if_branch;
2 | use super::advanced_if::process_if_branch;
3 | use super::ctx::Ctx;
4 | use super::ctx::MinifyScope;
5 | use super::ctx::MinifySymbol;
6 | use parse_js::ast::new_node;
7 | use parse_js::ast::NodeData;
8 | use parse_js::ast::Syntax;
9 | use parse_js::operator::Operator;
10 | use parse_js::operator::OperatorName;
11 | use parse_js::session::Session;
12 | use parse_js::visit::JourneyControls;
13 | use parse_js::visit::Visitor;
14 | use std::str::from_utf8_unchecked;
15 |
16 | // - Detect all usages of JSX components, as React determines `` to be the HTML tag and `` to be the variable `Link` as a component, so we cannot minify `Link` to `link` or `a0` or `bb` (i.e. make capitalised JSX elements uncapitalised).
17 | // - Find all references of variables so we can determine inherited variables (see `MinifiedNameGenerator` and `MinifyScope`). This is because JS allows variables to be lexically referenced before they're used, so we cannot do this in the same pass. For example, `let b = 1; { let a = () => b; let b = 2; }`.
18 | // - Find uses of `new ` and set `is_used_as_constructor`.
19 | // - Find uses of `.prototype` and set `has_prototype`.
20 | // - Combine consecutive expression statements into one.
21 | // - Convert `if (x) { expr; }` to `x && expr`.
22 | // - Convert `if (x) { expr1; } else { expr2; }` to `x ? expr1 : expr2`.
23 | // - Concatenate addition of two literal strings.
24 | // - Unwrap unnecessary block statements.
25 | // - Drop debugger statements.
26 | // - Normalise `if-else` branches into block statements.
27 | pub struct Pass1<'a, 'b> {
28 | pub ctx: Ctx<'a, 'b>,
29 | }
30 |
31 | fn stmt_has_return<'a>(stx: &Syntax<'a>) -> bool {
32 | match stx {
33 | Syntax::ReturnStmt { .. } => true,
34 | Syntax::BlockStmt { body } => body.iter().any(|n| stmt_has_return(&n.stx)),
35 | _ => false,
36 | }
37 | }
38 |
39 | // Decompose into functions for easier reasoning and testing, and more readable final top-level combined usage (i.e. `x(); y(); z()` instead of `match typ { A => { x(); y() } B => { x(); z() } C => { a() } D => { z() } }`).
40 | // Hope that the compiler inlines into one giant `match` instead of executing sequentially and bailing out one-after-another on the first syntax type condition of each function.
41 |
42 | // Wrap any consequent or alternate expression or non-block statement in a block (e.g. `if (x) a` => `if (x) { a; }`).
43 | #[inline(always)]
44 | fn maybe_ensure_if_statement_consequent_and_alternate_are_wrapped<'a, 'b>(
45 | ctx: &mut Ctx<'a, 'b>,
46 | n: &mut NodeData<'a>,
47 | ) {
48 | let Syntax::IfStmt {
49 | consequent,
50 | alternate,
51 | ..
52 | } = &mut n.stx
53 | else {
54 | return;
55 | };
56 | fn maybe_wrap<'a>(session: &'a Session, branch: &mut &mut NodeData<'a>) {
57 | match &branch.stx {
58 | // Already a block, don't need to do anything.
59 | Syntax::BlockStmt { .. } => {}
60 | _ => {
61 | let inner = branch.take(session);
62 | let wrapped = new_node(session, inner.scope, inner.loc, Syntax::BlockStmt {
63 | body: {
64 | let mut body = session.new_vec();
65 | body.push(inner);
66 | body
67 | },
68 | });
69 | // Update the original node's consequent/alternate to point to the new block we've just created.
70 | *branch = wrapped;
71 | }
72 | };
73 | }
74 | maybe_wrap(ctx.session, consequent);
75 | if let Some(alt) = alternate {
76 | maybe_wrap(ctx.session, alt);
77 | }
78 | }
79 |
80 | #[inline(always)]
81 | fn maybe_combine_string_literals<'a, 'b>(ctx: &mut Ctx<'a, 'b>, n: &mut NodeData<'a>) {
82 | let Syntax::BinaryExpr {
83 | operator: OperatorName::Addition,
84 | left: NodeData {
85 | stx: Syntax::LiteralStringExpr { value: l },
86 | ..
87 | },
88 | right: NodeData {
89 | stx: Syntax::LiteralStringExpr { value: r },
90 | ..
91 | },
92 | ..
93 | } = &mut n.stx
94 | else {
95 | return;
96 | };
97 | let concat = ctx
98 | .session
99 | .get_allocator()
100 | .alloc_slice_fill_default(l.len() + r.len());
101 | concat[..l.len()].copy_from_slice(l.as_bytes());
102 | concat[l.len()..].copy_from_slice(r.as_bytes());
103 | n.stx = Syntax::LiteralStringExpr {
104 | value: unsafe { from_utf8_unchecked(concat) },
105 | };
106 | }
107 |
108 | #[cfg(test)]
109 | mod tests {
110 | use super::Pass1;
111 | use crate::emit;
112 | use crate::minify::ctx::Ctx;
113 | use crate::minify::ctx::MinifyScope;
114 | use crate::minify::ctx::MinifySymbol;
115 | use crate::minify::pass1::maybe_combine_string_literals;
116 | use crate::minify::pass1::maybe_ensure_if_statement_consequent_and_alternate_are_wrapped;
117 | use parse_js::ast::NodeData;
118 | use parse_js::ast::Syntax;
119 | use parse_js::parse::toplevel::TopLevelMode;
120 | use parse_js::session::Session;
121 | use parse_js::symbol::Scope;
122 | use parse_js::symbol::Symbol;
123 | use parse_js::visit::JourneyControls;
124 | use parse_js::visit::Visitor;
125 |
126 | macro_rules! setup {
127 | // Rust won't expose declared vars in a macro unless we explicitly pass in their names.
128 | ($n:ident, $ctx:ident, $source:expr) => {
129 | let session = Session::new();
130 | let $n = parse_js::parse(&session, $source.as_bytes(), TopLevelMode::Global).unwrap();
131 | let mut symbols = session.new_hashmap::();
132 | let mut scopes = session.new_hashmap::, MinifyScope<'_>>();
133 | let $ctx = Ctx {
134 | scopes: &mut scopes,
135 | session: &session,
136 | symbols: &mut symbols,
137 | };
138 | };
139 | }
140 |
141 | macro_rules! check {
142 | ($root_node:expr, $expected:expr) => {
143 | let mut out = Vec::new();
144 | emit($root_node, &mut out);
145 | assert_eq!($expected, std::str::from_utf8(&out).unwrap());
146 | };
147 | }
148 |
149 | #[test]
150 | fn test_ensure_if_statement_consequent_and_alternate_are_wrapped() {
151 | struct P<'a, 'b> {
152 | pub ctx: Ctx<'a, 'b>,
153 | }
154 | impl<'a, 'b> Visitor<'a> for P<'a, 'b> {
155 | fn on_syntax_down(&mut self, n: &mut NodeData<'a>, _ctl: &mut JourneyControls) -> () {
156 | maybe_ensure_if_statement_consequent_and_alternate_are_wrapped(&mut self.ctx, n);
157 | }
158 | }
159 |
160 | setup!(n, ctx, "if (x) a;");
161 | P { ctx }.visit(n);
162 | check!(n, "if(x){a}");
163 |
164 | setup!(n, ctx, "if (x) {} else b;");
165 | P { ctx }.visit(n);
166 | check!(n, "if(x){}else{b}");
167 |
168 | setup!(n, ctx, "if (x) a; else {b}");
169 | P { ctx }.visit(n);
170 | check!(n, "if(x){a}else{b}");
171 |
172 | setup!(n, ctx, "if (x) a; else b");
173 | P { ctx }.visit(n);
174 | check!(n, "if(x){a}else{b}");
175 | }
176 |
177 | #[test]
178 | fn test_combine_string_literals() {
179 | struct P<'a, 'b> {
180 | pub ctx: Ctx<'a, 'b>,
181 | }
182 | impl<'a, 'b> Visitor<'a> for P<'a, 'b> {
183 | fn on_syntax_up(&mut self, n: &mut NodeData<'a>) -> () {
184 | maybe_combine_string_literals(&mut self.ctx, n);
185 | }
186 | }
187 |
188 | setup!(n, ctx, "'a' + 'b';");
189 | P { ctx }.visit(n);
190 | check!(n, "`ab`");
191 |
192 | setup!(n, ctx, "'a' + 'b' + 'c';");
193 | P { ctx }.visit(n);
194 | check!(n, "`abc`");
195 | }
196 | }
197 |
198 | impl<'a, 'b> Visitor<'a> for Pass1<'a, 'b> {
199 | fn on_syntax_down(&mut self, n: &mut NodeData<'a>, _ctl: &mut JourneyControls) -> () {
200 | let scope = n.scope;
201 | maybe_ensure_if_statement_consequent_and_alternate_are_wrapped(&mut self.ctx, n);
202 | match &mut n.stx {
203 | Syntax::BlockStmt { body } => {
204 | let mut i = 0;
205 | while i < body.len() {
206 | if let Syntax::IfStmt {
207 | test,
208 | consequent,
209 | alternate: maybe_alternate,
210 | } = &mut body[i].stx
211 | {
212 | if let Some(alternate) = maybe_alternate {
213 | // If `if` returns, unwrap `else`.
214 | // If `else` returns **AND** `if` does not return, swap `if` and `else`, and then unwrap `else` (post-swap).
215 | // Whatever is unwrapped becomes another statement in the current body and should be processed, not skipped.
216 | let cons_has_return = stmt_has_return(&consequent.stx);
217 | let swapped = if !cons_has_return && stmt_has_return(&alternate.stx) {
218 | core::mem::swap(consequent, alternate);
219 | let orig_test = test.take(self.ctx.session);
220 | test.stx = Syntax::UnaryExpr {
221 | parenthesised: false,
222 | operator: OperatorName::LogicalNot,
223 | argument: orig_test,
224 | };
225 | true
226 | } else {
227 | false
228 | };
229 | if swapped || cons_has_return {
230 | // We can't always double-unwrap if it's a block as the block might be necessary (e.g. `let`). We have later optimisations that will unwrap it if possible.
231 | let alternate_branch = alternate.take(self.ctx.session);
232 | *maybe_alternate = None;
233 | body.insert(i + 1, alternate_branch);
234 | }
235 | }
236 | };
237 | i += 1;
238 | }
239 | }
240 | Syntax::IdentifierExpr { name } => {
241 | self.ctx.track_variable_usage(scope, *name);
242 | }
243 | // IdentifierPattern also appears in destructuring, not just declarations. It's safe either way; if it's a declaration, its scope will have its declaration, so there will be no inheritance.
244 | Syntax::IdentifierPattern { name } => {
245 | self.ctx.track_variable_usage(scope, *name);
246 | }
247 | Syntax::MemberExpr {
248 | right: p2,
249 | optional_chaining: false,
250 | left: NodeData {
251 | stx: Syntax::IdentifierExpr { name: p1 },
252 | ..
253 | },
254 | ..
255 | } if p2.as_slice() == b"prototype" => {
256 | if let Some(sym) = scope.find_symbol(*p1) {
257 | self
258 | .ctx
259 | .symbols
260 | .entry(sym)
261 | .or_insert_with(|| MinifySymbol::new(self.ctx.session))
262 | .has_prototype = true;
263 | };
264 | }
265 | Syntax::UnaryExpr {
266 | parenthesised: _,
267 | operator: OperatorName::New,
268 | argument,
269 | } => {
270 | let var_name = match &argument.stx {
271 | // e.g. `new Array()`.
272 | Syntax::CallExpr { callee, .. } => match &callee.stx {
273 | Syntax::IdentifierExpr { name } => Some(*name),
274 | _ => None,
275 | },
276 | // e.g. `new Array`.
277 | Syntax::IdentifierExpr { name } => Some(*name),
278 | _ => None,
279 | };
280 | if let Some(var_name) = var_name {
281 | if let Some(sym) = scope.find_symbol(var_name) {
282 | self
283 | .ctx
284 | .symbols
285 | .entry(sym)
286 | .or_insert_with(|| MinifySymbol::new(self.ctx.session))
287 | .is_used_as_constructor = true;
288 | };
289 | };
290 | }
291 | Syntax::JsxElement {
292 | name:
293 | Some(NodeData {
294 | stx: Syntax::IdentifierExpr { name },
295 | ..
296 | }),
297 | ..
298 | } => {
299 | if let Some(sym) = n.scope.find_symbol(*name) {
300 | self
301 | .ctx
302 | .symbols
303 | .entry(sym)
304 | .or_insert_with(|| MinifySymbol::new(self.ctx.session))
305 | .is_used_as_jsx_component = true;
306 | };
307 | }
308 | _ => {}
309 | }
310 | }
311 |
312 | fn on_syntax_up(&mut self, node: &mut NodeData<'a>) -> () {
313 | let loc = node.loc;
314 | let scope = node.scope;
315 | match &mut node.stx {
316 | // This is bottom-up as we could remove nested blocks recursively.
317 | Syntax::BlockStmt { body } => {
318 | let mut returned = false;
319 | // Next writable slot when shifting down due to gaps from deleting merged ExpressionStmt values.
320 | let mut w = 0;
321 | // Next readable slot to process.
322 | let mut r = 0;
323 | // We can't use a for loop or cache `body.len()` as it might change (e.g. unpacking redundant block statement).
324 | while r < body.len() {
325 | if returned {
326 | // Drop remaining unreachable code.
327 | // TODO There may be more code outside this block that's now unreachable and can be removed.
328 | break;
329 | };
330 | // Get `scope` before we borrow mutably for `stx`.
331 | let r_scope = body[r].scope;
332 | let keep = match &mut body[r].stx {
333 | // NOTE: We must match here as BlockStmt may not always be a block statement (e.g. `for`, `while`, function bodies).
334 | Syntax::BlockStmt { body: block_body } => {
335 | if block_body.is_empty() {
336 | false
337 | } else if r_scope.symbol_names().is_empty() {
338 | // This block statement doesn't have any block-scoped declarations, so it's unnecessary.
339 | let mut to_add = self.ctx.session.new_vec();
340 | for s in block_body {
341 | to_add.push(s.take(self.ctx.session));
342 | }
343 | // Insert after current `r` so we process these next.
344 | body.splice(r + 1..r + 1, to_add);
345 | false
346 | } else {
347 | true
348 | }
349 | }
350 | Syntax::ExpressionStmt { expression: _ } => {
351 | // TODO Remove if pure.
352 | true
353 | }
354 | Syntax::ReturnStmt { .. } => {
355 | returned = true;
356 | true
357 | }
358 | _ => true,
359 | };
360 | if keep {
361 | body.swap(w, r);
362 | w += 1;
363 | };
364 | r += 1;
365 | }
366 | body.truncate(w);
367 | }
368 | Syntax::IfStmt {
369 | test,
370 | consequent,
371 | alternate,
372 | } => {
373 | // Note that we cannot process unless both branches can be processed, otherwise we'll be left with one branch mutated.
374 | let cons_ok = analyse_if_branch(&consequent.stx);
375 | let alt_ok = alternate.as_ref().map(|alt| analyse_if_branch(&alt.stx));
376 |
377 | match (cons_ok, alt_ok) {
378 | (true, None) => {
379 | let closure_scope = scope.find_self_or_ancestor(|t| t.is_closure()).unwrap();
380 | let cons_expr = process_if_branch(self.ctx.session, scope, consequent);
381 | let min_scope = self
382 | .ctx
383 | .scopes
384 | .entry(closure_scope)
385 | .or_insert_with(|| MinifyScope::new(self.ctx.session));
386 | min_scope
387 | .hoisted_vars
388 | .extend_from_slice(&cons_expr.hoisted_vars);
389 | if cons_expr.returns {
390 | consequent.stx = Syntax::ReturnStmt {
391 | value: Some(cons_expr.expression),
392 | };
393 | } else {
394 | let right = cons_expr.expression;
395 | let test = test.take(self.ctx.session);
396 | node.stx = Syntax::ExpressionStmt {
397 | expression: new_node(self.ctx.session, scope, loc, Syntax::BinaryExpr {
398 | parenthesised: false,
399 | operator: OperatorName::LogicalAnd,
400 | left: test,
401 | right,
402 | }),
403 | };
404 | }
405 | }
406 | (true, Some(true)) => {
407 | let closure_scope = scope.find_self_or_ancestor(|t| t.is_closure()).unwrap();
408 | let cons_expr = process_if_branch(self.ctx.session, scope, consequent);
409 | let alt_expr = process_if_branch(self.ctx.session, scope, alternate.as_mut().unwrap());
410 | let min_scope = self
411 | .ctx
412 | .scopes
413 | .entry(closure_scope)
414 | .or_insert_with(|| MinifyScope::new(self.ctx.session));
415 | min_scope
416 | .hoisted_vars
417 | .extend_from_slice(&cons_expr.hoisted_vars);
418 | min_scope
419 | .hoisted_vars
420 | .extend_from_slice(&alt_expr.hoisted_vars);
421 | // Due to normalisation, it's not possible for an `if-else` to return in either branch, because one branch would've been unwrapped.
422 | assert!(cons_expr.returns && alt_expr.returns);
423 | let test = test.take(self.ctx.session);
424 | let consequent = cons_expr.expression;
425 | let alternate = alt_expr.expression;
426 | node.stx = Syntax::ExpressionStmt {
427 | expression: new_node(self.ctx.session, scope, loc, Syntax::ConditionalExpr {
428 | parenthesised: false,
429 | test,
430 | consequent,
431 | alternate,
432 | }),
433 | };
434 | }
435 | _ => {}
436 | };
437 | }
438 | _ => {}
439 | };
440 | }
441 | }
442 |
--------------------------------------------------------------------------------
/rust/src/minify/pass2.rs:
--------------------------------------------------------------------------------
1 | use super::ctx::Ctx;
2 | use super::ctx::MinifyScope;
3 | use parse_js::ast::NodeData;
4 | use parse_js::ast::Syntax;
5 | use parse_js::visit::Visitor;
6 |
7 | // - Move function declarations into `hoisted_functions`, so we can then place them back in the tree at the top of a closure in the next pass.
8 | pub struct Pass2<'a, 'b> {
9 | pub ctx: Ctx<'a, 'b>,
10 | }
11 |
12 | impl<'a, 'b> Visitor<'a> for Pass2<'a, 'b> {
13 | fn on_syntax_up(&mut self, n: &mut NodeData<'a>) -> () {
14 | let scope = n.scope;
15 | // This needs to be done when we iterate upwards and not downwards:
16 | // - If we do it while iterating down, we won't traverse the function declaration's subtree, which we still need to do for the other tasks (e.g. tracking inherited variables).
17 | // - It makes sense to cut out the pieces inside out (i.e. the nested parts that are function declarations), instead of removing the entire function declaration which itself may have some nested function declarations alongside other things.
18 | // TODO Consider `export` and `export default`.
19 | let named_fn_decl_name = match &n.stx {
20 | Syntax::FunctionDecl {
21 | export: false,
22 | name: Some(name),
23 | ..
24 | } => Some(name.loc),
25 | _ => None,
26 | };
27 | if let Some(name) = named_fn_decl_name {
28 | let decl_scope = scope
29 | .find_self_or_ancestor(|t| t.is_closure_or_global())
30 | .unwrap();
31 | self
32 | .ctx
33 | .scopes
34 | .entry(decl_scope)
35 | .or_insert_with(|| MinifyScope::new(self.ctx.session))
36 | .hoisted_functions
37 | .insert(name, n.replace(self.ctx.session, Syntax::EmptyStmt {}));
38 | return;
39 | };
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/rust/src/minify/pass3.rs:
--------------------------------------------------------------------------------
1 | use super::ctx::MinifyScope;
2 | use super::ctx::MinifySymbol;
3 | use parse_js::ast::new_node;
4 | use parse_js::ast::ClassOrObjectMemberKey;
5 | use parse_js::ast::ClassOrObjectMemberValue;
6 | use parse_js::ast::ExportNames;
7 | use parse_js::ast::NodeData;
8 | use parse_js::ast::ObjectMemberType;
9 | use parse_js::ast::Syntax;
10 | use parse_js::ast::VarDeclMode;
11 | use parse_js::ast::VariableDeclarator;
12 | use parse_js::flag::Flags;
13 | use parse_js::session::Session;
14 | use parse_js::session::SessionHashMap;
15 | use parse_js::source::SourceRange;
16 | use parse_js::symbol::Scope;
17 | use parse_js::symbol::ScopeFlag;
18 | use parse_js::symbol::Symbol;
19 | use parse_js::visit::JourneyControls;
20 | use parse_js::visit::Visitor;
21 |
22 | pub struct ExportBinding<'a> {
23 | pub target: SourceRange<'a>,
24 | pub alias: SourceRange<'a>,
25 | }
26 |
27 | fn unwrap_block_statement_if_possible<'a>(session: &'a Session, node: &mut NodeData<'a>) {
28 | if let Syntax::BlockStmt { body } = &mut node.stx {
29 | if body.len() == 1 {
30 | let stmt = body[0].take(session);
31 | core::mem::swap(node, stmt);
32 | };
33 | };
34 | }
35 |
36 | // This should be run after the `minify_names` function.
37 | pub struct Pass3<'a, 'b> {
38 | pub session: &'a Session,
39 | // Exports with the same exported name (including multiple default exports) are illegal, so we don't have to worry about/handle that case.
40 | pub export_bindings: &'b mut Vec>,
41 | pub symbols: &'b mut SessionHashMap<'a, Symbol, MinifySymbol<'a>>,
42 | pub scopes: &'b mut SessionHashMap<'a, Scope<'a>, MinifyScope<'a>>,
43 | }
44 |
45 | impl<'a, 'b> Pass3<'a, 'b> {
46 | fn visit_exported_pattern(&mut self, n: &mut NodeData<'a>) -> () {
47 | match &mut n.stx {
48 | Syntax::ArrayPattern { elements, rest } => {
49 | for e in elements {
50 | if let Some(e) = e {
51 | self.visit_exported_pattern(e.target);
52 | }
53 | }
54 | if let Some(rest) = rest {
55 | self.visit_exported_pattern(*rest);
56 | }
57 | }
58 | Syntax::ObjectPattern { properties, rest } => {
59 | for p in properties {
60 | self.visit_exported_pattern(*p);
61 | }
62 | if let Some(rest) = rest {
63 | self.visit_exported_pattern(*rest);
64 | }
65 | }
66 | Syntax::ObjectPatternProperty { target, .. } => {
67 | self.visit_exported_pattern(*target);
68 | }
69 | Syntax::IdentifierPattern { name } => self.export_bindings.push(ExportBinding {
70 | target: *name,
71 | alias: *name,
72 | }),
73 | _ => unreachable!(),
74 | }
75 | }
76 | }
77 |
78 | impl<'a, 'b> Visitor<'a> for Pass3<'a, 'b> {
79 | fn on_syntax_down(&mut self, node: &mut NodeData<'a>, ctl: &mut JourneyControls) -> () {
80 | // We must not use `node.` after this point, as we're now borrowing it as mut.
81 | let loc = node.loc;
82 | let scope = node.scope;
83 | let mut new_stx: Option> = None;
84 | match &mut node.stx {
85 | Syntax::TopLevel { body } | Syntax::BlockStmt { body } => {
86 | // TODO Are all global/closure scopes associated with exactly one BlockStmt or TopLevel?
87 | if scope.typ().is_closure_or_global() {
88 | if let Some(min_scope) = self.scopes.get_mut(&scope) {
89 | if !min_scope.hoisted_vars.is_empty() {
90 | body.insert(
91 | 0,
92 | new_node(self.session, scope, loc, Syntax::VarDecl {
93 | export: false,
94 | mode: VarDeclMode::Var,
95 | declarators: {
96 | let mut decls = self.session.new_vec();
97 | for v in min_scope.hoisted_vars.iter() {
98 | decls.push(VariableDeclarator {
99 | pattern: new_node(self.session, scope, loc, Syntax::IdentifierPattern {
100 | name: *v,
101 | }),
102 | initializer: None,
103 | })
104 | }
105 | decls
106 | },
107 | }),
108 | );
109 | }
110 | for fn_decl in min_scope.hoisted_functions.values_mut() {
111 | // TODO Batch prepend to avoid repeated Vec shifting.
112 | body.insert(0, fn_decl.take(self.session));
113 | }
114 | };
115 | };
116 | }
117 | Syntax::ArrowFunctionExpr {
118 | parenthesised,
119 | is_async,
120 | signature,
121 | body,
122 | } => {
123 | if let Syntax::BlockStmt { body } = &mut body.stx {
124 | if body.len() == 1 {
125 | if let Syntax::ReturnStmt { value } = &mut body[0].stx {
126 | if let Some(return_value) = value {
127 | new_stx = Some(Syntax::ArrowFunctionExpr {
128 | parenthesised: *parenthesised,
129 | is_async: *is_async,
130 | signature: signature.take(self.session),
131 | body: return_value.take(self.session),
132 | });
133 | }
134 | };
135 | };
136 | };
137 | }
138 | Syntax::FunctionExpr {
139 | parenthesised: _,
140 | is_async,
141 | generator: false,
142 | name: None,
143 | signature,
144 | body,
145 | } => {
146 | let fn_scope = body.scope;
147 | // TODO This will still work for named functions as long as that name isn't used (including if it's shadowed).
148 | // TODO Detect property access of "prototype" on variable referencing function to reduce (but not remove) false negatives.
149 | // TODO Can this work sometimes even when `arguments` is used?
150 | // TODO This is still not risk-free, as the function's prototype could still be used even if there is no `this`.
151 | // TODO Detect `function(){}.bind(this)`, which is pretty much risk free unless somehow Function.prototype.bind has been overridden. However, any other value for the first argument of `.bind` means that it is no longer safe.
152 | if !fn_scope
153 | .flags()
154 | .has_any(ScopeFlag::UsesArguments | ScopeFlag::UsesThis)
155 | {
156 | new_stx = Some(Syntax::ArrowFunctionExpr {
157 | // TODO
158 | parenthesised: true,
159 | is_async: *is_async,
160 | signature: signature.take(self.session),
161 | body: body.take(self.session),
162 | });
163 | };
164 | }
165 | Syntax::FunctionDecl {
166 | export: false,
167 | body,
168 | generator: false,
169 | is_async,
170 | name: Some(name),
171 | signature,
172 | ..
173 | } => {
174 | let fn_scope = body.scope;
175 | // TODO Consider `export function` and `export default function`.
176 | // TODO Detect property access of "prototype" on variable referencing function to reduce (but not remove) false negatives.
177 | // TODO Can this work sometimes even when `arguments` is used?
178 | // TODO This is still not risk-free, as the function's prototype could still be used even if there is no `this`.
179 | // TODO Detect `function(){}.bind(this)`, which is pretty much risk free unless somehow Function.prototype.bind has been overridden. However, any other value for the first argument of `.bind` means that it is no longer safe.
180 | if !fn_scope.flags().has_any(ScopeFlag::UsesArguments | ScopeFlag::UsesThis)
181 | // Use `find_symbol` as we might not be in a closure scope and the function declaration's symbol would've been added to an ancestor.
182 | // If no symbol is found (e.g. global), or it exists but is not `is_used_as_constructor` and not `has_prototype`, then we can safely proceed.
183 | && scope.find_symbol(name.loc).and_then(|sym| self.symbols.get(&sym)).filter(|sym| sym.is_used_as_constructor || sym.has_prototype).is_none()
184 | {
185 | let var_decl_pat = new_node(
186 | self.session,
187 | // TODO Is this scope correct?
188 | scope,
189 | name.loc,
190 | Syntax::IdentifierPattern { name: name.loc },
191 | );
192 | let var_decl_init = new_node(
193 | self.session,
194 | // TODO Is this scope correct?
195 | scope,
196 | loc,
197 | Syntax::ArrowFunctionExpr {
198 | // TODO
199 | parenthesised: true,
200 | is_async: *is_async,
201 | signature: signature.take(self.session),
202 | body: body.take(self.session),
203 | },
204 | );
205 |
206 | new_stx = Some(Syntax::VarDecl {
207 | export: false,
208 | // We must use `var` to have the same hoisting and shadowing semantics.
209 | // TODO Are there some differences e.g. reassignment, shadowing, hoisting, redeclaration, and use-before-assignment/declaration?
210 | mode: VarDeclMode::Var,
211 | declarators: {
212 | let mut vec = self.session.new_vec();
213 | vec.push(VariableDeclarator {
214 | pattern: var_decl_pat,
215 | initializer: Some(var_decl_init),
216 | });
217 | vec
218 | },
219 | });
220 | }
221 | }
222 | Syntax::IdentifierPattern { name } => {
223 | let sym = scope.find_symbol(*name);
224 | if let Some(sym) = sym {
225 | let minified = self.symbols[&sym].minified_name.unwrap();
226 | new_stx = Some(Syntax::IdentifierPattern { name: minified });
227 | };
228 | }
229 | Syntax::IdentifierExpr { name } => {
230 | let sym = scope.find_symbol(*name);
231 | if let Some(sym) = sym {
232 | let minified = self.symbols[&sym].minified_name.unwrap();
233 | new_stx = Some(Syntax::IdentifierExpr { name: minified });
234 | };
235 | }
236 | Syntax::ClassOrFunctionName { name } => {
237 | let sym = scope.find_symbol(*name);
238 | if let Some(sym) = sym {
239 | let minified = self.symbols[&sym].minified_name.unwrap();
240 | new_stx = Some(Syntax::ClassOrFunctionName { name: minified });
241 | };
242 | }
243 | Syntax::ClassDecl {
244 | export: true,
245 | export_default,
246 | name,
247 | ..
248 | }
249 | | Syntax::FunctionDecl {
250 | export: true,
251 | export_default,
252 | name,
253 | ..
254 | } => {
255 | if let Some(name) = name {
256 | match &name.stx {
257 | Syntax::ClassOrFunctionName { name } => {
258 | self.export_bindings.push(ExportBinding {
259 | target: *name,
260 | alias: if *export_default {
261 | SourceRange::from_slice(b"default")
262 | } else {
263 | *name
264 | },
265 | });
266 | }
267 | _ => unreachable!(),
268 | };
269 | }
270 | }
271 | Syntax::VarDecl {
272 | export: true,
273 | declarators,
274 | ..
275 | } => {
276 | for decl in declarators.iter_mut() {
277 | self.visit_exported_pattern(decl.pattern);
278 | }
279 | }
280 | Syntax::ExportListStmt { names, from } => {
281 | ctl.skip();
282 | match from {
283 | None => match names {
284 | ExportNames::Specific(names) => {
285 | for e in names {
286 | self.export_bindings.push(ExportBinding {
287 | target: e.target,
288 | alias: match &e.alias.stx {
289 | Syntax::IdentifierPattern { name } => *name,
290 | _ => unreachable!(),
291 | },
292 | });
293 | new_stx = Some(Syntax::EmptyStmt {});
294 | }
295 | }
296 | ExportNames::All(_) => unreachable!(),
297 | },
298 | // `export ... from ...` do not touch/alter the module's scope, so we can ignore completely.
299 | _ => {}
300 | }
301 | }
302 | Syntax::ObjectPatternProperty {
303 | key: ClassOrObjectMemberKey::Direct(name),
304 | target,
305 | shorthand: true,
306 | default_value,
307 | ..
308 | } => {
309 | if scope.find_symbol(*name).is_some() {
310 | // If the symbol declaration exists, we know it definitely has a minified name. However, because the parser recurses into changed subtrees, we must simply expand this property with a IdentifierPattern target referencing the original name, so that the visitor for it will then change it to the minified name. Otherwise, we'll retrieve the minified name for a minified name, which is incorrect. Note that we can't simply skip the subtree entirely as there are still other parts.
311 | new_stx = Some(Syntax::ObjectPatternProperty {
312 | key: ClassOrObjectMemberKey::Direct(*name),
313 | target: target.take(self.session),
314 | default_value: default_value.take(),
315 | shorthand: false,
316 | });
317 | };
318 | }
319 | Syntax::ObjectMember {
320 | typ: ObjectMemberType::Shorthand { identifier },
321 | } => {
322 | let name = identifier.loc;
323 | if scope.find_symbol(name).is_some() {
324 | // See Syntax::ObjectPatternProperty match branch.
325 | let replacement_initializer_node = identifier.take(self.session);
326 | new_stx = Some(Syntax::ObjectMember {
327 | typ: ObjectMemberType::Valued {
328 | key: ClassOrObjectMemberKey::Direct(name),
329 | value: ClassOrObjectMemberValue::Property {
330 | initializer: Some(replacement_initializer_node),
331 | },
332 | },
333 | });
334 | };
335 | }
336 | _ => {}
337 | };
338 |
339 | if let Some(new_stx) = new_stx {
340 | node.stx = new_stx;
341 | }
342 | }
343 |
344 | fn on_syntax_up(&mut self, node: &mut NodeData<'a>) -> () {
345 | match &mut node.stx {
346 | Syntax::IfStmt {
347 | consequent,
348 | alternate,
349 | ..
350 | } => {
351 | unwrap_block_statement_if_possible(self.session, consequent);
352 | if let Some(alt) = alternate {
353 | unwrap_block_statement_if_possible(self.session, alt);
354 | }
355 | }
356 | Syntax::WhileStmt { body, .. }
357 | | Syntax::DoWhileStmt { body, .. }
358 | | Syntax::ForStmt { body, .. } => {
359 | unwrap_block_statement_if_possible(self.session, body);
360 | }
361 | _ => {}
362 | };
363 | }
364 | }
365 |
--------------------------------------------------------------------------------
/version:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | "use strict";
4 |
5 | const { readFileSync, writeFileSync } = require("fs");
6 | const { spawnSync } = require("child_process");
7 |
8 | const currentVersion = /^version = "(\d+)\.(\d+)\.(\d+)"\s*$/m
9 | .exec(readFileSync("rust/Cargo.toml", "utf8"))
10 | .slice(1)
11 | .map((n) => Number.parseInt(n, 10));
12 |
13 | const assertBetween = (n, min, max) => {
14 | if (n < min || n > max) {
15 | throw new Error("Invalid argument");
16 | }
17 | return n;
18 | };
19 |
20 | const newVersion = currentVersion.slice();
21 | let versionPart = assertBetween(
22 | ["major", "minor", "patch"].indexOf(process.argv[2].toLowerCase()),
23 | 0,
24 | 2
25 | );
26 | newVersion[versionPart++]++;
27 | while (versionPart < 3) {
28 | newVersion[versionPart++] = 0;
29 | }
30 |
31 | console.log(`${currentVersion.join(".")} => ${newVersion.join(".")}`);
32 |
33 | const NEW_VERSION = newVersion.join(".");
34 |
35 | const cmd = (...cfg) => {
36 | const command = cfg[0];
37 | const args = cfg.slice(1);
38 | const {
39 | workingDir,
40 | throwOnBadStatus = true,
41 | throwOnSignal = true,
42 | captureStdio = false,
43 | throwOnStdErr = false,
44 | } = typeof args[args.length - 1] == "object" ? args.pop() : {};
45 |
46 | const throwErr = (msg) => {
47 | throw new Error(`${msg}\n ${command} ${args.join(" ")}`);
48 | };
49 |
50 | const { status, signal, error, stdout, stderr } = spawnSync(
51 | command,
52 | args.map(String),
53 | {
54 | cwd: workingDir,
55 | stdio: [
56 | "ignore",
57 | captureStdio ? "pipe" : "inherit",
58 | captureStdio || throwOnStdErr ? "pipe" : "inherit",
59 | ],
60 | encoding: "utf8",
61 | }
62 | );
63 | if (error) {
64 | throwErr(error.message);
65 | }
66 | if (throwOnSignal && signal) {
67 | throwErr(`Command exited with signal ${signal}`);
68 | }
69 | if (throwOnBadStatus && status !== 0) {
70 | throwErr(`Command exited with status ${status}`);
71 | }
72 | if (throwOnStdErr && stderr) {
73 | throwErr(`stderr: ${stderr}`);
74 | }
75 | return { status, signal, stdout, stderr };
76 | };
77 |
78 | const replaceInFile = (path, pattern, replacement) =>
79 | writeFileSync(path, readFileSync(path, "utf8").replace(pattern, replacement));
80 |
81 | if (
82 | cmd("git", "status", "--porcelain", {
83 | throwOnStderr: true,
84 | captureStdio: true,
85 | }).stdout
86 | ) {
87 | throw new Error("Working directory not clean");
88 | }
89 | cmd("git", "pull");
90 | cmd("cargo", "test", "--features", "serialize");
91 |
92 | for (const f of ["rust/Cargo.toml", "cli/Cargo.toml", "nodejs/Cargo.toml"]) {
93 | replaceInFile(f, /^version = "\d+\.\d+\.\d+"/m, `version = "${NEW_VERSION}"`);
94 | }
95 |
96 | for (const f of ["nodejs/Cargo.toml"]) {
97 | replaceInFile(
98 | f,
99 | /^(minify-js = { version = )"\d+\.\d+\.\d+"/m,
100 | `$1"${NEW_VERSION}"`
101 | );
102 | }
103 |
104 | for (const f of ["nodejs/package.json"]) {
105 | replaceInFile(
106 | f,
107 | /^(\s*"version": )"\d+\.\d+\.\d+",\s*$/m,
108 | `$1"${NEW_VERSION}",`
109 | );
110 | }
111 |
112 | for (const f of ["README.md"]) {
113 | replaceInFile(f, /^(minify-js = )"\d+\.\d+\.\d+"/m, `$1"${NEW_VERSION}"`);
114 | }
115 |
116 | for (const f of ["README.md"]) {
117 | replaceInFile(
118 | f,
119 | /(static.wilsonl\.in\/minify-js\/(?:bench|cli)\/)\d+\.\d+\.\d+/g,
120 | `$1${NEW_VERSION}`
121 | );
122 | }
123 |
124 | cmd("cargo", "generate-lockfile");
125 | cmd("git", "add", "-A");
126 | cmd("git", "commit", "-m", NEW_VERSION);
127 | cmd("git", "tag", "-a", `v${NEW_VERSION}`, "-m", "");
128 | cmd("cargo", "publish", "--allow-dirty", { workingDir: "rust" });
129 | cmd("git", "push", "--follow-tags");
130 |
--------------------------------------------------------------------------------