file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
crates/swc_ecma_parser/tests/typescript/stc/0001/input.ts | TypeScript | var obj2 = {
0B11111111111111111111111111111111111111111111111101001010100000010111110001111111111: false,
}
obj2["9.671406556917009e+24"]; // boolean
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/stc/0002/input.ts | TypeScript | obj2[9.671406556917009e+24]; | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/template-literal-type/input.ts | TypeScript | type MyAlias = `some-value`;
type OtherAlias =
| `some`
| `text`;
type MultiLine = `
some value
`;
type WithTypes = `with-a-${string}`;
type WithTypes2 = `with-a-${MyAlias}-end`;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/top-level-await/input.ts | TypeScript | await 1 + 2
await 1 * 2
await 1 || 2
await null ?? 3
await a instanceof await b
await a in await b
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/ts-import-type/input.ts | TypeScript | type Vite = typeof import("vite", {
with: {
"resolution-mode": "import"
}
});
type Vite2 = typeof import("vite",);
type Vite3 = typeof import("vite");
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/tsx/brace-is-block/input.ts | TypeScript | // Regression test for tokenizer bug where the `{` after `<T>` was considered a JSX interpolation.
class C extends D<T> {}
<C/>
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/tsx/type-arguments/input.ts | TypeScript | f<T>();
new C<T>();
type A = T<T>; | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/tsx/type-parameters/input.ts | TypeScript | function f(): <T>() => number {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/type-alias/declare/input.ts | TypeScript | declare type T = number;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/type-alias/export/input.ts | TypeScript | export type T = number;
// `export default type` is not valid.
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/type-alias/generic-complex/input.ts | TypeScript | type T<U extends object = { x: number }> = Array<U>;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/type-alias/generic/input.ts | TypeScript | type T<U> = U;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/type-alias/plain/input.ts | TypeScript | type T = number;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/type-arguments/call/input.ts | TypeScript | f<T>();
f<T, U>();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/type-arguments/new-false-positive/input.ts | TypeScript | new A < T;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/type-arguments/new/input.ts | TypeScript | new C<T>();
new C<T, U>();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/type-arguments/tagged-template-no-asi/input.ts | TypeScript | new C<T>
``
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/type-arguments/tagged-template/input.ts | TypeScript | f<T>``;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/type-arguments/tsx/input.ts | TypeScript | <C<number>></C>;
<C<number>/>;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/type-arguments/whitespace/input.ts | TypeScript | function f< T >() {} | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/array/input.ts | TypeScript | let arr: number[][];
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/conditional-infer-extends/basic/input.ts | TypeScript | type X1<T extends any[]> =
T extends [infer U extends string] ? ["string", U] :
T extends [infer U extends number] ? ["number", U] :
never;
type X2<T extends (...args: any[]) => void> =
T extends (a: infer U extends string) => void ? ["string", U] :
T extends (a: infer U extends number) => void ? ["number", U] :
never;
type X3<T extends (...args: any[]) => any> =
T extends (...args: any[]) => (infer U extends string) ? ["string", U] :
T extends (...args: any[]) => (infer U extends number) ? ["number", U] :
never;
type X4<T extends new (...args: any[]) => any> =
T extends new (...args: any[]) => (infer U extends { a: string }) ? ["string", U] :
T extends new (...args: any[]) => (infer U extends { a: number }) ? ["number", U] :
never;
type X5<T> =
T extends Promise<infer U extends string> ? ["string", U] :
T extends Promise<infer U extends number> ? ["number", U] :
never;
type X6<T> =
T extends { a: infer U extends string } ? ["string", U] :
T extends { a: infer U extends number } ? ["number", U] :
never;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/conditional-infer-extends/distinguishing/input.ts | TypeScript | type X10<T> = T extends (infer U extends number ? 1 : 0) ? 1 : 0; // ok, parsed as conditional
type X11<T> = T extends ((infer U) extends number ? 1 : 0) ? 1 : 0; // ok, parsed as conditional
type X12<T> = T extends (infer U extends number) ? 1 : 0; // ok, parsed as `infer..extends` (no trailing `?`)
type X13<T> = T extends infer U extends number ? 1 : 0; // ok, parsed as `infer..extends` (conditional types not allowed in 'extends type')
type X14<T> = T extends keyof infer U extends number ? 1 : 0; // ok, parsed as `infer..extends` (precedence wouldn't have parsed the `?` as part of a type operator)
type X15<T> = T extends { [P in infer U extends keyof T ? 1 : 0]: 1; } ? 1 : 0; // ok, parsed as conditional
type X16<T> = T extends { [P in infer U extends keyof T]: 1; } ? 1 : 0; // ok, parsed as `infer..extends` (no trailing `?`)
type X17<T> = T extends { [P in keyof T as infer U extends P ? 1 : 0]: 1; } ? 1 : 0; // ok, parsed as conditional
type X18<T> = T extends { [P in keyof T as infer U extends P]: 1; } ? 1 : 0; // ok, parsed as `infer..extends` (no trailing `?`)
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/conditional-infer/input.ts | TypeScript | type Element<T> = T extends (infer U)[] ? U : T;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/conditional/input.ts | TypeScript | let x: number extends string ? boolean : null;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/function-generic/input.ts | TypeScript | let f: <T>(a: T) => T;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/function-in-generic/input.ts | TypeScript | let x: Array<() => void>;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/function-with-this/input.ts | TypeScript | let f: (this: number) => void;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/function/input.ts | TypeScript | let f: (a: number, b?: number, ...c: number[]) => void;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/indexed/input.ts | TypeScript | let x: T[K];
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/keywords/input.ts | TypeScript | let a: any;
let un: unknown;
let b: boolean;
let ne: never;
let nul: null;
let num: number;
let o: object;
let st: string;
let sy: symbol;
let u: undefined;
let v: void;
let n: bigint;
let i: intrinsic;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/literal-boolean/input.ts | TypeScript | let x: true;
let x: false;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/literal-number-negative/input.ts | TypeScript | let x: -1;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/literal-number/input.ts | TypeScript | let x: 0;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/literal-string/input.ts | TypeScript | let x: "foo";
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/mapped/input.ts | TypeScript | let map: { [P in string]: number; };
let map: { readonly [P in string]?: number; };
let map: { +readonly [P in string]+?: number; };
let map: { -readonly [P in string]-?: number };
let map: { [P in string as string]: number };
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/object-shorthand/input.ts | TypeScript | const table = {
put<T extends { id: string }>(value: T) {
// actually put.
}
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/parenthesized/input.ts | TypeScript | type T = ({});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/reference-generic-nested/input.ts | TypeScript | let x: Array<Array<number>>;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/reference-generic/input.ts | TypeScript | let x: Array<number>;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/reference/input.ts | TypeScript | let x: T;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/tuple-empty/input.ts | TypeScript | let x: [];
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/tuple-optional/input.ts | TypeScript | let x: [string, number?, (string | number)?]
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/tuple-rest-after-optional/input.ts | TypeScript | function foo(...args: [number, string?, ...number[]]) {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/tuple-rest/input.ts | TypeScript | let x: [string, ...number[]]
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/tuple/input.ts | TypeScript | let x: [number, number, number];
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/type-literal/input.ts | TypeScript | let obj: { x: number };
// Type literals have the same body syntax as interfaces, so see `interface` directory for that.
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/type-operator/input.ts | TypeScript | let x: keyof T;
let y: unique symbol;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/typeof/input.ts | TypeScript | let x: typeof y.z;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/types/union-intersection/input.ts | TypeScript | let union: number | null | undefined;
let intersection: number & string;
let precedence1: number | string & boolean;
let precedence2: number & string | boolean;
type LeadingUnion =
| string
| number;
type LeadingIntersection =
& number
& string;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/v4/issue-864/input.ts | TypeScript | type Strings = [string, string];
type Numbers = [number, number];
// [string, string, number, number]
type StrStrNumNum = [...Strings, ...Numbers]; // works now | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/v4/issue-865/input.ts | TypeScript | type Range = [start: number, end: number];
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/v4/issue-866/input.ts | TypeScript | a &&= b;
a ||= b;
a ??= b; | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/v4/issue-941/input.ts | TypeScript | try {
} catch (e: unknown) {
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/v4/optional-tuple-element/input.ts | TypeScript | type Foo = [first: number, second?: string, ...rest: any[]];
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/variable-declarator/definite-assignment/input.ts | TypeScript | let x!: number;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/variance-annotations/1/input.ts | TypeScript | type Covariant<out T> = {
x: T;
}
declare let super_covariant: Covariant<unknown>;
declare let sub_covariant: Covariant<string>;
super_covariant = sub_covariant;
sub_covariant = super_covariant; // Error
type Contravariant<in T> = {
f: (x: T) => void;
}
declare let super_contravariant: Contravariant<unknown>;
declare let sub_contravariant: Contravariant<string>;
super_contravariant = sub_contravariant; // Error
sub_contravariant = super_contravariant;
type Invariant<in out T> = {
f: (x: T) => T;
}
declare let super_invariant: Invariant<unknown>;
declare let sub_invariant: Invariant<string>;
super_invariant = sub_invariant; // Error
sub_invariant = super_invariant; // Error
// Variance of various type constructors
type T10<out T> = T;
type T11<in T> = keyof T;
type T12<out T, out K extends keyof T> = T[K];
type T13<in out T> = T[keyof T];
// Variance annotation errors
type Covariant1<in T> = { // Error
x: T;
}
type Contravariant1<out T> = keyof T; // Error
type Contravariant2<out T> = { // Error
f: (x: T) => void;
}
type Invariant1<in T> = { // Error
f: (x: T) => T;
}
type Invariant2<out T> = { // Error
f: (x: T) => T;
}
// Variance in circular types
type Foo1<in T> = { // Error
x: T;
f: FooFn1<T>;
}
type FooFn1<T> = (foo: Bar1<T[]>) => void;
type Bar1<T> = {
value: Foo1<T[]>;
}
type Foo2<out T> = { // Error
x: T;
f: FooFn2<T>;
}
type FooFn2<T> = (foo: Bar2<T[]>) => void;
type Bar2<T> = {
value: Foo2<T[]>;
}
type Foo3<in out T> = {
x: T;
f: FooFn3<T>;
}
type FooFn3<T> = (foo: Bar3<T[]>) => void;
type Bar3<T> = {
value: Foo3<T[]>;
}
// Wrong modifier usage
type T20<public T> = T; // Error
type T21<in out in T> = T; // Error
type T22<in out out T> = T; // Error
type T23<out in T> = T; // Error
declare function f1<in T>(x: T): void; // Error
declare function f2<out T>(): T; // Error
class C {
in a = 0; // Error
out b = 0; // Error
}
// Interface merging
interface Baz<out T> {}
interface Baz<in T> {}
declare let baz1: Baz<unknown>;
declare let baz2: Baz<string>;
baz1 = baz2; // Error
baz2 = baz1; // Error
// Repro from #44572
interface Parent<out A> {
child: Child<A> | null;
parent: Parent<A> | null;
}
interface Child<A, B = unknown> extends Parent<A> {
readonly a: A;
readonly b: B;
}
function fn<A>(inp: Child<A>) {
const a: Child<unknown> = inp;
}
const pu: Parent<unknown> = { child: { a: 0, b: 0, child: null, parent: null }, parent: null };
const notString: Parent<string> = pu; // Error
// Repro from comment in #44572
declare class StateNode<TContext, in out TEvent extends { type: string }> {
_storedEvent: TEvent;
_action: ActionObject<TEvent>;
_state: StateNode<TContext, any>;
}
interface ActionObject<TEvent extends { type: string }> {
exec: (meta: StateNode<any, TEvent>) => void;
}
declare function createMachine<TEvent extends { type: string }>(action: ActionObject<TEvent>): StateNode<any, any>;
declare function interpret<TContext>(machine: StateNode<TContext, any>): void;
const machine = createMachine({} as any);
interpret(machine);
declare const qq: ActionObject<{ type: "PLAY"; value: number }>;
createMachine<{ type: "PLAY"; value: number } | { type: "RESET" }>(qq); // Error
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/variance-annotations/with_jsx/input.tsx | TypeScript (TSX) | type Covariant<out T> = {
x: T;
}
declare let super_covariant: Covariant<unknown>;
declare let sub_covariant: Covariant<string>;
super_covariant = sub_covariant;
sub_covariant = super_covariant; // Error
type Contravariant<in T> = {
f: (x: T) => void;
}
declare let super_contravariant: Contravariant<unknown>;
declare let sub_contravariant: Contravariant<string>;
super_contravariant = sub_contravariant; // Error
sub_contravariant = super_contravariant;
type Invariant<in out T> = {
f: (x: T) => T;
}
declare let super_invariant: Invariant<unknown>;
declare let sub_invariant: Invariant<string>;
super_invariant = sub_invariant; // Error
sub_invariant = super_invariant; // Error
// Variance of various type constructors
type T10<out T> = T;
type T11<in T> = keyof T;
type T12<out T, out K extends keyof T> = T[K];
type T13<in out T> = T[keyof T];
// Variance annotation errors
type Covariant1<in T> = { // Error
x: T;
}
type Contravariant1<out T> = keyof T; // Error
type Contravariant2<out T> = { // Error
f: (x: T) => void;
}
type Invariant1<in T> = { // Error
f: (x: T) => T;
}
type Invariant2<out T> = { // Error
f: (x: T) => T;
}
// Variance in circular types
type Foo1<in T> = { // Error
x: T;
f: FooFn1<T>;
}
type FooFn1<T> = (foo: Bar1<T[]>) => void;
type Bar1<T> = {
value: Foo1<T[]>;
}
type Foo2<out T> = { // Error
x: T;
f: FooFn2<T>;
}
type FooFn2<T> = (foo: Bar2<T[]>) => void;
type Bar2<T> = {
value: Foo2<T[]>;
}
type Foo3<in out T> = {
x: T;
f: FooFn3<T>;
}
type FooFn3<T> = (foo: Bar3<T[]>) => void;
type Bar3<T> = {
value: Foo3<T[]>;
}
// Wrong modifier usage
type T20<public T> = T; // Error
type T21<in out in T> = T; // Error
type T22<in out out T> = T; // Error
type T23<out in T> = T; // Error
declare function f1<in T>(x: T): void; // Error
declare function f2<out T>(): T; // Error
class C {
in a = 0; // Error
out b = 0; // Error
}
// Interface merging
interface Baz<out T> {}
interface Baz<in T> {}
declare let baz1: Baz<unknown>;
declare let baz2: Baz<string>;
baz1 = baz2; // Error
baz2 = baz1; // Error
// Repro from #44572
interface Parent<out A> {
child: Child<A> | null;
parent: Parent<A> | null;
}
interface Child<A, B = unknown> extends Parent<A> {
readonly a: A;
readonly b: B;
}
function fn<A>(inp: Child<A>) {
const a: Child<unknown> = inp;
}
const pu: Parent<unknown> = { child: { a: 0, b: 0, child: null, parent: null }, parent: null };
const notString: Parent<string> = pu; // Error
// Repro from comment in #44572
declare class StateNode<TContext, in out TEvent extends { type: string }> {
_storedEvent: TEvent;
_action: ActionObject<TEvent>;
_state: StateNode<TContext, any>;
}
interface ActionObject<TEvent extends { type: string }> {
exec: (meta: StateNode<any, TEvent>) => void;
}
declare function createMachine<TEvent extends { type: string }>(action: ActionObject<TEvent>): StateNode<any, any>;
declare function interpret<TContext>(machine: StateNode<TContext, any>): void;
const machine = createMachine({} as any);
interpret(machine);
declare const qq: ActionObject<{ type: "PLAY"; value: number }>;
createMachine<{ type: "PLAY"; value: number } | { type: "RESET" }>(qq); // Error
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_parser/tests/typescript/vercel/web-875/input.ts | TypeScript |
export async function postProcessHTML(
) {
const postProcessors: Array<PostProcessorFunction> = [
process.env.NEXT_RUNTIME !== 'edge' && inAmpMode
? async (html: string) => {
const optimizeAmp = require('./optimize-amp')
.default as typeof import('./optimize-amp').default
html = await optimizeAmp!(html, renderOpts.ampOptimizerConfig)
if (!renderOpts.ampSkipValidation && renderOpts.ampValidator) {
await renderOpts.ampValidator(html, pathname)
}
return html
}
: null,
process.env.NEXT_RUNTIME !== 'edge' && renderOpts.optimizeFonts
? async (html: string) => {
const getFontDefinition = (url: string): string => {
}
}
: null,
process.env.NEXT_RUNTIME !== 'edge' && renderOpts.optimizeCss
? async (html: string) => {
}
: null,
inAmpMode || hybridAmp
? (html: string) => {
return html.replace(/&amp=1/g, '&=1')
}
: null,
].filter(nonNullable)
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/benches/polyfills.rs | Rust | use codspeed_criterion_compat::{black_box, criterion_group, criterion_main, Bencher, Criterion};
use swc_common::{comments::SingleThreadedComments, FileName, Mark};
use swc_ecma_ast::Program;
use swc_ecma_parser::{Parser, StringInput, Syntax};
use swc_ecma_preset_env::{preset_env, Config};
use swc_ecma_transforms::helpers::{Helpers, HELPERS};
fn run(b: &mut Bencher, src: &str, config: Config) {
let _ = ::testing::run_test(false, |cm, handler| {
HELPERS.set(&Helpers::new(true), || {
let fm = cm.new_source_file(FileName::Anon.into(), src.into());
let mut parser = Parser::new(Syntax::default(), StringInput::from(&*fm), None);
let module = parser
.parse_module()
.map_err(|e| e.into_diagnostic(handler).emit())
.unwrap();
for e in parser.take_errors() {
e.into_diagnostic(handler).emit()
}
let mut folder = preset_env(
Mark::fresh(Mark::root()),
Some(SingleThreadedComments::default()),
config,
Default::default(),
&mut Default::default(),
);
b.iter(|| black_box(Program::Module(module.clone()).apply(&mut folder)));
Ok(())
})
});
}
fn bench_cases(c: &mut Criterion) {
c.bench_function("es/preset-env/usage/builtin_type", |b| {
const SOURCE: &str = r#"
// From a length
var float32 = new Float32Array(2);
float32[0] = 42;
console.log(float32[0]); // 42
console.log(float32.length); // 2
console.log(float32.BYTES_PER_ELEMENT); // 4
// From an array
var arr = new Float32Array([21,31]);
console.log(arr[1]); // 31
// From another TypedArray
var x = new Float32Array([21, 31]);
var y = new Float32Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
var buffer = new ArrayBuffer(16);
var z = new Float32Array(buffer, 0, 4);
// From an iterable
var iterable = function*(){ yield* [1,2,3]; }();
var float32 = new Float32Array(iterable);
// Float32Array[1, 2, 3]
"#;
run(b, SOURCE, Default::default())
});
c.bench_function("es/preset-env/usage/property", |b| {
const SOURCE: &str = r#"
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
"#;
run(b, SOURCE, Default::default())
});
}
criterion_group!(benches, bench_cases);
criterion_main!(benches);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/scripts/copy-data.js | JavaScript | const fs = require("fs");
const path = require("path");
const nodeModulesDirectory = path.join(
__dirname,
"..",
"..",
"..",
"node_modules"
);
/**
*
* @param {string} s
*/
function copy(s) {
console.log(`es/preset-env: Copying ${s}`);
const targetPath = path.join(__dirname, "..", "data", s);
const targetDir = path.dirname(targetPath);
fs.mkdirSync(targetDir, { recursive: true });
fs.copyFileSync(path.join(nodeModulesDirectory, s), targetPath);
}
copy("@babel/compat-data/data/plugins.json");
copy("@babel/compat-data/data/plugin-bugfixes.json");
copy("core-js-compat/data.json");
copy("core-js-compat/entries.json");
copy("core-js-compat/modules-by-versions.json");
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/corejs2/builtin.rs | Rust | use once_cell::sync::Lazy;
use rustc_hash::FxHashMap;
use crate::{BrowserData, Versions};
pub(crate) static BUILTINS: Lazy<FxHashMap<String, Versions>> = Lazy::new(|| {
let map: FxHashMap<_, BrowserData<Option<String>>> =
serde_json::from_str(include_str!("builtin.json")).expect("failed to parse json");
map.into_iter()
.map(|(feature, version)| {
(
feature,
version.map_value(|version| version.map(|v| v.parse().unwrap())),
)
})
.collect()
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/corejs2/data.rs | Rust | use crate::util::DataMap;
static ARRAY_NATURE_ITERATORS: &[&str] = &[
"es6.object.to-string",
"es6.array.iterator",
"web.dom.iterable",
];
static COMMON_ITERATORS: &[&str] = &[
"es6.string.iterator",
"es6.object.to-string",
"es6.array.iterator",
"web.dom.iterable",
];
static PROMISE_DEPENDENCIES: &[&str] = &["es6.object.to-string", "es6.promise"];
pub static BUILTIN_TYPES: DataMap<&[&str]> = data_map!(Map {
DataView: "es6.typed.data-view",
Float32Array: "es6.typed.float32-array",
Float64Array: "es6.typed.float64-array",
Int8Array: "es6.typed.int8-array",
Int16Array: "es6.typed.int16-array",
Int32Array: "es6.typed.int32-array",
Map: [
"es6.map",
"es6.string.iterator",
"es6.object.to-string",
"es6.array.iterator",
"web.dom.iterable",
],
Number: "es6.number.constructor",
Promise: PROMISE_DEPENDENCIES,
RegExp: ["es6.regexp.constructor"],
Set: [
"es6.set",
"es6.string.iterator",
"es6.object.to-string",
"es6.array.iterator",
"web.dom.iterable",
],
Symbol: ["es6.symbol", "es7.symbol.async-iterator"],
Uint8Array: "es6.typed.uint8-array",
Uint8ClampedArray: "es6.typed.uint8-clamped-array",
Uint16Array: "es6.typed.uint16-array",
Uint32Array: "es6.typed.uint32-array",
WeakMap: [
"es6.weak-map",
"es6.string.iterator",
"es6.object.to-string",
"es6.array.iterator",
"web.dom.iterable",
],
WeakSet: [
"es6.weak-set",
"es6.string.iterator",
"es6.object.to-string",
"es6.array.iterator",
"web.dom.iterable",
],
});
pub static INSTANCE_PROPERTIES: DataMap<&[&str]> = data_map!(Map {
__defineGetter__: ["es7.object.define-getter"],
__defineSetter__: ["es7.object.define-setter"],
__lookupGetter__: ["es7.object.lookup-getter"],
__lookupSetter__: ["es7.object.lookup-setter"],
anchor: ["es6.string.anchor"],
big: ["es6.string.big"],
bind: ["es6.function.bind"],
blink: ["es6.string.blink"],
bold: ["es6.string.bold"],
codePointAt: ["es6.string.code-point-at"],
copyWithin: ["es6.array.copy-within"],
endsWith: ["es6.string.ends-with"],
entries: ARRAY_NATURE_ITERATORS,
every: ["es6.array.is-array"],
fill: ["es6.array.fill"],
filter: ["es6.array.filter"],
finally: ["es7.promise.finally", "es6.object.to-string", "es6.promise"],
find: ["es6.array.find"],
findIndex: ["es6.array.find-index"],
fixed: ["es6.string.fixed"],
flags: ["es6.regexp.flags"],
flatMap: ["es7.array.flat-map"],
fontcolor: ["es6.string.fontcolor"],
fontsize: ["es6.string.fontsize"],
forEach: ["es6.array.for-each"],
includes: ["es6.string.includes", "es7.array.includes"],
indexOf: ["es6.array.index-of"],
italics: ["es6.string.italics"],
keys: ARRAY_NATURE_ITERATORS,
lastIndexOf: ["es6.array.last-index-of"],
link: ["es6.string.link"],
map: ["es6.array.map"],
match: ["es6.regexp.match"],
name: ["es6.function.name"],
padStart: ["es7.string.pad-start"],
padEnd: ["es7.string.pad-end"],
reduce: ["es6.array.reduce"],
reduceRight: ["es6.array.reduce-right"],
repeat: ["es6.string.repeat"],
replace: ["es6.regexp.replace"],
search: ["es6.regexp.search"],
slice: ["es6.array.slice"],
small: ["es6.string.small"],
some: ["es6.array.some"],
sort: ["es6.array.sort"],
split: ["es6.regexp.split"],
startsWith: ["es6.string.starts-with"],
strike: ["es6.string.strike"],
sub: ["es6.string.sub"],
sup: ["es6.string.sup"],
toISOString: ["es6.date.to-iso-string"],
toJSON: ["es6.date.to-json"],
toString: [
"es6.object.to-string",
"es6.date.to-string",
"es6.regexp.to-string",
],
trim: ["es6.string.trim"],
trimEnd: ["es7.string.trim-right"],
trimLeft: ["es7.string.trim-left"],
trimRight: ["es7.string.trim-right"],
trimStart: ["es7.string.trim-left"],
values: ARRAY_NATURE_ITERATORS,
});
pub static STATIC_PROPERTIES: DataMap<DataMap<&[&str]>> = data_map!(Map {
Array: Map {
from: ["es6.array.from", "es6.string.iterator"],
isArray: "es6.array.is-array",
of: "es6.array.of",
},
Date: Map {
now: "es6.date.now",
},
Object: Map {
assign: "es6.object.assign",
create: "es6.object.create",
defineProperty: "es6.object.define-property",
defineProperties: "es6.object.define-properties",
entries: "es7.object.entries",
freeze: "es6.object.freeze",
getOwnPropertyDescriptors: "es7.object.get-own-property-descriptors",
getOwnPropertySymbols: "es6.symbol",
is: "es6.object.is",
isExtensible: "es6.object.is-extensible",
isFrozen: "es6.object.is-frozen",
isSealed: "es6.object.is-sealed",
keys: "es6.object.keys",
preventExtensions: "es6.object.prevent-extensions",
seal: "es6.object.seal",
setPrototypeOf: "es6.object.set-prototype-of",
values: "es7.object.values",
},
Math: Map {
acosh: "es6.math.acosh",
asinh: "es6.math.asinh",
atanh: "es6.math.atanh",
cbrt: "es6.math.cbrt",
clz32: "es6.math.clz32",
cosh: "es6.math.cosh",
expm1: "es6.math.expm1",
fround: "es6.math.fround",
hypot: "es6.math.hypot",
imul: "es6.math.imul",
log1p: "es6.math.log1p",
log10: "es6.math.log10",
log2: "es6.math.log2",
sign: "es6.math.sign",
sinh: "es6.math.sinh",
tanh: "es6.math.tanh",
trunc: "es6.math.trunc",
},
String: Map {
fromCodePoint: "es6.string.from-code-point",
raw: "es6.string.raw",
},
Number: Map {
EPSILON: "es6.number.epsilon",
MIN_SAFE_INTEGER: "es6.number.min-safe-integer",
MAX_SAFE_INTEGER: "es6.number.max-safe-integer",
isFinite: "es6.number.is-finite",
isInteger: "es6.number.is-integer",
isSafeInteger: "es6.number.is-safe-integer",
isNaN: "es6.number.is-nan",
parseFloat: "es6.number.parse-float",
parseInt: "es6.number.parse-int",
},
Promise: Map {
all: COMMON_ITERATORS,
race: COMMON_ITERATORS,
},
Reflect: Map {
apply: "es6.reflect.apply",
construct: "es6.reflect.construct",
defineProperty: "es6.reflect.define-property",
deleteProperty: "es6.reflect.delete-property",
get: "es6.reflect.get",
getOwnPropertyDescriptor: "es6.reflect.get-own-property-descriptor",
getPrototypeOf: "es6.reflect.get-prototype-of",
has: "es6.reflect.has",
isExtensible: "es6.reflect.is-extensible",
ownKeys: "es6.reflect.own-keys",
preventExtensions: "es6.reflect.prevent-extensions",
set: "es6.reflect.set",
setPrototypeOf: "es6.reflect.set-prototype-of",
},
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/corejs2/entry.rs | Rust | use std::sync::Arc;
use indexmap::IndexSet;
use preset_env_base::{version::should_enable, Versions};
use rustc_hash::FxBuildHasher;
use swc_atoms::atom;
use swc_common::DUMMY_SP;
use swc_ecma_ast::*;
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use super::builtin::BUILTINS;
#[derive(Debug)]
pub struct Entry {
is_any_target: bool,
target: Arc<Versions>,
pub imports: IndexSet<&'static str, FxBuildHasher>,
}
impl Entry {
pub fn new(target: Arc<Versions>, regenerator: bool) -> Self {
let is_any_target = target.is_any_target();
let is_web_target = target.into_iter().any(|(k, v)| {
if k == "node" {
return false;
}
v.is_some()
});
let mut v = Entry {
is_any_target: target.is_any_target(),
target,
imports: Default::default(),
};
if is_any_target || is_web_target {
v.imports.insert("web.timers");
v.imports.insert("web.immediate");
v.imports.insert("web.dom.iterable");
}
if regenerator {
v.imports.insert("regenerator-runtime/runtime.js");
}
v
}
/// Add imports.
/// Returns true if it's replaced.
fn add_all(&mut self, src: &str) -> bool {
if src != "@babel/polyfill" && src != "@swc/polyfill" && src != "core-js" {
return false;
}
for (feature, version) in BUILTINS.iter() {
self.add_inner(feature, version);
}
true
}
fn add_inner(&mut self, feature: &'static str, version: &Versions) {
if self.is_any_target || should_enable(&self.target, version, true) {
self.imports.insert(feature);
}
}
}
impl VisitMut for Entry {
noop_visit_mut_type!(fail);
fn visit_mut_import_decl(&mut self, i: &mut ImportDecl) {
let remove = i.specifiers.is_empty() && self.add_all(&i.src.value);
if remove {
i.src.value = atom!("");
i.src.span = DUMMY_SP;
}
}
fn visit_mut_module_items(&mut self, items: &mut Vec<ModuleItem>) {
items.retain_mut(|item| {
item.visit_mut_children_with(self);
if let ModuleItem::Stmt(Stmt::Expr(ExprStmt { expr, .. })) = &item {
if let Expr::Call(CallExpr {
callee: Callee::Expr(callee),
ref args,
..
}) = &**expr
{
if callee.is_ident_ref_to("require")
&& args.len() == 1
&& if let ExprOrSpread { spread: None, expr } = &args[0] {
if let Expr::Lit(Lit::Str(s)) = &**expr {
s.value == *"core-js"
|| s.value == *"@swc/polyfill"
|| s.value == *"@babel/polyfill"
} else {
false
}
} else {
false
}
&& self.add_all("@swc/polyfill")
{
return false;
}
}
}
true
})
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/corejs2/mod.rs | Rust | use std::sync::Arc;
use indexmap::IndexSet;
use preset_env_base::{version::should_enable, Versions};
use rustc_hash::FxBuildHasher;
use swc_atoms::Atom;
use swc_ecma_ast::*;
use swc_ecma_visit::{noop_visit_type, Visit, VisitWith};
pub(crate) use self::entry::Entry;
use self::{
builtin::BUILTINS,
data::{BUILTIN_TYPES, INSTANCE_PROPERTIES, STATIC_PROPERTIES},
};
use crate::util::DataMapExt;
mod builtin;
mod data;
mod entry;
pub(crate) struct UsageVisitor {
is_any_target: bool,
target: Arc<Versions>,
pub required: IndexSet<&'static str, FxBuildHasher>,
}
impl UsageVisitor {
pub fn new(target: Arc<Versions>) -> Self {
// let mut v = Self { required: Vec::new() };
//
//
// let is_web_target = target
// .iter()
// .any(|(name, version)| name != "node" &&
// version.is_some());
//
// println!(
// "is_any_target={:?}\nis_web_target={:?}",
// is_any_target, is_web_target
// );
//
// // Web default
// if is_any_target || is_web_target {
// v.add(&["web.timers", "web.immediate",
// "web.dom.iterable"]); }
// v
//if target.is_any_target() || target.node.is_none() {
// v.add(&["web.timers", "web.immediate", "web.dom.iterable"]);
//}
Self {
is_any_target: target.is_any_target(),
target,
required: Default::default(),
}
}
/// Add imports
fn add(&mut self, features: &'static [&'static str]) {
let UsageVisitor {
is_any_target,
target,
..
} = self;
self.required.extend(features.iter().filter(|f| {
if !*is_any_target {
if let Some(v) = BUILTINS.get(&***f) {
// Skip
if !should_enable(target, v, true) {
return false;
}
}
}
true
}));
}
fn add_property_deps_inner(&mut self, obj: Option<&Atom>, prop: &Atom) {
if let Some(obj) = obj {
if let Some(map) = STATIC_PROPERTIES.get_data(obj) {
if let Some(features) = map.get_data(prop) {
self.add(features);
}
}
}
if let Some(features) = INSTANCE_PROPERTIES.get_data(prop) {
self.add(features);
}
}
fn visit_object_pat_props(&mut self, obj: &Expr, props: &[ObjectPatProp]) {
let obj = match obj {
Expr::Ident(i) => Some(&i.sym),
_ => None,
};
for p in props {
match p {
ObjectPatProp::KeyValue(KeyValuePatProp {
key: PropName::Ident(i),
..
}) => self.add_property_deps_inner(obj, &i.sym),
ObjectPatProp::Assign(AssignPatProp { key, .. }) => {
self.add_property_deps_inner(obj, &key.sym)
}
_ => {}
}
}
}
}
// TODO:
// Program(path: NodePath) {
// path.get("body").forEach(bodyPath => {
// if (isPolyfillSource(getRequireSource(bodyPath))) {
// console.warn(NO_DIRECT_POLYFILL_IMPORT);
// bodyPath.remove();
// }
// });
// },
/// Detects usage of types
impl Visit for UsageVisitor {
noop_visit_type!(fail);
fn visit_ident(&mut self, node: &Ident) {
node.visit_children_with(self);
for (name, builtin) in BUILTIN_TYPES {
if node.sym == **name {
self.add(builtin)
}
}
}
fn visit_var_declarator(&mut self, d: &VarDeclarator) {
d.visit_children_with(self);
if let Some(ref init) = d.init {
if let Pat::Object(ref o) = d.name {
self.visit_object_pat_props(init, &o.props)
}
} else if let Pat::Object(ref o) = d.name {
self.visit_object_pat_props(&Ident::default().into(), &o.props)
}
}
fn visit_assign_expr(&mut self, e: &AssignExpr) {
e.visit_children_with(self);
if let AssignTarget::Pat(AssignTargetPat::Object(o)) = &e.left {
self.visit_object_pat_props(&e.right, &o.props)
}
}
/// Detects usage of instance properties and static properties.
///
/// - `Array.from`
fn visit_member_expr(&mut self, node: &MemberExpr) {
node.obj.visit_with(self);
if let MemberProp::Computed(c) = &node.prop {
c.visit_with(self);
}
//enter(path: NodePath) {
// const { node } = path;
// const { object, property } = node;
//
// // ignore namespace
// if (isNamespaced(path.get("object"))) return;
//
// let evaluatedPropType = object.name;
// let propertyName = "";
// let instanceType = "";
//
// if (node.computed) {
// if (t.isStringLiteral(property)) {
// propertyName = property.value;
// } else {
// const result = path.get("property").evaluate();
// if (result.confident && result.value) {
// propertyName = result.value;
// }
// }
// } else {
// propertyName = property.name;
// }
//
// if (path.scope.getBindingIdentifier(object.name)) {
// const result = path.get("object").evaluate();
// if (result.value) {
// instanceType = getType(result.value);
// } else if (result.deopt && result.deopt.isIdentifier()) {
// evaluatedPropType = result.deopt.node.name;
// }
// }
//
// if (has(STATIC_PROPERTIES, evaluatedPropType)) {
// const BuiltInProperties = STATIC_PROPERTIES[evaluatedPropType];
// if (has(BuiltInProperties, propertyName)) {
// const StaticPropertyDependencies =
// BuiltInProperties[propertyName];
// this.addUnsupported(StaticPropertyDependencies); }
// }
//
// if (has(INSTANCE_PROPERTIES, propertyName)) {
// let InstancePropertyDependencies = INSTANCE_PROPERTIES[propertyName];
// if (instanceType) {
// InstancePropertyDependencies =
// InstancePropertyDependencies.filter( module =>
// module.includes(instanceType), );
// }
// this.addUnsupported(InstancePropertyDependencies);
// }
//},
//
//// Symbol.match
//exit(path: NodePath) {
// const { name } = path.node.object;
//
// if (!has(BUILT_INS, name)) return;
// if (path.scope.getBindingIdentifier(name)) return;
//
// const BuiltInDependencies = BUILT_INS[name];
// this.addUnsupported(BuiltInDependencies);
//},
match &node.prop {
MemberProp::Ident(i) => {
//
for (name, imports) in INSTANCE_PROPERTIES {
if i.sym == **name {
self.add(imports)
}
}
}
MemberProp::Computed(ComputedPropName { expr, .. }) => {
if let Expr::Lit(Lit::Str(Str { value, .. })) = &**expr {
for (name, imports) in INSTANCE_PROPERTIES {
if *value == **name {
self.add(imports);
}
}
}
}
_ => {}
}
if let Expr::Ident(obj) = &*node.obj {
for (ty, props) in STATIC_PROPERTIES {
if obj.sym == **ty {
match &node.prop {
MemberProp::Computed(ComputedPropName { expr, .. }) => {
if let Expr::Lit(Lit::Str(Str { value, .. })) = &**expr {
for (name, imports) in INSTANCE_PROPERTIES {
if *value == **name {
self.add(imports);
}
}
}
}
MemberProp::Ident(ref p) => {
for (prop, imports) in *props {
if p.sym == **prop {
self.add(imports);
}
}
}
_ => {}
}
}
}
}
}
// maybe not needed?
fn visit_super_prop_expr(&mut self, node: &SuperPropExpr) {
if let SuperProp::Computed(c) = &node.prop {
c.visit_with(self);
}
}
///
/// - `arr[Symbol.iterator]()`
fn visit_call_expr(&mut self, e: &CallExpr) {
e.visit_children_with(self);
if match &e.callee {
Callee::Expr(callee) => matches!(&**callee, Expr::Member(MemberExpr {
prop: MemberProp::Computed(ComputedPropName { expr, .. }),
..
}) if is_symbol_iterator(expr)),
_ => false,
} {
self.add(&["web.dom.iterable"])
}
}
///
/// - `Symbol.iterator in arr`
fn visit_bin_expr(&mut self, e: &BinExpr) {
e.visit_children_with(self);
match e.op {
op!("in") if is_symbol_iterator(&e.left) => self.add(&["web.dom.iterable"]),
_ => {}
}
}
///
/// - `yield*`
fn visit_yield_expr(&mut self, e: &YieldExpr) {
e.visit_children_with(self);
if e.delegate {
self.add(&["web.dom.iterable"])
}
}
}
fn is_symbol_iterator(e: &Expr) -> bool {
match e {
Expr::Member(MemberExpr { obj, prop, .. }) if prop.is_ident_with("iterator") => {
obj.is_ident_ref_to("Symbol")
}
_ => false,
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/corejs3/builtin.rs | Rust | use once_cell::sync::Lazy;
use crate::util::{descriptor, CoreJSPolyfillDescriptor, ObjectMap, ObjectMap2};
fn dynamic_concat(a: &[&'static str], b: &[&'static str]) -> &'static [&'static str] {
let mut res = Vec::with_capacity(a.len() + b.len());
res.extend_from_slice(a);
res.extend_from_slice(b);
res.leak()
}
const fn concat2<const N: usize>(a: &[&'static str], b: &[&'static str]) -> [&'static str; N] {
assert!(N == a.len() + b.len());
let mut res = [""; N];
let mut idx = 0;
while idx < a.len() {
res[idx] = a[idx];
idx += 1;
}
while idx < a.len() + b.len() {
res[idx] = b[idx - a.len()];
idx += 1;
}
res
}
fn typed(names: &'static [&'static str]) -> CoreJSPolyfillDescriptor {
let mut global = Vec::with_capacity(names.len() + TYPED_ARRAY_DEPENDENCIES.len());
global.extend_from_slice(names);
global.extend_from_slice(TYPED_ARRAY_DEPENDENCIES);
descriptor(None, global.leak(), Some(names[0]), &[])
}
static ARRAY_NATURE_ITERATORS: &[&str] = &["es.array.iterator", "web.dom-collections.iterator"];
pub static COMMON_ITERATORS: &[&str] =
&concat2::<3>(ARRAY_NATURE_ITERATORS, &["es.string.iterator"]);
static ARRAY_NATURE_ITERATORS_WITH_TAG: &[&str] =
&concat2::<3>(ARRAY_NATURE_ITERATORS, &["es.object.to-string"]);
static COMMON_ITERATORS_WITH_TAG: &[&str] =
&concat2::<4>(COMMON_ITERATORS, &["es.object.to-string"]);
static ERROR_DEPENDENCIES: &[&str] = &["es.error.cause", "es.error.to-string"];
static SUPPRESSED_ERROR_DEPENDENCIES: &[&str] =
&concat2::<3>(&["esnext.suppressed-error.constructor"], ERROR_DEPENDENCIES);
static ARRAY_BUFFER_DEPENDENCIES: &[&str] = &[
"es.array-buffer.constructor",
"es.array-buffer.slice",
"es.data-view",
"es.array-buffer.detached",
"es.array-buffer.transfer",
"es.array-buffer.transfer-to-fixed-length",
"es.object.to-string",
];
static TYPED_ARRAY_DEPENDENCIES: &[&str] = &concat2::<42>(
&[
"es.typed-array.at",
"es.typed-array.copy-within",
"es.typed-array.every",
"es.typed-array.fill",
"es.typed-array.filter",
"es.typed-array.find",
"es.typed-array.find-index",
"es.typed-array.find-last",
"es.typed-array.find-last-index",
"es.typed-array.for-each",
"es.typed-array.includes",
"es.typed-array.index-of",
"es.typed-array.iterator",
"es.typed-array.join",
"es.typed-array.last-index-of",
"es.typed-array.map",
"es.typed-array.reduce",
"es.typed-array.reduce-right",
"es.typed-array.reverse",
"es.typed-array.set",
"es.typed-array.slice",
"es.typed-array.some",
"es.typed-array.sort",
"es.typed-array.subarray",
"es.typed-array.to-locale-string",
"es.typed-array.to-reversed",
"es.typed-array.to-sorted",
"es.typed-array.to-string",
"es.typed-array.with",
"es.object.to-string",
"es.array.iterator",
"esnext.typed-array.filter-reject",
"esnext.typed-array.group-by",
"esnext.typed-array.to-spliced",
"esnext.typed-array.unique-by",
],
ARRAY_BUFFER_DEPENDENCIES,
);
pub static PROMISE_DEPENDENCIES: &[&str] = &["es.promise", "es.object.to-string"];
static PROMISE_DEPENDENCIES_WITH_ITERATORS: &[&str] =
&concat2::<5>(PROMISE_DEPENDENCIES, COMMON_ITERATORS);
static SYMBOL_DEPENDENCIES: &[&str] =
&["es.symbol", "es.symbol.description", "es.object.to-string"];
static MAP_DEPENDENCIES: &[&str] = &concat2::<19>(
&[
"es.map",
"esnext.map.delete-all",
"esnext.map.emplace",
"esnext.map.every",
"esnext.map.filter",
"esnext.map.find",
"esnext.map.find-key",
"esnext.map.includes",
"esnext.map.key-of",
"esnext.map.map-keys",
"esnext.map.map-values",
"esnext.map.merge",
"esnext.map.reduce",
"esnext.map.some",
"esnext.map.update",
],
COMMON_ITERATORS_WITH_TAG,
);
static SET_DEPENDENCIES: &[&str] = &concat2::<28>(
&[
"es.set",
"es.set.difference.v2",
"es.set.intersection.v2",
"es.set.is-disjoint-from.v2",
"es.set.is-subset-of.v2",
"es.set.is-superset-of.v2",
"es.set.symmetric-difference.v2",
"es.set.union.v2",
"esnext.set.add-all",
"esnext.set.delete-all",
"esnext.set.difference",
"esnext.set.every",
"esnext.set.filter",
"esnext.set.find",
"esnext.set.intersection",
"esnext.set.is-disjoint-from",
"esnext.set.is-subset-of",
"esnext.set.is-superset-of",
"esnext.set.join",
"esnext.set.map",
"esnext.set.reduce",
"esnext.set.some",
"esnext.set.symmetric-difference",
"esnext.set.union",
],
COMMON_ITERATORS_WITH_TAG,
);
static WEAK_MAP_DEPENDENCIES: &[&str] = &concat2::<7>(
&[
"es.weak-map",
"esnext.weak-map.delete-all",
"esnext.weak-map.emplace",
],
COMMON_ITERATORS_WITH_TAG,
);
static WEAK_SET_DEPENDENCIES: &[&str] = &concat2::<7>(
&[
"es.weak-set",
"esnext.weak-set.add-all",
"esnext.weak-set.delete-all",
],
COMMON_ITERATORS_WITH_TAG,
);
static DOM_EXCEPTION_DEPENDENCIES: &[&str] = &[
"web.dom-exception.constructor",
"web.dom-exception.stack",
"web.dom-exception.to-string-tag",
"es.error.to-string",
];
static URL_SEARCH_PARAMS_DEPENDENCIES: &[&str] = &concat2::<8>(
&[
"web.url-search-params",
"web.url-search-params.delete",
"web.url-search-params.has",
"web.url-search-params.size",
],
COMMON_ITERATORS_WITH_TAG,
);
static ASYNC_ITERATOR_DEPENDENCIES: &[&str] =
&concat2::<3>(&["esnext.async-iterator.constructor"], PROMISE_DEPENDENCIES);
static ASYNC_ITERATOR_PROBLEM_METHODS: &[&str] = &[
"esnext.async-iterator.every",
"esnext.async-iterator.filter",
"esnext.async-iterator.find",
"esnext.async-iterator.flat-map",
"esnext.async-iterator.for-each",
"esnext.async-iterator.map",
"esnext.async-iterator.reduce",
"esnext.async-iterator.some",
];
static ITERATOR_DEPENDENCIES: &[&str] = &["esnext.iterator.constructor", "es.object.to-string"];
static DECORATOR_METADATA_DEPENDENCIES: &[&str] =
&["esnext.symbol.metadata", "esnext.function.metadata"];
fn typed_array_static_methods(
base: &'static [&'static str],
) -> ObjectMap<CoreJSPolyfillDescriptor> {
map!(Map {
from: define(
null,
["es.typed-array.from", base, TYPED_ARRAY_DEPENDENCIES]
),
fromAsync: define(
null,
[
"esnext.typed-array.from-async",
base,
PROMISE_DEPENDENCIES_WITH_ITERATORS,
TYPED_ARRAY_DEPENDENCIES,
]
),
of: define(null, ["es.typed-array.of", base, TYPED_ARRAY_DEPENDENCIES]),
})
}
fn uint8_typed_array_static_methods() -> ObjectMap<CoreJSPolyfillDescriptor> {
let mut map = typed_array_static_methods(&["es.typed-array.uint8-array"]);
map.extend(map!(Map {
fromBase64: define(
null,
["esnext.uint8-array.from-base64", TYPED_ARRAY_DEPENDENCIES,]
),
fromHex: define(
null,
["esnext.uint8-array.from-hex", TYPED_ARRAY_DEPENDENCIES,]
),
}));
map
}
static DATA_VIEW_DEPENDENCIES: &[&str] =
&concat2::<8>(&["es.data-view"], ARRAY_BUFFER_DEPENDENCIES);
pub(crate) static BUILT_INS: Lazy<ObjectMap<CoreJSPolyfillDescriptor>> = lazy_map!(Map{
AsyncDisposableStack: define("async-disposable-stack/index", [
"esnext.async-disposable-stack.constructor",
"es.object.to-string",
"esnext.async-iterator.async-dispose",
"esnext.iterator.dispose",
PROMISE_DEPENDENCIES,
SUPPRESSED_ERROR_DEPENDENCIES,
]),
AsyncIterator: define("async-iterator/index", ASYNC_ITERATOR_DEPENDENCIES),
AggregateError: define("aggregate-error", [
"es.aggregate-error",
ERROR_DEPENDENCIES,
COMMON_ITERATORS_WITH_TAG,
"es.aggregate-error.cause",
]),
ArrayBuffer: define(null, ARRAY_BUFFER_DEPENDENCIES),
DataView: define(null, DATA_VIEW_DEPENDENCIES),
Date: define(null, ["es.date.to-string"]),
DOMException: define("dom-exception/index", DOM_EXCEPTION_DEPENDENCIES),
DisposableStack: define("disposable-stack/index", [
"esnext.disposable-stack.constructor",
"es.object.to-string",
"esnext.iterator.dispose",
SUPPRESSED_ERROR_DEPENDENCIES,
]),
Error: define(null, ERROR_DEPENDENCIES),
EvalError: define(null, ERROR_DEPENDENCIES),
Float32Array: typed(&["es.typed-array.float32-array"]),
Float64Array: typed(&["es.typed-array.float64-array"]),
Int8Array: typed(&["es.typed-array.int8-array"]),
Int16Array: typed(&["es.typed-array.int16-array"]),
Int32Array: typed(&["es.typed-array.int32-array"]),
Iterator: define("iterator/index", ITERATOR_DEPENDENCIES),
Uint8Array: typed(&[
"es.typed-array.uint8-array",
"esnext.uint8-array.set-from-base64",
"esnext.uint8-array.set-from-hex",
"esnext.uint8-array.to-base64",
"esnext.uint8-array.to-hex",
]),
Uint8ClampedArray: typed(&["es.typed-array.uint8-clamped-array"]),
Uint16Array: typed(&["es.typed-array.uint16-array"]),
Uint32Array: typed(&["es.typed-array.uint32-array"]),
Map: define("map/index", MAP_DEPENDENCIES),
Number: define(null, ["es.number.constructor"]),
Observable: define("observable/index", [
"esnext.observable",
"esnext.symbol.observable",
"es.object.to-string",
COMMON_ITERATORS_WITH_TAG,
]),
Promise: define("promise/index", PROMISE_DEPENDENCIES),
RangeError: define(null, ERROR_DEPENDENCIES),
ReferenceError: define(null, ERROR_DEPENDENCIES),
Reflect: define(null, ["es.reflect.to-string-tag", "es.object.to-string"]),
RegExp: define(null, [
"es.regexp.constructor",
"es.regexp.dot-all",
"es.regexp.exec",
"es.regexp.sticky",
"es.regexp.to-string",
]),
Set: define("set/index", SET_DEPENDENCIES),
SuppressedError: define("suppressed-error", SUPPRESSED_ERROR_DEPENDENCIES),
Symbol: define("symbol/index", SYMBOL_DEPENDENCIES),
SyntaxError: define(null, ERROR_DEPENDENCIES),
TypeError: define(null, ERROR_DEPENDENCIES),
URIError: define(null, ERROR_DEPENDENCIES),
URL: define("url/index", [
"web.url",
"web.url.to-json",
URL_SEARCH_PARAMS_DEPENDENCIES,
]),
URLSearchParams: define(
"url-search-params/index",
URL_SEARCH_PARAMS_DEPENDENCIES
),
WeakMap: define("weak-map/index", WEAK_MAP_DEPENDENCIES),
WeakSet: define("weak-set/index", WEAK_SET_DEPENDENCIES),
atob: define("atob", ["web.atob", DOM_EXCEPTION_DEPENDENCIES]),
btoa: define("btoa", ["web.btoa", DOM_EXCEPTION_DEPENDENCIES]),
clearImmediate: define("clear-immediate", ["web.immediate"]),
compositeKey: define("composite-key", ["esnext.composite-key"]),
compositeSymbol: define("composite-symbol", ["esnext.composite-symbol"]),
escape: define("escape", ["es.escape"]),
fetch: define(null, PROMISE_DEPENDENCIES),
globalThis: define("global-this", ["es.global-this"]),
parseFloat: define("parse-float", ["es.parse-float"]),
parseInt: define("parse-int", ["es.parse-int"]),
queueMicrotask: define("queue-microtask", ["web.queue-microtask"]),
self: define("self", ["web.self"]),
setImmediate: define("set-immediate", ["web.immediate"]),
setInterval: define("set-interval", ["web.timers"]),
setTimeout: define("set-timeout", ["web.timers"]),
structuredClone: define("structured-clone", [
"web.structured-clone",
DOM_EXCEPTION_DEPENDENCIES,
"es.array.iterator",
"es.object.keys",
"es.object.to-string",
"es.map",
"es.set",
]),
unescape: define("unescape", ["es.unescape"]),
});
pub(crate) static STATIC_PROPERTIES: Lazy<ObjectMap2<CoreJSPolyfillDescriptor>> = lazy_map!(Map {
AsyncIterator: Map {
from: define("async-iterator/from", [
"esnext.async-iterator.from",
ASYNC_ITERATOR_DEPENDENCIES,
AsyncIteratorProblemMethods,
CommonIterators,
]),
},
Array: Map {
from: define("array/from", ["es.array.from", "es.string.iterator"]),
fromAsync: define("array/from-async", [
"esnext.array.from-async",
PROMISE_DEPENDENCIES_WITH_ITERATORS,
]),
isArray: define("array/is-array", ["es.array.is-array"]),
isTemplateObject: define("array/is-template-object", [
"esnext.array.is-template-object",
]),
of: define("array/of", ["es.array.of"]),
},
ArrayBuffer: Map {
isView: define(null, ["es.array-buffer.is-view"]),
},
BigInt: Map {
range: define("bigint/range", [
"esnext.bigint.range",
"es.object.to-string",
]),
},
Date: Map {
now: define("date/now", ["es.date.now"]),
},
Function: Map {
isCallable: define("function/is-callable", ["esnext.function.is-callable"]),
isConstructor: define("function/is-constructor", [
"esnext.function.is-constructor",
]),
},
Iterator: Map {
from: define("iterator/from", [
"esnext.iterator.from",
ITERATOR_DEPENDENCIES,
CommonIterators,
]),
range: define("iterator/range", [
"esnext.iterator.range",
"es.object.to-string",
]),
},
JSON: Map {
isRawJSON: define("json/is-raw-json", ["esnext.json.is-raw-json"]),
parse: define("json/parse", ["esnext.json.parse", "es.object.keys"]),
rawJSON: define("json/raw-json", [
"esnext.json.raw-json",
"es.object.create",
"es.object.freeze",
]),
stringify: define("json/stringify", ["es.json.stringify"], "es.symbol"),
},
Math: Map {
DEG_PER_RAD: define("math/deg-per-rad", ["esnext.math.deg-per-rad"]),
RAD_PER_DEG: define("math/rad-per-deg", ["esnext.math.rad-per-deg"]),
acosh: define("math/acosh", ["es.math.acosh"]),
asinh: define("math/asinh", ["es.math.asinh"]),
atanh: define("math/atanh", ["es.math.atanh"]),
cbrt: define("math/cbrt", ["es.math.cbrt"]),
clamp: define("math/clamp", ["esnext.math.clamp"]),
clz32: define("math/clz32", ["es.math.clz32"]),
cosh: define("math/cosh", ["es.math.cosh"]),
degrees: define("math/degrees", ["esnext.math.degrees"]),
expm1: define("math/expm1", ["es.math.expm1"]),
fround: define("math/fround", ["es.math.fround"]),
f16round: define("math/f16round", ["esnext.math.f16round"]),
fscale: define("math/fscale", ["esnext.math.fscale"]),
hypot: define("math/hypot", ["es.math.hypot"]),
iaddh: define("math/iaddh", ["esnext.math.iaddh"]),
imul: define("math/imul", ["es.math.imul"]),
imulh: define("math/imulh", ["esnext.math.imulh"]),
isubh: define("math/isubh", ["esnext.math.isubh"]),
log10: define("math/log10", ["es.math.log10"]),
log1p: define("math/log1p", ["es.math.log1p"]),
log2: define("math/log2", ["es.math.log2"]),
radians: define("math/radians", ["esnext.math.radians"]),
scale: define("math/scale", ["esnext.math.scale"]),
seededPRNG: define("math/seeded-prng", ["esnext.math.seeded-prng"]),
sign: define("math/sign", ["es.math.sign"]),
signbit: define("math/signbit", ["esnext.math.signbit"]),
sinh: define("math/sinh", ["es.math.sinh"]),
tanh: define("math/tanh", ["es.math.tanh"]),
trunc: define("math/trunc", ["es.math.trunc"]),
umulh: define("math/umulh", ["esnext.math.umulh"]),
},
Map: Map {
from: define(null, ["esnext.map.from", MAP_DEPENDENCIES]),
groupBy: define(null, ["esnext.map.group-by", MAP_DEPENDENCIES]),
keyBy: define(null, ["esnext.map.key-by", MAP_DEPENDENCIES]),
of: define(null, ["esnext.map.of", MAP_DEPENDENCIES]),
},
Number: Map {
EPSILON: define("number/epsilon", ["es.number.epsilon"]),
MAX_SAFE_INTEGER: define("number/max-safe-integer", [
"es.number.max-safe-integer",
]),
MIN_SAFE_INTEGER: define("number/min-safe-integer", [
"es.number.min-safe-integer",
]),
fromString: define("number/from-string", ["esnext.number.from-string"]),
isFinite: define("number/is-finite", ["es.number.is-finite"]),
isInteger: define("number/is-integer", ["es.number.is-integer"]),
isNaN: define("number/is-nan", ["es.number.is-nan"]),
isSafeInteger: define("number/is-safe-integer", [
"es.number.is-safe-integer",
]),
parseFloat: define("number/parse-float", ["es.number.parse-float"]),
parseInt: define("number/parse-int", ["es.number.parse-int"]),
range: define("number/range", [
"esnext.number.range",
"es.object.to-string",
]),
},
Object: Map {
assign: define("object/assign", ["es.object.assign"]),
create: define("object/create", ["es.object.create"]),
defineProperties: define("object/define-properties", [
"es.object.define-properties",
]),
defineProperty: define("object/define-property", [
"es.object.define-property",
]),
entries: define("object/entries", ["es.object.entries"]),
freeze: define("object/freeze", ["es.object.freeze"]),
fromEntries: define("object/from-entries", [
"es.object.from-entries",
"es.array.iterator",
]),
getOwnPropertyDescriptor: define("object/get-own-property-descriptor", [
"es.object.get-own-property-descriptor",
]),
getOwnPropertyDescriptors: define("object/get-own-property-descriptors", [
"es.object.get-own-property-descriptors",
]),
getOwnPropertyNames: define("object/get-own-property-names", [
"es.object.get-own-property-names",
]),
getOwnPropertySymbols: define("object/get-own-property-symbols", [
"es.symbol",
]),
getPrototypeOf: define("object/get-prototype-of", [
"es.object.get-prototype-of",
]),
groupBy: define("object/group-by", [
"esnext.object.group-by",
"es.object.create",
]),
hasOwn: define("object/has-own", ["es.object.has-own"]),
is: define("object/is", ["es.object.is"]),
isExtensible: define("object/is-extensible", ["es.object.is-extensible"]),
isFrozen: define("object/is-frozen", ["es.object.is-frozen"]),
isSealed: define("object/is-sealed", ["es.object.is-sealed"]),
keys: define("object/keys", ["es.object.keys"]),
preventExtensions: define("object/prevent-extensions", [
"es.object.prevent-extensions",
]),
seal: define("object/seal", ["es.object.seal"]),
setPrototypeOf: define("object/set-prototype-of", [
"es.object.set-prototype-of",
]),
values: define("object/values", ["es.object.values"]),
},
Promise: Map {
all: define(null, PROMISE_DEPENDENCIES_WITH_ITERATORS),
allSettled: define(null, [
"es.promise.all-settled",
PROMISE_DEPENDENCIES_WITH_ITERATORS,
]),
any: define(null, [
"es.promise.any",
"es.aggregate-error",
PROMISE_DEPENDENCIES_WITH_ITERATORS,
]),
race: define(null, PROMISE_DEPENDENCIES_WITH_ITERATORS),
try: define(null, ["esnext.promise.try", PROMISE_DEPENDENCIES]),
withResolvers: define(null, [
"esnext.promise.with-resolvers",
PROMISE_DEPENDENCIES,
]),
},
Reflect: Map {
apply: define("reflect/apply", ["es.reflect.apply"]),
construct: define("reflect/construct", ["es.reflect.construct"]),
defineMetadata: define("reflect/define-metadata", [
"esnext.reflect.define-metadata",
]),
defineProperty: define("reflect/define-property", [
"es.reflect.define-property",
]),
deleteMetadata: define("reflect/delete-metadata", [
"esnext.reflect.delete-metadata",
]),
deleteProperty: define("reflect/delete-property", [
"es.reflect.delete-property",
]),
get: define("reflect/get", ["es.reflect.get"]),
getMetadata: define("reflect/get-metadata", [
"esnext.reflect.get-metadata",
]),
getMetadataKeys: define("reflect/get-metadata-keys", [
"esnext.reflect.get-metadata-keys",
]),
getOwnMetadata: define("reflect/get-own-metadata", [
"esnext.reflect.get-own-metadata",
]),
getOwnMetadataKeys: define("reflect/get-own-metadata-keys", [
"esnext.reflect.get-own-metadata-keys",
]),
getOwnPropertyDescriptor: define("reflect/get-own-property-descriptor", [
"es.reflect.get-own-property-descriptor",
]),
getPrototypeOf: define("reflect/get-prototype-of", [
"es.reflect.get-prototype-of",
]),
has: define("reflect/has", ["es.reflect.has"]),
hasMetadata: define("reflect/has-metadata", [
"esnext.reflect.has-metadata",
]),
hasOwnMetadata: define("reflect/has-own-metadata", [
"esnext.reflect.has-own-metadata",
]),
isExtensible: define("reflect/is-extensible", ["es.reflect.is-extensible"]),
metadata: define("reflect/metadata", ["esnext.reflect.metadata"]),
ownKeys: define("reflect/own-keys", ["es.reflect.own-keys"]),
preventExtensions: define("reflect/prevent-extensions", [
"es.reflect.prevent-extensions",
]),
set: define("reflect/set", ["es.reflect.set"]),
setPrototypeOf: define("reflect/set-prototype-of", [
"es.reflect.set-prototype-of",
]),
},
Set: Map {
from: define(null, ["esnext.set.from", SET_DEPENDENCIES]),
of: define(null, ["esnext.set.of", SET_DEPENDENCIES]),
},
String: Map {
cooked: define("string/cooked", ["esnext.string.cooked"]),
dedent: define("string/dedent", [
"esnext.string.dedent",
"es.string.from-code-point",
"es.weak-map",
]),
fromCodePoint: define("string/from-code-point", [
"es.string.from-code-point",
]),
raw: define("string/raw", ["es.string.raw"]),
},
Symbol: Map {
asyncDispose: define("symbol/async-dispose", [
"esnext.symbol.async-dispose",
"esnext.async-iterator.async-dispose",
]),
asyncIterator: define("symbol/async-iterator", [
"es.symbol.async-iterator",
]),
dispose: define("symbol/dispose", [
"esnext.symbol.dispose",
"esnext.iterator.dispose",
]),
for: define("symbol/for", [], "es.symbol"),
hasInstance: define("symbol/has-instance", [
"es.symbol.has-instance",
"es.function.has-instance",
]),
isConcatSpreadable: define("symbol/is-concat-spreadable", [
"es.symbol.is-concat-spreadable",
"es.array.concat",
]),
isRegistered: define("symbol/is-registered", [
"esnext.symbol.is-registered",
"es.symbol",
]),
isRegisteredSymbol: define("symbol/is-registered-symbol", [
"esnext.symbol.is-registered-symbol",
"es.symbol",
]),
isWellKnown: define("symbol/is-well-known", [
"esnext.symbol.is-well-known",
"es.symbol",
]),
isWellKnownSymbol: define("symbol/is-well-known-symbol", [
"esnext.symbol.is-well-known-symbol",
"es.symbol",
]),
iterator: define("symbol/iterator", [
"es.symbol.iterator",
COMMON_ITERATORS_WITH_TAG,
]),
keyFor: define("symbol/key-for", [], "es.symbol"),
match: define("symbol/match", ["es.symbol.match", "es.string.match"]),
matcher: define("symbol/matcher", ["esnext.symbol.matcher"]),
matchAll: define("symbol/match-all", [
"es.symbol.match-all",
"es.string.match-all",
]),
metadata: define("symbol/metadata", [
"esnext.symbol.metadata",
"esnext.function.metadata",
]),
metadataKey: define("symbol/metadata-key", ["esnext.symbol.metadata-key"]),
observable: define("symbol/observable", ["esnext.symbol.observable"]),
patternMatch: define("symbol/pattern-match", [
"esnext.symbol.pattern-match",
]),
replace: define("symbol/replace", [
"es.symbol.replace",
"es.string.replace",
]),
search: define("symbol/search", ["es.symbol.search", "es.string.search"]),
species: define("symbol/species", [
"es.symbol.species",
"es.array.species",
]),
split: define("symbol/split", ["es.symbol.split", "es.string.split"]),
toPrimitive: define("symbol/to-primitive", [
"es.symbol.to-primitive",
"es.date.to-primitive",
]),
toStringTag: define("symbol/to-string-tag", [
"es.symbol.to-string-tag",
"es.object.to-string",
"es.math.to-string-tag",
"es.json.to-string-tag",
]),
unscopables: define("symbol/unscopables", ["es.symbol.unscopables"]),
},
URL: Map {
canParse: define("url/can-parse", ["web.url.can-parse", "web.url"]),
parse: define("url/parse", ["web.url.parse", "web.url"]),
},
WeakMap: Map {
from: define(null, ["esnext.weak-map.from", WEAK_MAP_DEPENDENCIES]),
of: define(null, ["esnext.weak-map.of", WEAK_MAP_DEPENDENCIES]),
},
WeakSet: Map {
from: define(null, ["esnext.weak-set.from", WEAK_SET_DEPENDENCIES]),
of: define(null, ["esnext.weak-set.of", WEAK_SET_DEPENDENCIES]),
},
Int8Array: typed_array_static_methods(&["es.typed-array.int8-array"]),
Uint8Array: uint8_typed_array_static_methods(),
Uint8ClampedArray: typed_array_static_methods(&["es.typed-array.uint8-clamped-array"]),
Int16Array: typed_array_static_methods(&["es.typed-array.int16-array"]),
Uint16Array: typed_array_static_methods(&["es.typed-array.uint16-array"]),
Int32Array: typed_array_static_methods(&["es.typed-array.int32-array"]),
Uint32Array: typed_array_static_methods(&["es.typed-array.uint32-array"]),
Float32Array: typed_array_static_methods(&["es.typed-array.float32-array"]),
Float64Array: typed_array_static_methods(&["es.typed-array.float64-array"]),
WebAssembly: Map {
CompileError: define(null, ERROR_DEPENDENCIES),
LinkError: define(null, ERROR_DEPENDENCIES),
RuntimeError: define(null, ERROR_DEPENDENCIES),
},
});
pub(crate) static INSTANCE_PROPERTIES: Lazy<ObjectMap<CoreJSPolyfillDescriptor>> = lazy_map!(Map {
asIndexedPairs: define(null, [
"esnext.async-iterator.as-indexed-pairs",
ASYNC_ITERATOR_DEPENDENCIES,
"esnext.iterator.as-indexed-pairs",
ITERATOR_DEPENDENCIES,
]),
at: define("instance/at", [
// TODO: We should introduce overloaded instance methods definition
// Before that is implemented, the `esnext.string.at` must be the first
// In pure mode, the provider resolves the descriptor as a "pure" `esnext.string.at`
// and treats the compat-data of `esnext.string.at` as the compat-data of
// pure import `instance/at`. The first polyfill here should have the lowest corejs
// supported versions.
"esnext.string.at",
"es.string.at-alternative",
"es.array.at",
]),
anchor: define(null, ["es.string.anchor"]),
big: define(null, ["es.string.big"]),
bind: define("instance/bind", ["es.function.bind"]),
blink: define(null, ["es.string.blink"]),
bold: define(null, ["es.string.bold"]),
codePointAt: define("instance/code-point-at", ["es.string.code-point-at"]),
codePoints: define("instance/code-points", ["esnext.string.code-points"]),
concat: define("instance/concat", ["es.array.concat"], None, ["String"]),
copyWithin: define("instance/copy-within", ["es.array.copy-within"]),
demethodize: define("instance/demethodize", ["esnext.function.demethodize"]),
description: define(null, ["es.symbol", "es.symbol.description"]),
dotAll: define(null, ["es.regexp.dot-all"]),
drop: define(null, [
"esnext.async-iterator.drop",
ASYNC_ITERATOR_DEPENDENCIES,
"esnext.iterator.drop",
ITERATOR_DEPENDENCIES,
]),
emplace: define("instance/emplace", [
"esnext.map.emplace",
"esnext.weak-map.emplace",
]),
endsWith: define("instance/ends-with", ["es.string.ends-with"]),
entries: define("instance/entries", ARRAY_NATURE_ITERATORS_WITH_TAG),
every: define("instance/every", [
"es.array.every",
"esnext.async-iterator.every",
// TODO: add async iterator dependencies when we support sub-dependencies
// esnext.async-iterator.every depends on es.promise
// but we don't want to pull es.promise when esnext.async-iterator is disabled
//
// ASYNC_ITERATOR_DEPENDENCIES
"esnext.iterator.every",
ITERATOR_DEPENDENCIES,
]),
exec: define(null, ["es.regexp.exec"]),
fill: define("instance/fill", ["es.array.fill"]),
filter: define("instance/filter", [
"es.array.filter",
"esnext.async-iterator.filter",
"esnext.iterator.filter",
ITERATOR_DEPENDENCIES,
]),
filterReject: define("instance/filterReject", ["esnext.array.filter-reject"]),
finally: define(null, ["es.promise.finally", PROMISE_DEPENDENCIES]),
find: define("instance/find", [
"es.array.find",
"esnext.async-iterator.find",
"esnext.iterator.find",
ITERATOR_DEPENDENCIES,
]),
findIndex: define("instance/find-index", ["es.array.find-index"]),
findLast: define("instance/find-last", ["es.array.find-last"]),
findLastIndex: define("instance/find-last-index", [
"es.array.find-last-index",
]),
fixed: define(null, ["es.string.fixed"]),
flags: define("instance/flags", ["es.regexp.flags"]),
flatMap: define("instance/flat-map", [
"es.array.flat-map",
"es.array.unscopables.flat-map",
"esnext.async-iterator.flat-map",
"esnext.iterator.flat-map",
ITERATOR_DEPENDENCIES,
]),
flat: define("instance/flat", ["es.array.flat", "es.array.unscopables.flat"]),
getFloat16: define(null, [
"esnext.data-view.get-float16",
DATA_VIEW_DEPENDENCIES,
]),
getUint8Clamped: define(null, [
"esnext.data-view.get-uint8-clamped",
DATA_VIEW_DEPENDENCIES,
]),
getYear: define(null, ["es.date.get-year"]),
group: define("instance/group", ["esnext.array.group"]),
groupBy: define("instance/group-by", ["esnext.array.group-by"]),
groupByToMap: define("instance/group-by-to-map", [
"esnext.array.group-by-to-map",
"es.map",
"es.object.to-string",
]),
groupToMap: define("instance/group-to-map", [
"esnext.array.group-to-map",
"es.map",
"es.object.to-string",
]),
fontcolor: define(null, ["es.string.fontcolor"]),
fontsize: define(null, ["es.string.fontsize"]),
forEach: define("instance/for-each", [
"es.array.for-each",
"esnext.async-iterator.for-each",
"esnext.iterator.for-each",
ITERATOR_DEPENDENCIES,
"web.dom-collections.for-each",
]),
includes: define("instance/includes", [
"es.array.includes",
"es.string.includes",
]),
indexed: define(null, [
"esnext.async-iterator.indexed",
ASYNC_ITERATOR_DEPENDENCIES,
"esnext.iterator.indexed",
ITERATOR_DEPENDENCIES,
]),
indexOf: define("instance/index-of", ["es.array.index-of"]),
isWellFormed: define("instance/is-well-formed", ["es.string.is-well-formed"]),
italic: define(null, ["es.string.italics"]),
join: define(null, ["es.array.join"]),
keys: define("instance/keys", ARRAY_NATURE_ITERATORS_WITH_TAG),
lastIndex: define(null, ["esnext.array.last-index"]),
lastIndexOf: define("instance/last-index-of", ["es.array.last-index-of"]),
lastItem: define(null, ["esnext.array.last-item"]),
link: define(null, ["es.string.link"]),
map: define("instance/map", [
"es.array.map",
"esnext.async-iterator.map",
"esnext.iterator.map",
]),
match: define(null, ["es.string.match", "es.regexp.exec"]),
matchAll: define("instance/match-all", [
"es.string.match-all",
"es.regexp.exec",
]),
name: define(null, ["es.function.name"]),
padEnd: define("instance/pad-end", ["es.string.pad-end"]),
padStart: define("instance/pad-start", ["es.string.pad-start"]),
push: define("instance/push", ["es.array.push"]),
reduce: define("instance/reduce", [
"es.array.reduce",
"esnext.async-iterator.reduce",
"esnext.iterator.reduce",
ITERATOR_DEPENDENCIES,
]),
reduceRight: define("instance/reduce-right", ["es.array.reduce-right"]),
repeat: define("instance/repeat", ["es.string.repeat"]),
replace: define(null, ["es.string.replace", "es.regexp.exec"]),
replaceAll: define("instance/replace-all", [
"es.string.replace-all",
"es.string.replace",
"es.regexp.exec",
]),
reverse: define("instance/reverse", ["es.array.reverse"]),
search: define(null, ["es.string.search", "es.regexp.exec"]),
setFloat16: define(null, [
"esnext.data-view.set-float16",
DATA_VIEW_DEPENDENCIES,
]),
setUint8Clamped: define(null, [
"esnext.data-view.set-uint8-clamped",
DATA_VIEW_DEPENDENCIES,
]),
setYear: define(null, ["es.date.set-year"]),
slice: define("instance/slice", ["es.array.slice"]),
small: define(null, ["es.string.small"]),
some: define("instance/some", [
"es.array.some",
"esnext.async-iterator.some",
"esnext.iterator.some",
ITERATOR_DEPENDENCIES,
]),
sort: define("instance/sort", ["es.array.sort"]),
splice: define("instance/splice", ["es.array.splice"]),
split: define(null, ["es.string.split", "es.regexp.exec"]),
startsWith: define("instance/starts-with", ["es.string.starts-with"]),
sticky: define(null, ["es.regexp.sticky"]),
strike: define(null, ["es.string.strike"]),
sub: define(null, ["es.string.sub"]),
substr: define(null, ["es.string.substr"]),
sup: define(null, ["es.string.sup"]),
take: define(null, [
"esnext.async-iterator.take",
ASYNC_ITERATOR_DEPENDENCIES,
"esnext.iterator.take",
ITERATOR_DEPENDENCIES,
]),
test: define(null, ["es.regexp.test", "es.regexp.exec"]),
toArray: define(null, [
"esnext.async-iterator.to-array",
ASYNC_ITERATOR_DEPENDENCIES,
"esnext.iterator.to-array",
ITERATOR_DEPENDENCIES,
]),
toAsync: define(null, [
"esnext.iterator.to-async",
ITERATOR_DEPENDENCIES,
ASYNC_ITERATOR_DEPENDENCIES,
ASYNC_ITERATOR_PROBLEM_METHODS,
]),
toExponential: define(null, ["es.number.to-exponential"]),
toFixed: define(null, ["es.number.to-fixed"]),
toGMTString: define(null, ["es.date.to-gmt-string"]),
toISOString: define(null, ["es.date.to-iso-string"]),
toJSON: define(null, ["es.date.to-json", "web.url.to-json"]),
toPrecision: define(null, ["es.number.to-precision"]),
toReversed: define("instance/to-reversed", ["es.array.to-reversed"]),
toSorted: define("instance/to-sorted", [
"es.array.to-sorted",
"es.array.sort",
]),
toSpliced: define("instance/to-spliced", ["es.array.to-spliced"]),
toString: define(null, [
"es.object.to-string",
"es.error.to-string",
"es.date.to-string",
"es.regexp.to-string",
]),
toWellFormed: define("instance/to-well-formed", ["es.string.to-well-formed"]),
trim: define("instance/trim", ["es.string.trim"]),
trimEnd: define("instance/trim-end", ["es.string.trim-end"]),
trimLeft: define("instance/trim-left", ["es.string.trim-start"]),
trimRight: define("instance/trim-right", ["es.string.trim-end"]),
trimStart: define("instance/trim-start", ["es.string.trim-start"]),
uniqueBy: define("instance/unique-by", ["esnext.array.unique-by", "es.map"]),
unshift: define("instance/unshift", ["es.array.unshift"]),
unThis: define("instance/un-this", ["esnext.function.un-this"]),
values: define("instance/values", ARRAY_NATURE_ITERATORS_WITH_TAG),
with: define("instance/with", ["es.array.with"]),
__defineGetter__: define(null, ["es.object.define-getter"]),
__defineSetter__: define(null, ["es.object.define-setter"]),
__lookupGetter__: define(null, ["es.object.lookup-getter"]),
__lookupSetter__: define(null, ["es.object.lookup-setter"]),
__proto__: define(null, ["es.object.proto"]),
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/corejs3/compat.rs | Rust | //! Ported from https://github.com/zloirock/core-js/tree/master/packages/core-js-compat
use once_cell::sync::Lazy;
use rustc_hash::FxHashMap;
use crate::Versions;
pub static DATA: Lazy<FxHashMap<String, Versions>> = Lazy::new(|| {
serde_json::from_str(include_str!("../../data/core-js-compat/data.json"))
.expect("failed parse corejs3-compat data.json")
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/corejs3/data.rs | Rust | use once_cell::sync::Lazy;
use preset_env_base::version::Version;
use rustc_hash::FxHashMap;
pub static POSSIBLE_GLOBAL_OBJECTS: &[&str] = &["global", "globalThis", "self", "window"];
pub static MODULES_BY_VERSION: Lazy<FxHashMap<&'static str, Version>> = Lazy::new(|| {
serde_json::from_str::<FxHashMap<_, _>>(include_str!(
"../../data/core-js-compat/modules-by-versions.json"
))
.expect("failed to parse modules-by-versions.json")
.into_iter()
.flat_map(|(k, v): (Version, Vec<String>)| {
v.into_iter()
.map(|s: String| (&*Box::leak(s.into_boxed_str()), k))
.collect::<Vec<_>>()
})
.collect()
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/corejs3/entry.rs | Rust | use std::sync::Arc;
use indexmap::IndexSet;
use once_cell::sync::Lazy;
use preset_env_base::{
version::{should_enable, Version},
Versions,
};
use rustc_hash::{FxBuildHasher, FxHashMap};
use swc_atoms::atom;
use swc_common::DUMMY_SP;
use swc_ecma_ast::*;
use swc_ecma_visit::VisitMut;
use super::{compat::DATA as CORE_JS_COMPAT_DATA, data::MODULES_BY_VERSION};
static ENTRIES: Lazy<FxHashMap<String, Vec<&'static str>>> = Lazy::new(|| {
serde_json::from_str::<FxHashMap<String, Vec<String>>>(include_str!(
"../../data/core-js-compat/entries.json"
))
.expect("failed to parse entries.json from core js 3")
.into_iter()
.map(|(k, v)| {
(
k,
v.into_iter()
.map(|s: String| &*Box::leak(s.into_boxed_str()))
.collect::<Vec<_>>(),
)
})
.collect()
});
#[derive(Debug)]
pub struct Entry {
is_any_target: bool,
target: Arc<Versions>,
corejs_version: Version,
pub imports: IndexSet<&'static str, FxBuildHasher>,
remove_regenerator: bool,
}
impl Entry {
pub fn new(target: Arc<Versions>, corejs_version: Version, remove_regenerator: bool) -> Self {
assert_eq!(corejs_version.major, 3);
Entry {
is_any_target: target.is_any_target(),
target,
corejs_version,
imports: Default::default(),
remove_regenerator,
}
}
/// Add imports.
/// Returns true if it's replaced.
fn add(&mut self, src: &str) -> bool {
let Entry {
is_any_target,
target,
corejs_version,
remove_regenerator,
..
} = self;
if *remove_regenerator && src == "regenerator-runtime/runtime.js" {
return true;
}
if let Some(features) = ENTRIES.get(src) {
self.imports.extend(features.iter().filter(|f| {
let feature = CORE_JS_COMPAT_DATA.get(&***f);
if !*is_any_target {
if let Some(feature) = feature {
if !should_enable(target, feature, true) {
return false;
}
}
}
if let Some(version) = MODULES_BY_VERSION.get(**f) {
return version <= corejs_version;
}
true
}));
true
} else {
false
}
}
}
impl VisitMut for Entry {
fn visit_mut_import_decl(&mut self, i: &mut ImportDecl) {
let remove = i.specifiers.is_empty() && self.add(&i.src.value);
if remove {
i.src.span = DUMMY_SP;
i.src.value = atom!("");
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/corejs3/mod.rs | Rust | pub(crate) use self::{entry::Entry, usage::UsageVisitor};
mod builtin;
mod compat;
mod data;
mod entry;
mod usage;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/corejs3/usage.rs | Rust | use std::sync::Arc;
use indexmap::IndexSet;
use preset_env_base::version::{should_enable, Version};
use rustc_hash::FxBuildHasher;
use swc_atoms::Atom;
use swc_ecma_ast::*;
use swc_ecma_visit::{noop_visit_type, Visit, VisitWith};
use super::{
builtin::{
BUILT_INS, COMMON_ITERATORS, INSTANCE_PROPERTIES, PROMISE_DEPENDENCIES, STATIC_PROPERTIES,
},
data::{MODULES_BY_VERSION, POSSIBLE_GLOBAL_OBJECTS},
};
use crate::{
corejs3::compat::DATA as CORE_JS_COMPAT_DATA, util::CoreJSPolyfillDescriptor, Versions,
};
pub(crate) struct UsageVisitor {
shipped_proposals: bool,
is_any_target: bool,
target: Arc<Versions>,
corejs_version: Version,
pub required: IndexSet<&'static str, FxBuildHasher>,
}
impl UsageVisitor {
pub fn new(target: Arc<Versions>, shipped_proposals: bool, corejs_version: Version) -> Self {
// let mut v = Self { required: Vec::new() };
//
//
// let is_web_target = target
// .iter()
// .any(|(name, version)| name != "node" &&
// version.is_some());
//
// println!(
// "is_any_target={:?}\nis_web_target={:?}",
// is_any_target, is_web_target
// );
//
// // Web default
// if is_any_target || is_web_target {
// v.add(&["web.timers", "web.immediate",
// "web.dom.iterable"]); }
// v
Self {
shipped_proposals,
is_any_target: target.is_any_target(),
target,
corejs_version,
required: Default::default(),
}
}
fn add(&mut self, desc: &CoreJSPolyfillDescriptor) {
let deps = desc.global;
// TODO: Exclude based on object
self.may_inject_global(deps)
}
/// Add imports
fn may_inject_global(&mut self, features: &[&'static str]) {
let UsageVisitor {
shipped_proposals,
is_any_target,
target,
corejs_version,
..
} = self;
self.required.extend(features.iter().filter(|f| {
if !*shipped_proposals && f.starts_with("esnext.") {
return false;
}
let feature = CORE_JS_COMPAT_DATA.get(&***f);
if !*is_any_target {
if let Some(feature) = feature {
if !should_enable(target, feature, true) {
return false;
}
}
}
if let Some(version) = MODULES_BY_VERSION.get(**f) {
return version <= corejs_version;
}
true
}));
}
fn add_builtin(&mut self, built_in: &str) {
if let Some(features) = BUILT_INS.get(built_in) {
self.add(features)
}
}
fn add_property_deps(&mut self, obj: &Expr, prop: &Atom) {
let obj = match obj {
Expr::Ident(i) => &i.sym,
_ => {
self.add_property_deps_inner(None, prop);
return;
}
};
self.add_property_deps_inner(Some(obj), prop)
}
fn add_property_deps_inner(&mut self, obj: Option<&Atom>, prop: &Atom) {
if let Some(obj) = obj {
if POSSIBLE_GLOBAL_OBJECTS.contains(&&**obj) {
self.add_builtin(prop);
}
if let Some(map) = STATIC_PROPERTIES.get(&**obj) {
if let Some(features) = map.get(&**prop) {
self.add(features);
return;
}
}
}
if let Some(features) = INSTANCE_PROPERTIES.get(&**prop) {
self.add(features);
}
}
fn visit_object_pat_props(&mut self, obj: &Expr, props: &[ObjectPatProp]) {
let obj = match obj {
Expr::Ident(i) => Some(&i.sym),
_ => None,
};
for p in props {
match p {
ObjectPatProp::KeyValue(KeyValuePatProp {
key: PropName::Ident(i),
..
}) => self.add_property_deps_inner(obj, &i.sym),
ObjectPatProp::Assign(AssignPatProp { key, .. }) => {
self.add_property_deps_inner(obj, &key.sym)
}
_ => {}
}
}
}
}
impl Visit for UsageVisitor {
noop_visit_type!(fail);
/// `[a, b] = c`
fn visit_array_pat(&mut self, p: &ArrayPat) {
p.visit_children_with(self);
self.may_inject_global(COMMON_ITERATORS)
}
fn visit_assign_expr(&mut self, e: &AssignExpr) {
e.visit_children_with(self);
if let AssignTarget::Pat(AssignTargetPat::Object(o)) = &e.left {
self.visit_object_pat_props(&e.right, &o.props)
}
}
fn visit_bin_expr(&mut self, e: &BinExpr) {
e.visit_children_with(self);
if e.op == op!("in") {
// 'entries' in Object
// 'entries' in [1, 2, 3]
if let Expr::Lit(Lit::Str(s)) = &*e.left {
self.add_property_deps(&e.right, &s.value);
}
}
}
/// import('something').then(...)
/// RegExp(".", "us")
fn visit_call_expr(&mut self, e: &CallExpr) {
e.visit_children_with(self);
if let Callee::Import(_) = &e.callee {
self.may_inject_global(PROMISE_DEPENDENCIES)
}
}
fn visit_expr(&mut self, e: &Expr) {
e.visit_children_with(self);
if let Expr::Ident(i) = e {
self.add_builtin(&i.sym)
}
}
/// `[...spread]`
fn visit_expr_or_spread(&mut self, e: &ExprOrSpread) {
e.visit_children_with(self);
if e.spread.is_some() {
self.may_inject_global(COMMON_ITERATORS)
}
}
/// for-of
fn visit_for_of_stmt(&mut self, s: &ForOfStmt) {
s.visit_children_with(self);
self.may_inject_global(COMMON_ITERATORS)
}
fn visit_function(&mut self, f: &Function) {
f.visit_children_with(self);
if f.is_async {
self.may_inject_global(PROMISE_DEPENDENCIES)
}
}
fn visit_member_expr(&mut self, e: &MemberExpr) {
e.obj.visit_with(self);
if let MemberProp::Computed(c) = &e.prop {
if let Expr::Lit(Lit::Str(s)) = &*c.expr {
self.add_property_deps(&e.obj, &s.value);
}
c.visit_with(self);
}
// Object.entries
// [1, 2, 3].entries
if let MemberProp::Ident(i) = &e.prop {
self.add_property_deps(&e.obj, &i.sym)
}
}
fn visit_super_prop_expr(&mut self, e: &SuperPropExpr) {
if let SuperProp::Computed(c) = &e.prop {
c.visit_with(self);
}
}
fn visit_var_declarator(&mut self, d: &VarDeclarator) {
d.visit_children_with(self);
if let Some(ref init) = d.init {
if let Pat::Object(ref o) = d.name {
self.visit_object_pat_props(init, &o.props)
}
} else if let Pat::Object(ref o) = d.name {
self.visit_object_pat_props(&Ident::default().into(), &o.props)
}
}
/// `yield*`
fn visit_yield_expr(&mut self, e: &YieldExpr) {
e.visit_children_with(self);
if e.delegate {
self.may_inject_global(COMMON_ITERATORS)
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/lib.rs | Rust | #![deny(clippy::all)]
#![allow(dead_code)]
#![recursion_limit = "256"]
use std::{path::PathBuf, sync::Arc};
use preset_env_base::query::targets_to_versions;
pub use preset_env_base::{query::Targets, version::Version, BrowserData, Versions};
use rustc_hash::FxHashSet;
use serde::Deserialize;
use swc_atoms::{atom, Atom};
use swc_common::{comments::Comments, pass::Optional, FromVariant, Mark, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms::{
compat::{
bugfixes,
class_fields_use_set::class_fields_use_set,
es2015::{self, generator::generator},
es2016, es2017, es2018, es2019, es2020, es2021, es2022, es3,
regexp::{self, regexp},
},
feature::FeatureFlag,
Assumptions,
};
use swc_ecma_utils::{prepend_stmts, ExprFactory};
use swc_ecma_visit::{visit_mut_pass, VisitMut, VisitMutWith, VisitWith};
pub use self::transform_data::Feature;
#[macro_use]
mod util;
mod corejs2;
mod corejs3;
mod regenerator;
mod transform_data;
pub fn preset_env<C>(
unresolved_mark: Mark,
comments: Option<C>,
c: Config,
assumptions: Assumptions,
feature_set: &mut FeatureFlag,
) -> impl Pass
where
C: Comments + Clone,
{
let loose = c.loose;
let targets = targets_to_versions(c.targets).expect("failed to parse targets");
let is_any_target = targets.is_any_target();
let (include, included_modules) = FeatureOrModule::split(c.include);
let (exclude, excluded_modules) = FeatureOrModule::split(c.exclude);
let pass = noop_pass();
macro_rules! should_enable {
($feature:ident, $default:expr) => {{
let f = transform_data::Feature::$feature;
!exclude.contains(&f)
&& (c.force_all_transforms
|| (is_any_target
|| include.contains(&f)
|| f.should_enable(&targets, c.bugfixes, $default)))
}};
}
macro_rules! add {
($prev:expr, $feature:ident, $pass:expr) => {{
add!($prev, $feature, $pass, false)
}};
($prev:expr, $feature:ident, $pass:expr, $default:expr) => {{
let f = transform_data::Feature::$feature;
let enable = should_enable!($feature, $default);
if !enable {
*feature_set |= swc_ecma_transforms::feature::FeatureFlag::$feature;
}
if c.debug {
println!("{}: {:?}", f.as_str(), enable);
}
($prev, Optional::new($pass, enable))
}};
}
let pass = (
pass,
Optional::new(
class_fields_use_set(assumptions.pure_getters),
assumptions.set_public_class_fields,
),
);
let pass = {
let enable_dot_all_regex = should_enable!(DotAllRegex, false);
let enable_named_capturing_groups_regex = should_enable!(NamedCapturingGroupsRegex, false);
let enable_sticky_regex = should_enable!(StickyRegex, false);
let enable_unicode_property_regex = should_enable!(UnicodePropertyRegex, false);
let enable_unicode_regex = should_enable!(UnicodeRegex, false);
let enable_unicode_sets_regex = should_enable!(UnicodeSetsRegex, false);
let enable = enable_dot_all_regex
|| enable_named_capturing_groups_regex
|| enable_sticky_regex
|| enable_unicode_property_regex
|| enable_unicode_regex;
(
pass,
Optional::new(
regexp(regexp::Config {
dot_all_regex: enable_dot_all_regex,
// TODO: add Feature:HasIndicesRegex
has_indices: false,
// TODO: add Feature::LookbehindAssertion
lookbehind_assertion: false,
named_capturing_groups_regex: enable_named_capturing_groups_regex,
sticky_regex: enable_sticky_regex,
unicode_property_regex: enable_unicode_property_regex,
unicode_regex: enable_unicode_regex,
unicode_sets_regex: enable_unicode_sets_regex,
}),
enable,
),
)
};
// Proposals
// ES2022
// static block needs to be placed before class property
// because it transforms into private static property
let pass = add!(pass, ClassStaticBlock, es2022::static_blocks());
let pass = add!(
pass,
ClassProperties,
es2022::class_properties(
es2022::class_properties::Config {
private_as_properties: loose || assumptions.private_fields_as_properties,
set_public_fields: loose || assumptions.set_public_class_fields,
constant_super: loose || assumptions.constant_super,
no_document_all: loose || assumptions.no_document_all,
pure_getter: loose || assumptions.pure_getters,
},
unresolved_mark
)
);
let pass = add!(pass, PrivatePropertyInObject, es2022::private_in_object());
// ES2021
let pass = add!(
pass,
LogicalAssignmentOperators,
es2021::logical_assignments()
);
// ES2020
let pass = add!(pass, ExportNamespaceFrom, es2020::export_namespace_from());
let pass = add!(
pass,
NullishCoalescing,
es2020::nullish_coalescing(es2020::nullish_coalescing::Config {
no_document_all: loose || assumptions.no_document_all
})
);
let pass = add!(
pass,
OptionalChaining,
es2020::optional_chaining(
es2020::optional_chaining::Config {
no_document_all: loose || assumptions.no_document_all,
pure_getter: loose || assumptions.pure_getters
},
unresolved_mark
)
);
// ES2019
let pass = add!(pass, OptionalCatchBinding, es2019::optional_catch_binding());
// ES2018
let pass = add!(
pass,
ObjectRestSpread,
es2018::object_rest_spread(es2018::object_rest_spread::Config {
no_symbol: loose || assumptions.object_rest_no_symbols,
set_property: loose || assumptions.set_spread_properties,
pure_getters: loose || assumptions.pure_getters
})
);
// ES2017
let pass = add!(
pass,
AsyncToGenerator,
es2017::async_to_generator(
es2017::async_to_generator::Config {
ignore_function_name: loose || assumptions.ignore_function_name,
ignore_function_length: loose || assumptions.ignore_function_length,
},
unresolved_mark
)
);
// ES2016
let pass = add!(pass, ExponentiationOperator, es2016::exponentiation());
// ES2015
let pass = add!(pass, BlockScopedFunctions, es2015::block_scoped_functions());
let pass = add!(
pass,
TemplateLiterals,
es2015::template_literal(es2015::template_literal::Config {
ignore_to_primitive: loose || assumptions.ignore_to_primitive_hint,
mutable_template: loose || assumptions.mutable_template_object
}),
true
);
let pass = add!(
pass,
Classes,
es2015::classes(es2015::classes::Config {
constant_super: loose || assumptions.constant_super,
no_class_calls: loose || assumptions.no_class_calls,
set_class_methods: loose || assumptions.set_class_methods,
super_is_callable_constructor: loose || assumptions.super_is_callable_constructor,
})
);
let pass = add!(
pass,
Spread,
es2015::spread(es2015::spread::Config { loose }),
true
);
let pass = add!(pass, ObjectSuper, es2015::object_super());
let pass = add!(pass, FunctionName, es2015::function_name());
let pass = add!(pass, ShorthandProperties, es2015::shorthand());
let pass = add!(
pass,
Parameters,
es2015::parameters(
es2015::parameters::Config {
ignore_function_length: loose || assumptions.ignore_function_length
},
unresolved_mark
)
);
let pass = add!(pass, ArrowFunctions, es2015::arrow(unresolved_mark));
let pass = add!(pass, DuplicateKeys, es2015::duplicate_keys());
let pass = add!(pass, StickyRegex, es2015::sticky_regex());
// TODO: InstanceOf,
let pass = add!(pass, TypeOfSymbol, es2015::typeof_symbol());
let pass = add!(
pass,
ForOf,
es2015::for_of(es2015::for_of::Config {
loose,
assume_array: loose || assumptions.iterable_is_array
}),
true
);
let pass = add!(
pass,
ComputedProperties,
es2015::computed_properties(es2015::computed_props::Config { loose }),
true
);
let pass = add!(
pass,
Destructuring,
es2015::destructuring(es2015::destructuring::Config { loose }),
true
);
let pass = add!(
pass,
BlockScoping,
es2015::block_scoping(unresolved_mark),
true
);
let pass = add!(
pass,
Regenerator,
generator(unresolved_mark, comments),
true
);
let pass = add!(pass, NewTarget, es2015::new_target(), true);
// TODO:
// Literals,
// ObjectSuper,
// DotAllRegex,
// UnicodeRegex,
// AsyncGeneratorFunctions,
// UnicodePropertyRegex,
// JsonStrings,
// NamedCapturingGroupsRegex,
// ES 3
let pass = add!(pass, PropertyLiterals, es3::property_literals());
let pass = add!(
pass,
MemberExpressionLiterals,
es3::member_expression_literals()
);
let pass = add!(pass, ReservedWords, es3::reserved_words(c.dynamic_import));
// Bugfixes
let pass = add!(pass, BugfixEdgeDefaultParam, bugfixes::edge_default_param());
let pass = add!(
pass,
BugfixAsyncArrowsInClass,
bugfixes::async_arrows_in_class(unresolved_mark)
);
let pass = add!(
pass,
BugfixTaggedTemplateCaching,
bugfixes::template_literal_caching()
);
let pass = add!(
pass,
BugfixSafariIdDestructuringCollisionInFunctionExpression,
bugfixes::safari_id_destructuring_collision_in_function_expression()
);
if c.debug {
println!("Targets: {:?}", targets);
}
(
pass,
visit_mut_pass(Polyfills {
mode: c.mode,
regenerator: should_enable!(Regenerator, true),
corejs: c.core_js.unwrap_or(Version {
major: 3,
minor: 0,
patch: 0,
}),
shipped_proposals: c.shipped_proposals,
targets,
includes: included_modules,
excludes: excluded_modules,
unresolved_mark,
}),
)
}
#[derive(Debug)]
struct Polyfills {
mode: Option<Mode>,
targets: Arc<Versions>,
shipped_proposals: bool,
corejs: Version,
regenerator: bool,
includes: FxHashSet<String>,
excludes: FxHashSet<String>,
unresolved_mark: Mark,
}
impl Polyfills {
fn collect<T>(&mut self, m: &mut T) -> Vec<Atom>
where
T: VisitWith<corejs2::UsageVisitor>
+ VisitWith<corejs3::UsageVisitor>
+ VisitMutWith<corejs2::Entry>
+ VisitMutWith<corejs3::Entry>,
{
let required = match self.mode {
None => Default::default(),
Some(Mode::Usage) => {
let mut r = match self.corejs {
Version { major: 2, .. } => {
let mut v = corejs2::UsageVisitor::new(self.targets.clone());
m.visit_with(&mut v);
v.required
}
Version { major: 3, .. } => {
let mut v = corejs3::UsageVisitor::new(
self.targets.clone(),
self.shipped_proposals,
self.corejs,
);
m.visit_with(&mut v);
v.required
}
_ => unimplemented!("corejs version other than 2 / 3"),
};
if regenerator::is_required(m) {
r.insert("regenerator-runtime/runtime.js");
}
r
}
Some(Mode::Entry) => match self.corejs {
Version { major: 2, .. } => {
let mut v = corejs2::Entry::new(self.targets.clone(), self.regenerator);
m.visit_mut_with(&mut v);
v.imports
}
Version { major: 3, .. } => {
let mut v =
corejs3::Entry::new(self.targets.clone(), self.corejs, !self.regenerator);
m.visit_mut_with(&mut v);
v.imports
}
_ => unimplemented!("corejs version other than 2 / 3"),
},
};
required
.iter()
.filter(|s| {
!s.starts_with("esnext") || !required.contains(&s.replace("esnext", "es").as_str())
})
.filter(|s| !self.excludes.contains(&***s))
.map(|s| -> Atom {
if *s != "regenerator-runtime/runtime.js" {
format!("core-js/modules/{}.js", s).into()
} else {
"regenerator-runtime/runtime.js".to_string().into()
}
})
.chain(self.includes.iter().map(|s| {
if s != "regenerator-runtime/runtime.js" {
format!("core-js/modules/{}.js", s).into()
} else {
"regenerator-runtime/runtime.js".to_string().into()
}
}))
.collect::<Vec<_>>()
}
}
impl VisitMut for Polyfills {
fn visit_mut_module(&mut self, m: &mut Module) {
let span = m.span;
let required = self.collect(m);
if cfg!(debug_assertions) {
let mut v = required.into_iter().collect::<Vec<_>>();
v.sort();
prepend_stmts(
&mut m.body,
v.into_iter().map(|src| {
ImportDecl {
span,
specifiers: Vec::new(),
src: Str {
span: DUMMY_SP,
raw: None,
value: src,
}
.into(),
type_only: false,
with: None,
phase: Default::default(),
}
.into()
}),
);
} else {
prepend_stmts(
&mut m.body,
required.into_iter().map(|src| {
ImportDecl {
span,
specifiers: Vec::new(),
src: Str {
span: DUMMY_SP,
raw: None,
value: src,
}
.into(),
type_only: false,
with: None,
phase: Default::default(),
}
.into()
}),
);
}
m.body.retain(|item| !matches!(item, ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl { src, .. })) if src.span == DUMMY_SP && src.value == atom!("")));
}
fn visit_mut_script(&mut self, m: &mut Script) {
let span = m.span;
let required = self.collect(m);
if cfg!(debug_assertions) {
let mut v = required.into_iter().collect::<Vec<_>>();
v.sort();
prepend_stmts(
&mut m.body,
v.into_iter().map(|src| {
ExprStmt {
span: DUMMY_SP,
expr: CallExpr {
span,
callee: Ident {
ctxt: SyntaxContext::empty().apply_mark(self.unresolved_mark),
sym: "require".into(),
..Default::default()
}
.as_callee(),
args: vec![Str {
span: DUMMY_SP,
value: src,
raw: None,
}
.as_arg()],
type_args: None,
..Default::default()
}
.into(),
}
.into()
}),
);
} else {
prepend_stmts(
&mut m.body,
required.into_iter().map(|src| {
ExprStmt {
span: DUMMY_SP,
expr: CallExpr {
span,
callee: Ident {
ctxt: SyntaxContext::empty().apply_mark(self.unresolved_mark),
sym: "require".into(),
..Default::default()
}
.as_callee(),
args: vec![Str {
span: DUMMY_SP,
value: src,
raw: None,
}
.as_arg()],
..Default::default()
}
.into(),
}
.into()
}),
);
}
}
}
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
pub enum Mode {
#[serde(rename = "usage")]
Usage,
#[serde(rename = "entry")]
Entry,
}
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct Config {
#[serde(default)]
pub mode: Option<Mode>,
#[serde(default)]
pub debug: bool,
#[serde(default)]
pub dynamic_import: bool,
#[serde(default)]
pub loose: bool,
/// Skipped es features.
///
/// e.g.)
/// - `core-js/modules/foo`
#[serde(default)]
pub skip: Vec<Atom>,
#[serde(default)]
pub include: Vec<FeatureOrModule>,
#[serde(default)]
pub exclude: Vec<FeatureOrModule>,
/// The version of the used core js.
#[serde(default)]
pub core_js: Option<Version>,
#[serde(default)]
pub targets: Option<Targets>,
#[serde(default = "default_path")]
pub path: PathBuf,
#[serde(default)]
pub shipped_proposals: bool,
#[serde(default)]
pub force_all_transforms: bool,
#[serde(default)]
pub bugfixes: bool,
}
fn default_path() -> PathBuf {
if cfg!(target_arch = "wasm32") {
Default::default()
} else {
std::env::current_dir().unwrap()
}
}
#[derive(Debug, Clone, Deserialize, FromVariant)]
#[serde(untagged)]
pub enum FeatureOrModule {
Feature(Feature),
CoreJsModule(String),
}
impl FeatureOrModule {
pub fn split(vec: Vec<FeatureOrModule>) -> (Vec<Feature>, FxHashSet<String>) {
let mut features: Vec<_> = Default::default();
let mut modules: FxHashSet<_> = Default::default();
for v in vec {
match v {
FeatureOrModule::Feature(f) => features.push(f),
FeatureOrModule::CoreJsModule(m) => {
modules.insert(m);
}
}
}
(features, modules)
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/regenerator/mod.rs | Rust | pub(super) fn is_required<T>(_: &T) -> bool {
false
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/transform_data.rs | Rust | use once_cell::sync::Lazy;
use preset_env_base::{
version::{should_enable, Version},
BrowserData, Versions,
};
use rustc_hash::FxHashMap;
use string_enum::StringEnum;
impl Feature {
pub fn should_enable(self, target: &Versions, bugfixes: bool, default: bool) -> bool {
let f = if bugfixes {
&BUGFIX_FEATURES[&self]
} else {
if !FEATURES.contains_key(&self) {
return false;
}
&FEATURES[&self]
};
should_enable(target, f, default)
}
}
#[derive(Clone, Copy, PartialEq, Eq, StringEnum, Hash)]
#[non_exhaustive]
pub enum Feature {
/// `transform-template-literals`
TemplateLiterals,
/// `transform-literals`
Literals,
/// `transform-function-name`
FunctionName,
/// `transform-arrow-functions`
ArrowFunctions,
/// `transform-block-scoped-functions`
BlockScopedFunctions,
/// `transform-classes`
Classes,
/// `transform-object-super`
ObjectSuper,
/// `transform-shorthand-properties`
ShorthandProperties,
/// `transform-duplicate-keys`
DuplicateKeys,
/// `transform-computed-properties`
ComputedProperties,
/// `transform-for-of`
ForOf,
/// `transform-sticky-regex`
StickyRegex,
/// `transform-dotall-regex`
DotAllRegex,
/// `transform-unicode-regex`
UnicodeRegex,
/// `transform-spread`
Spread,
/// `transform-parameters`
Parameters,
/// `transform-destructuring`
Destructuring,
/// `transform-block-scoping`
BlockScoping,
/// `transform-typeof-symbol`
TypeOfSymbol,
/// `transform-new-target`
NewTarget,
/// `transform-regenerator`
Regenerator,
/// `transform-exponentiation-operator`
ExponentiationOperator,
/// `transform-async-to-generator`
AsyncToGenerator,
/// `transform-async-generator-functions`
#[string_enum(alias("proposal-async-generator-functions"))]
AsyncGeneratorFunctions,
/// `transform-object-rest-spread`
#[string_enum(alias("proposal-object-rest-spread"))]
ObjectRestSpread,
/// `transform-unicode-property-regex`
#[string_enum(alias("proposal-unicode-property-regex"))]
UnicodePropertyRegex,
/// `transform-json-strings`
#[string_enum(alias("proposal-json-strings"))]
JsonStrings,
/// `transform-optional-catch-binding`
#[string_enum(alias("proposal-optional-catch-binding"))]
OptionalCatchBinding,
/// `transform-named-capturing-groups-regex`
NamedCapturingGroupsRegex,
/// `transform-member-expression-literals`
MemberExpressionLiterals,
/// `transform-property-literals`
PropertyLiterals,
/// `transform-reserved-words`
ReservedWords,
/// `transform-export-namespace-from`
#[string_enum(alias("proposal-export-namespace-from"))]
ExportNamespaceFrom,
/// `transform-nullish-coalescing-operator`
#[string_enum(alias("proposal-nullish-coalescing-operator"))]
NullishCoalescing,
/// `transform-logical-assignment-operators`
#[string_enum(alias("proposal-logical-assignment-operators"))]
LogicalAssignmentOperators,
/// `transform-optional-chaining`
#[string_enum(alias("proposal-optional-chaining"))]
OptionalChaining,
/// `transform-class-properties`
#[string_enum(alias("proposal-class-properties"))]
ClassProperties,
/// `transform-numeric-separator`
#[string_enum(alias("proposal-numeric-separator"))]
NumericSeparator,
/// `transform-private-methods`
#[string_enum(alias("proposal-private-methods"))]
PrivateMethods,
/// `transform-class-static-block`
#[string_enum(alias("proposal-class-static-block"))]
ClassStaticBlock,
/// `transform-private-property-in-object`
#[string_enum(alias("proposal-private-property-in-object"))]
PrivatePropertyInObject,
/// `transform-unicode-escapes`
UnicodeEscapes,
/// `transform-unicode-sets-regex`
UnicodeSetsRegex,
/// `transform-duplicate-named-capturing-groups-regex`
DuplicateNamedCapturingGroupsRegex, // TODO
/// `bugfix/transform-async-arrows-in-class`
BugfixAsyncArrowsInClass,
/// `bugfix/transform-edge-default-parameters`
BugfixEdgeDefaultParam,
/// `bugfix/transform-tagged-template-caching`
BugfixTaggedTemplateCaching,
/// `bugfix/transform-safari-id-destructuring-collision-in-function-expression`
BugfixSafariIdDestructuringCollisionInFunctionExpression,
/// `bugfix/transform-edge-function-name`
BugfixTransformEdgeFunctionName, // TODO
/// `bugfix/transform-safari-block-shadowing`
BugfixTransformSafariBlockShadowing, // TODO
/// `bugfix/transform-safari-for-shadowing`
BugfixTransformSafariForShadowing, // TODO
/// `bugfix/transform-v8-spread-parameters-in-optional-chaining`
BugfixTransformV8SpreadParametersInOptionalChaining, // TODO
/// `bugfix/transform-v8-static-class-fields-redefine-readonly`
BugfixTransformV8StaticClassFieldsRedefineReadonly, // TODO
/// `bugfix/transform-firefox-class-in-computed-class-key`
BugfixTransformFirefoxClassInComputedClassKey, // TODO
/// `bugfix/transform-safari-class-field-initializer-scope`
BugfixTransformSafariClassFieldInitializerScope, // TODO
}
pub(crate) static FEATURES: Lazy<FxHashMap<Feature, BrowserData<Option<Version>>>> =
Lazy::new(|| {
let map: FxHashMap<Feature, BrowserData<Option<String>>> =
serde_json::from_str(include_str!("../data/@babel/compat-data/data/plugins.json"))
.expect("failed to parse json");
map.into_iter()
.map(|(feature, version)| {
(
feature,
version.map_value(|version| {
if matches!(version.as_deref(), Some("tp")) {
return None;
}
version.map(|v| {
v.parse().unwrap_or_else(|err| {
panic!("failed to parse `{v}` as a version: {err:?}")
})
})
}),
)
})
.collect()
});
pub(crate) static BUGFIX_FEATURES: Lazy<FxHashMap<Feature, BrowserData<Option<Version>>>> =
Lazy::new(|| {
let map: FxHashMap<Feature, BrowserData<Option<String>>> = serde_json::from_str(
include_str!("../data/@babel/compat-data/data/plugin-bugfixes.json"),
)
.expect("failed to parse json");
FEATURES
.clone()
.into_iter()
.chain(map.into_iter().map(|(feature, version)| {
(
feature,
version.map_value(|version| version.map(|v| v.parse().unwrap())),
)
}))
.collect()
});
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn arrow() {
assert!(Feature::ArrowFunctions.should_enable(
&BrowserData {
ie: Some("11.0.0".parse().unwrap()),
..Default::default()
},
false,
false
));
}
#[test]
fn tpl_lit() {
assert!(!Feature::TemplateLiterals.should_enable(
&BrowserData {
chrome: Some("71.0.0".parse().unwrap()),
..Default::default()
},
false,
true
));
}
#[test]
fn tpl_lit_bugfixes() {
// Enable template literals pass in Safari 9 without bugfixes option
assert!(Feature::TemplateLiterals.should_enable(
&BrowserData {
safari: Some("9.0.0".parse().unwrap()),
..Default::default()
},
false,
false
));
assert!(!Feature::BugfixTaggedTemplateCaching.should_enable(
&BrowserData {
safari: Some("10.0.0".parse().unwrap()),
..Default::default()
},
false,
false
));
// Don't enable it with the bugfixes option. Bugfix pass enabled instead.
assert!(!Feature::TemplateLiterals.should_enable(
&BrowserData {
safari: Some("9.0.0".parse().unwrap()),
..Default::default()
},
true,
false
));
assert!(Feature::BugfixTaggedTemplateCaching.should_enable(
&BrowserData {
safari: Some("9.0.0".parse().unwrap()),
..Default::default()
},
true,
false
));
assert!(!Feature::BugfixTaggedTemplateCaching.should_enable(
&BrowserData {
safari: Some("13.0.0".parse().unwrap()),
..Default::default()
},
true,
false
));
}
#[test]
fn edge_default_param_bug() {
// Enable params pass in Edge 17 without bugfixes option
assert!(Feature::Parameters.should_enable(
&BrowserData {
edge: Some("17.0.0".parse().unwrap()),
..Default::default()
},
false,
false
));
assert!(!Feature::BugfixEdgeDefaultParam.should_enable(
&BrowserData {
edge: Some("17.0.0".parse().unwrap()),
..Default::default()
},
false,
false
));
// Don't enable it with the bugfixes option. Bugfix pass enabled instead.
assert!(!Feature::Parameters.should_enable(
&BrowserData {
edge: Some("17.0.0".parse().unwrap()),
..Default::default()
},
true,
false
));
assert!(Feature::BugfixEdgeDefaultParam.should_enable(
&BrowserData {
edge: Some("17.0.0".parse().unwrap()),
..Default::default()
},
true,
false
));
assert!(!Feature::BugfixEdgeDefaultParam.should_enable(
&BrowserData {
edge: Some("18.0.0".parse().unwrap()),
..Default::default()
},
true,
false
));
}
#[test]
fn async_arrows_in_class_bug() {
// Enable async to generator pass in Safari 10.1 without bugfixes option
assert!(Feature::AsyncToGenerator.should_enable(
&BrowserData {
safari: Some("10.1.0".parse().unwrap()),
..Default::default()
},
false,
false
));
assert!(!Feature::BugfixAsyncArrowsInClass.should_enable(
&BrowserData {
safari: Some("10.1.0".parse().unwrap()),
..Default::default()
},
false,
false
));
// Don't enable it with the bugfixes option. Bugfix pass enabled instead.
assert!(!Feature::AsyncToGenerator.should_enable(
&BrowserData {
safari: Some("10.1.0".parse().unwrap()),
..Default::default()
},
true,
false
));
assert!(Feature::BugfixAsyncArrowsInClass.should_enable(
&BrowserData {
safari: Some("10.1.0".parse().unwrap()),
..Default::default()
},
true,
false
));
assert!(!Feature::BugfixAsyncArrowsInClass.should_enable(
&BrowserData {
safari: Some("11.1.0".parse().unwrap()),
..Default::default()
},
true,
false
));
}
#[test]
fn block_scoping() {
// Enable block scoping pass in Safari 10 without bugfixes option
assert!(Feature::BlockScoping.should_enable(
&BrowserData {
safari: Some("10.0.0".parse().unwrap()),
..Default::default()
},
false,
false
));
// Don't enable it with the bugfixes option.
assert!(!Feature::BlockScoping.should_enable(
&BrowserData {
safari: Some("10.0.0".parse().unwrap()),
..Default::default()
},
true,
false
));
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/src/util.rs | Rust | use rustc_hash::FxHashMap;
pub(crate) type ObjectMap<T> = FxHashMap<&'static str, T>;
pub(crate) type ObjectMap2<V> = ObjectMap<ObjectMap<V>>;
pub(crate) fn descriptor(
pure: Option<&'static str>,
global: &'static [&'static str],
name: Option<&'static str>,
exclude: &'static [&'static str],
) -> CoreJSPolyfillDescriptor {
let name = name.unwrap_or_else(|| global[0]);
CoreJSPolyfillDescriptor {
pure,
global,
name,
exclude,
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct CoreJSPolyfillDescriptor {
pub pure: Option<&'static str>,
pub global: &'static [&'static str],
pub name: &'static str,
pub exclude: &'static [&'static str],
}
macro_rules! val {
(& $v:expr) => {
&$v
};
($v:expr) => {
&$v
};
}
macro_rules! expand_array_like {
($name:ident) => {{
$name
}};
($lit:literal) => {{
[$lit]
}};
// An array with a single item
([$first:tt]) => {{
expand_array_like!($first)
}};
([$($tt:tt)*]) => {{
expand_array_like!(@ARRAY, All(&[]), Wip(), Rest($($tt)*))
}};
// Eat string literal as much as we can, and create a single array literal from them.
(@ARRAY, All($all:expr), Wip($($s:literal)*), Rest($first:literal, $($rest:tt)*)) => {{
expand_array_like!(@ARRAY, All($all), Wip($($s)* $first), Rest($($rest)*))
}};
(@ARRAY, All($all:expr), Wip($($s:literal)*), Rest($first:literal)) => {{
expand_array_like!(@ARRAY, All($all), Wip($($s)* $first), Rest())
}};
// We need to stop eating string literals.
(@ARRAY, All($all:expr), Wip($($s:literal)*), Rest($first:ident, $($rest:tt)*)) => {{
static PREV: &[&str]= &[$($s),*];
dynamic_concat($all, dynamic_concat(PREV, $first))
}};
(@ARRAY, All($all:expr), Wip($($s:literal)*), Rest($first:ident)) => {{
static PREV: &[&str]= &[$($s),*];
dynamic_concat($all, dynamic_concat(PREV, $first))
}};
// Done
(@ARRAY, All($all:expr), Wip($($s:literal)*), Rest()) => {{
static CUR_LIT: &[&str]= &[$($s),*];
dynamic_concat($all, CUR_LIT)
}};
}
/// Calls [`descriptor`].
macro_rules! define_descriptor {
(
$pure:literal,
[$($global:tt)*]
) => {{
define_descriptor!(@Done, Some($pure), &expand_array_like!([$($global)*]), None, &[])
}};
(
null,
[$($global:tt)*]
) => {{
define_descriptor!(@Done, None, &expand_array_like!([$($global)*]), None, &[])
}};
(
null,
$global:ident
) => {{
define_descriptor!(@Done, None, &expand_array_like!($global), None, &[])
}};
(
$pure:literal,
$global:ident
) => {{
define_descriptor!(@Done, Some($pure), &expand_array_like!($global), None, &[])
}};
(
$pure:literal,
$global:ident,
$first:tt
) => {{
define_descriptor!(@Done, Some($pure), &expand_array_like!($($global)*), Some($first), &[])
}};
(
$pure:literal,
[$($global:tt)*],
$first:literal
) => {{
define_descriptor!(@Done, Some($pure), &expand_array_like!([$($global)*]), Some($first), &[])
}};
(
$pure:literal,
[$($global:tt)*],
None,
$exclude:tt
) => {{
define_descriptor!(@Done, Some($pure), &expand_array_like!([$($global)*]), None, &$exclude)
}};
// @Indirect: No need to distinguish `$pure`.
(
@Done,
$pure:expr,
$global:expr,
$name:expr,
$exclude:expr
) => {{
$crate::util::descriptor($pure, $global, $name, $exclude)
}};
}
macro_rules! lazy_map {
($($tt:tt)*) => {{
Lazy::new(|| map!($($tt)*))
}};
}
macro_rules! map {
(
Map {
$($rest:tt)+
}
) => {{
map!(@Key, Map {}, Rest {$($rest)*})
}};
(
@Key,
Map {
$($i:ident : $e:expr,)*
},
Rest {
$ni:ident : $($rest:tt)+
}
) => {{
map!(
@Value,
Map {
$(
$i : $e,
)*
},
Rest {
$($rest)*
},
Wip {
$ni
}
)
}};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
[$($v:tt)*], $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
map!(@Key, Map {
$(
$i : $e,
)*
$ni : val!(&[$($v)*]),
}, Rest {$($rest)*})
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
&[$($v:tt)*], $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
map!(@Key, Map {
$(
$i : $e,
)*
$ni : val!(&[$($v)*]),
},
Rest {
$($rest)*
})
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
$v:literal, $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
map!(@Key, Map {
$(
$i : $e,
)*
$ni : &[$v],
},
Rest {
$($rest)*
})
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
$v:literal $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
map!(@Key, Map {
$(
$i : $e,
)*
$ni : &[$v],
},
Rest {
$($rest)*
})
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
&$v:ident, $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
map!(@Key, Map {
$(
$i : $e,
)*
$ni : $v,
},
Rest {
$($rest)*
})
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
Map { $($m:tt)* }, $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
map!(
@Key,
Map {
$(
$i : $e,
)*
$ni : map!(Map { $($m)* }),
},
Rest {
$($rest)*
}
)
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
$v:ident, $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
map!(
@Key,
Map {
$(
$i : $e,
)*
$ni : $v,
},
Rest {
$($rest)*
}
)
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
*$v:ident, $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
map!(
@Key,
Map {
$(
$i : $e,
)*
$ni : (*$v).clone(),
},
Rest {
$($rest)*
}
)
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
define($($args:tt)*), $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
map!(
@Key,
Map {
$(
$i : $e,
)*
$ni : define_descriptor!($($args)*),
},
Rest {
$($rest)*
}
)
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
$callee:ident($($args:tt)*), $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
map!(
@Key,
Map {
$(
$i : $e,
)*
$ni : $callee($($args)*),
},
Rest {
$($rest)*
}
)
};
// Done
(
@Key,
Map {
$($i:ident : $e:expr,)*
},
Rest {}
) => {{
let mut map = ObjectMap::default();
$(
map.insert(stringify!($i), $e);
)*
map
}};
}
macro_rules! data_map {
(
Map {
$($rest:tt)+
}
) => {
data_map!(@Ident, Map {}, Rest {$($rest)*})
};
(
@Ident,
Map {
$($i:ident : $e:expr,)*
},
Rest {
$ni:ident : $($rest:tt)+
}
) => {
data_map!(@Value, Map {
$(
$i : $e,
)*
},
Rest {
$($rest)*
},
Wip {
$ni
})
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
[$($v:tt)*], $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
data_map!(@Ident, Map {
$(
$i : $e,
)*
$ni : val!(&[$($v)*]),
}, Rest {$($rest)*})
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
&[$($v:tt)*], $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
data_map!(@Ident, Map {
$(
$i : $e,
)*
$ni : val!(&[$($v)*]),
},
Rest {
$($rest)*
})
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
$v:literal, $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
data_map!(@Ident, Map {
$(
$i : $e,
)*
$ni : &[$v],
},
Rest {
$($rest)*
})
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
$v:literal $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
data_map!(@Ident, Map {
$(
$i : $e,
)*
$ni : &[$v],
},
Rest {
$($rest)*
})
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
&$v:ident, $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
data_map!(@Ident, Map {
$(
$i : $e,
)*
$ni : $v,
},
Rest {
$($rest)*
})
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
Map { $($m:tt)* }, $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
data_map!(@Ident, Map {
$(
$i : $e,
)*
$ni : data_map!(Map { $($m)* }),
},
Rest {
$($rest)*
})
};
(
@Value,
Map {
$($i:ident : $e:expr,)*
},
Rest {
$v:ident, $($rest:tt)*
},
Wip {
$ni:ident
}
) => {
data_map!(@Ident, Map {
$(
$i : $e,
)*
$ni : $v,
},
Rest {
$($rest)*
})
};
// Done
(
@Ident,
Map {
$($i:ident : $e:expr,)*
},
Rest {}
) => {
&[
$(
(stringify!($i), $e)
),*
]
};
}
pub(crate) type DataMap<T> = &'static [(&'static str, T)];
pub(crate) type FeatureMap = DataMap<&'static [&'static str]>;
pub(crate) trait DataMapExt<T> {
fn as_ref(&self) -> DataMap<T>;
fn get_data(&self, s: &str) -> Option<&'static T> {
for (k, v) in self.as_ref() {
if *k == s {
return Some(v);
}
}
None
}
}
impl<T> DataMapExt<T> for DataMap<T> {
fn as_ref(&self) -> &'static [(&'static str, T)] {
self
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-all-orig/input.mjs | JavaScript | Array.from; // static method
Map; // built-in
new Promise(); // new builtin
Symbol.match; // as member expression
_arr[Symbol.iterator](); // Symbol.iterator
// no import
Array.asdf;
Array2.from;
Map2;
new Promise2();
Symbol.asdf;
Symbol2.match;
_arr9[Symbol2.iterator]();
_arr9[Symbol.iterator2]();
G.assign; // static method
function H(WeakMap) {
var blah = new WeakMap();
} // shadowed
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-all-orig/output.mjs | JavaScript | import "core-js/modules/es7.symbol.async-iterator";
import "core-js/modules/es6.symbol";
import "core-js/modules/es6.regexp.match";
import "core-js/modules/es6.promise";
import "core-js/modules/web.dom.iterable";
import "core-js/modules/es6.array.iterator";
import "core-js/modules/es6.object.to-string";
import "core-js/modules/es6.map";
import "core-js/modules/es6.string.iterator";
import "core-js/modules/es6.array.from";
Array.from; // static method
Map; // built-in
new Promise(); // new builtin
Symbol.match; // as member expression
_arr[Symbol.iterator](); // Symbol.iterator
// no import
Array.asdf;
Array2.from;
Map2;
new Promise2();
Symbol.asdf;
Symbol2.match;
_arr9[Symbol2.iterator]();
_arr9[Symbol.iterator2]();
G.assign; // static method
function H(WeakMap) {
var blah = new WeakMap();
} // shadowed
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-browserslist-config-ignore/input.mjs | JavaScript | const a = new Map();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-browserslist-config-ignore/output.mjs | JavaScript | import "core-js/modules/web.dom.iterable";
var a = new Map();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-evaluated-class-methods/input.mjs | JavaScript | var objectClass = Object;
var arrayInstance = [];
var assignStr = "assign";
var entriesStr = "entries";
var valuesStr = "values";
var includesStr = "includes";
var findStr = "find";
// Allow static methods be assigned to variables only directly in the module.
externalVar[valuesStr]; // don't include
objectClass[assignStr]({}); // include
arrayInstance[entriesStr]({}); // don't include
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-evaluated-class-methods/output.mjs | JavaScript | import "core-js/modules/es6.object.assign";
import "core-js/modules/web.dom.iterable";
import "core-js/modules/es6.array.iterator";
import "core-js/modules/es6.object.to-string";
var objectClass = Object;
var arrayInstance = [];
var assignStr = "assign";
var entriesStr = "entries";
var valuesStr = "values";
var includesStr = "includes";
var findStr = "find"; // Allow static methods be assigned to variables only directly in the module.
externalVar[valuesStr]; // don't include
objectClass[assignStr]({}); // include
arrayInstance[entriesStr]({}); // don't include
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-evaluated-instance-methods/input.mjs | JavaScript | var arrayInstance = [];
var includesStr = "includes";
var findStr = "find";
// Allow instance methods be assigned to variables.
arrayInstance[includesStr](); // include
externalVar[findStr]; // include
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-evaluated-instance-methods/output.mjs | JavaScript | import "core-js/modules/es6.array.find";
import "core-js/modules/es7.array.includes";
var arrayInstance = [];
var includesStr = "includes";
var findStr = "find"; // Allow instance methods be assigned to variables.
arrayInstance[includesStr](); // include
externalVar[findStr]; // include
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-evaluated-not-confident/input.mjs | JavaScript | Object["values"](); // include
[]["map"](); // include
Object[keys](); // don't include
[][filter](); // don't include
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-evaluated-not-confident/output.mjs | JavaScript | import "core-js/modules/es6.array.map";
import "core-js/modules/web.dom.iterable";
import "core-js/modules/es6.array.iterator";
import "core-js/modules/es6.object.to-string";
import "core-js/modules/es7.object.values";
Object['values'](); // include
[]['map'](); // include
Object[keys](); // don't include
[][filter](); // don't include
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-instance-methods/input.mjs | JavaScript | Array.from; // static function
Map; // top level built-in
// instance methods may have false positives (which is ok)
a.includes(); // method call
b["find"]; // computed string?
c.prototype.findIndex(); // .prototype
d.fill.bind(); //.bind
e.padStart.apply(); // .apply
f.padEnd.call(); // .call
String.prototype.startsWith.call; // prototype.call
var { codePointAt, endsWith } = k; // destructuring
var asdf = "copyWithin";
var asdf2 = "split";
var asdf3 = "re" + "place";
i[asdf]; // computed with identifier
j[`search`]; // computed with template
k[asdf3]; // computed with concat strings
var { [asdf2]: _a } = k; // computed
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-instance-methods/output.mjs | JavaScript | import "core-js/modules/es6.regexp.split";
import "core-js/modules/es6.regexp.replace";
import "core-js/modules/es6.regexp.search";
import "core-js/modules/es6.array.copy-within";
import "core-js/modules/es6.string.ends-with";
import "core-js/modules/es6.string.code-point-at";
import "core-js/modules/es6.string.starts-with";
import "core-js/modules/es7.string.pad-end";
import "core-js/modules/es7.string.pad-start";
import "core-js/modules/es6.array.fill";
import "core-js/modules/es6.function.bind";
import "core-js/modules/es6.array.find-index";
import "core-js/modules/es6.array.find";
import "core-js/modules/es7.array.includes";
import "core-js/modules/es6.string.includes";
import "core-js/modules/web.dom.iterable";
import "core-js/modules/es6.array.iterator";
import "core-js/modules/es6.object.to-string";
import "core-js/modules/es6.map";
import "core-js/modules/es6.string.iterator";
import "core-js/modules/es6.array.from";
Array.from; // static function
Map; // top level built-in
// instance methods may have false positives (which is ok)
a.includes(); // method call
b['find']; // computed string?
c.prototype.findIndex(); // .prototype
d.fill.bind(); //.bind
e.padStart.apply(); // .apply
f.padEnd.call(); // .call
String.prototype.startsWith.call; // prototype.call
var _k = k,
codePointAt = _k.codePointAt,
endsWith = _k.endsWith; // destructuring
var asdf = "copyWithin";
var asdf2 = "split";
var asdf3 = "re" + "place";
i[asdf]; // computed with identifier
j["search"]; // computed with template
k[asdf3]; // computed with concat strings
var _k2 = k,
_a = _k2[asdf2]; // computed
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-modules-namespaced-orig/input.mjs | JavaScript | import * as ns from "ns";
ns.map;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-modules-namespaced-orig/output.mjs | JavaScript | import * as ns from "ns";
ns.map;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-modules-transform/input.mjs | JavaScript | Promise;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-modules-transform/output.js | JavaScript | "use strict";
require("core-js/modules/es6.promise");
require("core-js/modules/es6.object.to-string");
Promise;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-regenerator-used-async-and-promise-native-support/input.mjs | JavaScript | async function a() {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-regenerator-used-async-and-promise-native-support/output.mjs | JavaScript | async function a() {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-regenerator-used-async-native-support/input.mjs | JavaScript | async function a() {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-regenerator-used-async-native-support/output.mjs | JavaScript | async function a() {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-regenerator-used-async/input.mjs | JavaScript | async function a() {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-regenerator-used-async/output.mjs | JavaScript | import "regenerator-runtime/runtime";
function a() {
return regeneratorRuntime.async(function a$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
case "end":
return _context.stop();
}
}
});
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-regenerator-used-generator-native-support/input.mjs | JavaScript | function* a() {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-regenerator-used-generator-native-support/output.mjs | JavaScript | function* a() {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_preset_env/tests/fixtures/corejs2/.usage-regenerator-used-generator/input.mjs | JavaScript | function* a() {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.