• Stars
    star
    166
  • Rank 227,748 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 2 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Extractors for ECMAScript

Extractors for ECMAScript

A proposal to introduce Extractors (a.k.a. "Extractor Objects") to ECMAScript.

Extractors would augment the syntax for BindingPattern and AssignmentPattern to allow for new destructuring forms, as in the following example:

// binding patterns
const Foo(y) = x;           // instance-array destructuring
const Foo{y} = x;           // instance-object destructuring
const [Foo(y)] = x;         // nesting
const [Foo{y}] = x;         // ..
const { z: Foo(y) } = x;    // ..
const { z: Foo{y} } = x;    // ..
const Foo(Bar(y)) = x;      // ..
const X.Foo(y) = x;         // qualified names (i.e., a.b.c)

// assignment patterns
Foo(y) = x;                 // instance-array destructuring
Foo{y} = x;                 // instance-object destructuring
[Foo(y)] = x;               // nesting
[Foo{y}] = x;               // ..
({ z: Foo(y) } = x);        // ..
({ z: Foo{y} } = x);        // ..
Foo(Bar(y)) = x;            // ..
X.Foo(y) = x;               // qualified names (i.e., a.b.c)

In addition, this would leverage the new Symbol.matcher built-in symbol added by the Pattern Matching proposal. When destructuring using the new form, the Symbol.matcher method would be called and its result would be destructured instead.

Status

Stage: 1
Champion: Ron Buckton (@rbuckton)

For more information see the TC39 proposal process.

Authors

  • Ron Buckton (@rbuckton)

Motivations

ECMAScript currently has no mechanism for executing user-defined logic during destructuring, which means that operations related to data validation and transformation may require multiple statements:

function toInstant(value) {
  if (value instanceof Temporal.Instant) {
    return value;
  } else if (value instanceof Date) {
    return Temporal.Instant.fromEpochMilliseconds(+value);
  } else if (typeof value === "string") {
    return Temporal.Instant.from(value);
  } else {
    throw new TypeError();
  }
}

class Book {
  constructor({
    isbn,
    title,
    createdAt = Temporal.Now.instant(),
    modifiedAt = createdAt
  }) {
    this.isbn = isbn;
    this.title = title;
    this.createdAt = toInstant(createdAt);
    // some effort duplicated if `modifiedAt` was `undefined`
    this.modifiedAt = toInstant(modifiedAt);
  }
}

new Book({ isbn: "...", title: "...", createdAt: Temporal.Instant.from("...") });
new Book({ isbn: "...", title: "...", createdAt: new Date() });
new Book({ isbn: "...", title: "...", createdAt: "..." });

With Extractors, such validation and transformation logic can be encapsulated and reused inside of the binding pattern:

const InstantExtractor = {
  [Symbol.matcher]: value =>
    value instanceof Temporal.Instant ? { matched: true, value: [value] } :
    value instanceof Date ? { matched: true, value: [Temporal.Instant.fromEpochMilliseconds(value.getTime())] } :
    typeof value === "string" ? { matched: true, value: [Temporal.Instant.from(value)] } :
    { matched: false };
  }
};

class Book {
  constructor({
    isbn,
    title,
    // Extract `createdAt` as an Instant
    createdAt: InstantExtractor(createdAt) = Temporal.Now.instant(),
    modifiedAt: InstantExtractor(modifiedAt) = createdAt
  }) {
    this.isbn = isbn;
    this.title = title;
    this.createdAt = createdAt;
    this.modifiedAt = modifiedAt;
  }
}

new Book({ isbn: "...", title: "...", createdAt: Temporal.Instant.from("...") });
new Book({ isbn: "...", title: "...", createdAt: new Date() });
new Book({ isbn: "...", title: "...", createdAt: "..." });

This would also be extremely useful when paired with a forthcoming enum proposal with support for Algebraic Data Types (ADT):

// Rust-like enum of algebraic data types:
enum Option of ADT {
  Some(value),
  None
}

// construction
const x = Option.Some(1);

// destructuring
const Option.Some(y) = x;
y; // 1

// pattern matching
match (x) {
  when Option.Some(y): console.log(y); // 1
  when Option.None: console.log("none");
}
// Another ADT enum example:
enum Message of ADT {
  Quit,
  Move{x, y},
  Write(message),
  ChangeColor(r, g, b),
}

// construction
const msg1 = Message.Move{ x: 10, y: 10 }; // NOTE: possible novel syntax for enum construction
const msg2 = Message.Write("Hello");
const msg3 = Message.ChangeColor(0x00, 0xff, 0xff);

// destructuring
const Message.Move{ x, y } = msg1;      // x: 10, y: 10
const Message.Write(message) = msg2;    // message: "Hello"
const Message.ChangeColor(r, g, b) = msg3;     // r: 0, g: 255, b: 255

// pattern matching
match (msg) {
  when Message.Move{ x, y }: ...;
  when Message.Write(message): ...;
  when Message.ChangeColor(r, g, b): ...;
  when Message.Quit: ...;
}

Proposed Solution

Extractors are loosely based on Scala's Extractor Objects and Rust's Pattern Matching. Extractors extend the syntax for BindingPattern and AssignmentPattern to allow for the evaluation of user-defined logic for validation and transformation.

Extractors come in two flavors: Array Extractors, which perform array destructuring on a successful match result, and Object Extractors, which perform object destructuring. Both types of extractors start with a reference to a value in scope using a QualifiedName, which is essentially an IdentifierReference (i.e., Point, InstantExtractor, etc.) or a dotted-name (i.e., Option.Some, Message.Move, etc.).

When an Extractor is evaluated during destructuring, its QualifiedName is evaluated, and that evaluated result's [Symbol.matcher] method is invoked with the current value to be destructured, returning a Match Result object like { matched: boolean, value: object }.

If matched is true, the value property is further destructured based on the type of Extractor that was defined. If matched is false, a TypeError is thrown.

Array Extractors

An Array Extractor consists of a QualifiedName followed by a parenthesized list of additional destructuring patterns:

// binding pattern
let Foo(a, { b }, [c]) = ...;

// assignment pattern
Foo(a, { b }, [c]) = ...;

Parentheses (()) are used instead of square brackets ([]) for several reasons:

  • Avoids collisions with a ElementAccessExpression when the extractor is part of an assignment pattern:
    Option.Some[value] = opt; // already an element access expression
  • Ensures a consistent syntax between binding and assignment patterns:
    let Option.Some(value) = opt;
    Option.Some(value) = opt;
  • Allows destructuring (and pattern matching) to mirror construction/application:
    let opt = Option.Some(x);
    let Option.Some(y) = opt;
    
    opt = Option.Some(x);
    Option.Some(y) = opt;

Object Extractors

An Object Extractor consists of a QualifiedName followed by an object destructuring pattern:

// binding pattern
const Message.Move{ x, y } = ...;

// assignment pattern
(Message.Move{ x, y } = ...);

Curly braces ({}) are used here to be otherwise consistent with normal object destructuring. Outermost parentheses would also likely be required to avoid too large of a syntax carve-out for identifier { ... } at the statement level.

The use of curly braces here is also intended to mirror a potential future property-literal construction syntax that might be used by Algebraic Data Types or other constructors, i.e.:

const enum Message of ADT {
  Move{ x, y },
  Write(text),
  Quit
}

// ADT construction
const msg = Message.Move{ x: 10, y: 20 };

// property-literal construction potentially used by fixed-shape objects (i.e., "struct"),
// or a user-defined construction mechanism similar to tagged templates or via a built-in-symbol named method:
struct Point { x, y };
const pt = Point{ x: 10, y: 20 };

Prior Art

Related Proposals

Examples

The examples in this section use a desugaring to explain the underlying semantics, given the following helper:

function %InvokeCustomMatcher%(val, matchable) {
    // see https://tc39.es/proposal-pattern-matching/#sec-custom-matcher
}

function %InvokeCustomMatcherOrThrow%(val, matchable) {
  const result = %InvokeCustomMatcher%(val, matchable);
  if (result === ~not-matched~) {
    throw new TypeError();
  }
  return result;
}

Extractor Destructuring

The statement

const Foo(y) = x;

is approximately the same as the following transposed representation

const [y] = %InvokeCustomMatcherOrThrow%(Foo, x);

The statement

const Foo{y} = x;

is approximately the same as the following transposed representation

const {y} = %InvokeCustomMatcherOrThrow%(Foo, x);

Nested Extractor Destructuring

The statement

const Foo(Bar(y)) = x;

is approximately the same as the following transposed representation

const [_a] = %InvokeCustomMatcherOrThrow%(Foo, x);
const [y] = %InvokeCustomMatcherOrThrow%(Bar, _a);

Custom Logic During Destructuring

Given the following definition

const MapExtractor = {
  [Symbol.matcher](map) {
    const obj = {};
    for (const [key, value] of map) {
      obj[typeof key === "symbol" ? key : `${key}`] = value;
    }
    return { matched: true, value: obj };
  }
};

const obj = {
    map: new Map([["a", 1], ["b", 2]])
};

The statement

const { map: MapExtractor{ a, b } } = obj;

is approximately the same as the following transposed representation

const { map: _temp } = obj;
const { a, b } = %InvokeCustomMatcherOrThrow%(MapExtractor, _temp);

Regular Expressions

// potentially built-in as part of Pattern Matching
RegExp.prototype[Symbol.matcher] = function (value) {
  const match = this.exec(value);
  if (match === null) return { matched: false };

  return {
    matched: true,
    value: {
      // spread in named capture groups for use with object destructuring
      ...match.groups,

      // iterator for use with array destructuring
      [Symbol.iterator]: () => match[Symbol.iterator]()
    }
  }
};

const IsoDate = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/;
const IsoTime = /^(?<hours>\d{2}):(?<minutes>\d{2}):(?<seconds>\d{2})$/;
const IsoDateTime = /^(?<date>[^TZ]+)T(?<time>[^Z]+)Z/;

// match `input`, extract, and destructure (or throw if match fails) using...

// ...an object extractor
const IsoDate{ year, month, day } = input;

// ...an array extractor
const IsoDate(, year, month, day) = input;

// concise, multi-step extraction using nested destructuring:
const IsoDateTime{
    date: IsoDate{ year, month, day },
    time: IsoTime{ hours, minutes, seconds }
} = input;
// 1. Matches `input` via `IsoDatTime` RegExp and extracts `date` and `time`
// 2. Matches `date` via `IsoDate` RegExp and extracts `year`, `month`, and `day` as lexical bindings
// 3. Matches `time` vai `IsoTime` RegExp and extracts `hours`, `minutes`, and `seconds` as lexical bindings

Potential Grammar

The grammar definition in this section is very early and subject to change.

++  QualifiedName[Yield, Await] :
++      IdentifierReference[?Yield, ?Await]
++      QualifiedName[?Yield, ?Await] `.` IdentifierName

    BindingPattern[Yield, Await] :
        ObjectBindingPattern[?Yield, ?Await]
        ArrayBindingPattern[?Yield, ?Await]
++      QualifiedName[?Yield, ?Await] ExtractorBindingPattern[?Yield, ?Await]

++  ExtractorBindingPattern[Yield, Await] :
++      ExtractorObjectBindingPattern[?Yield, ?Await]
++      ExtractorArrayBindingPattern[?Yield, ?Await]

++  ExtractorObjectBindingPattern[Yield, Await] :
++      ObjectBindingPattern[?Yield, ?Await]

++  ExtractorArrayBindingPattern[Yield, Await] :
++      `(` Elision? BindingRestElement[?Yield, ?Await]? `)`
++      `(` BindingElementList[?Yield, ?Await] `)`
++      `(` BindingElementList[?Yield, ?Await] `,` Elision? BindingRestElement[?Yield, ?Await]? `)`

    AssignmentPattern[Yield, Await] :
        ObjectAssignmentPattern[?Yield, ?Await]
        ArrayAssignmentPattern[?Yield, ?Await]
++      QualifiedName[?Yield, ?Await] ExtractorAssignmentPattern[?Yield, ?Await]

++  ExtractorAssignmentPattern[Yield, Await] :
++      ExtractorObjectAssignmentPattern[?Yield, ?Await]
++      ExtractorArrayAssignmentPattern[?Yield, ?Await]

++  ExtractorObjectAssignmentPattern[Yield, Await] :
++      ObjectAssignmentPattern[?Yield, ?Await]

++  ExtractorArrayAssignmentPattern[Yield, Await] :
++      `(` Elision? BindingRestElement[?Yield, ?Await]? `)`
++      `(` BindingElementList[?Yield, ?Await] `)`
++      `(` BindingElementList[?Yield, ?Await] `,` Elision? BindingRestElement[?Yield, ?Await]? `)`

++  FunctionCall[Yield, Await] :
++      CallExpression[?Yield, ?Await] Arguments[?Yield, ?Await]

    CallExpression[Yield, Await] :
        CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await]
        SuperCall[?Yield, ?Await]
        ImportCall[?Yield, ?Await]
++      FunctionCall[?Yield, ?Await]
--      CallExpression[?Yield, ?Await] Arguments[?Yield, ?Await]
        CallExpression[?Yield, ?Await] `[` Expression[+In, ?Yield, ?Await] `]`
        CallExpression[?Yield, ?Await] `.` IdentifierName
        CallExpression[?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged]
        CallExpression[?Yield, ?Await] `.` PrivateIdentifier

Potential Semantics

The semantics in this section are very early and subject to change.

8.5.2 โ€” Runtime Semantics: BindingInitialization

The syntax-directed operation BindingInitialization takes arguments value and environment.

++  BindingPattern : QualifiedName ExtractorBindingPattern
  1. Let ref be the result of evaluating QualifiedName.
  2. Let extractor be ? GetValue(ref).
  3. Let obj be ? InvokeCustomMatcherOrThrow(extractor, value).
  4. Return the result of performing BindingInitialization of ExtractorBindingPattern with arguments obj and environment.
++  ExtractorBindingPattern : ExtractorArrayBindingPattern
  1. Let iteratorRecord be ? GetIterator(value).
  2. Let result be IteratorBindingInitialization of ExtractorBindingPattern with arguments iteratorRecord and environment.
  3. If iteratorRecord.[[Done]] is false, return ? IteratorClose(iteratorRecord, result).
  4. Return result.

8.5.2.2 โ€” Runtime Semantics: InvokeCustomMatcherOrThrow ( val, matchable )

  1. Let result be ? InvokeCustomMatcher(val, matchable).
  2. If result is not-matched, throw a TypeError exception.
  3. Return result.

8.5.3 โ€” Runtime Semantics: IteratorBindingInitialization

The syntax-directed operation IteratorBindingInitialization takes arguments iteratorRecord and environment.

    ArrayBindingPattern : `[` `]`
++  ExtractorBindingPattern : `(` `)`
  1. Return NormalCompletion(empty).
    ArrayBindingPattern : `[` Elision `]`
++  ExtractorBindingPattern : `(` Elision `)`
  1. Return the result of performing IteratorDestructuringAssignmentEvaluation of Elision with iteratorRecord as the argument.
    ArrayBindingPattern : `[` Elision? BindingRestElement `]`
++  ExtractorBindingPattern : `(` Elision? BindingRestElement `)`
  1. If Elision is present, then
    1. Perform ? IteratorDestructuringAssignmentEvaluation of Elision with iteratorRecord as the argument.
  2. Return the result of performing IteratorBindingInitialization for BindingRestElement with iteratorRecord and environment as arguments.
    ArrayBindingPattern : `[` BindingElementList `,` Elision `]`
++  ExtractorBindingPattern : `(` BindingElementList `,` Elision `)`
  1. Perform ? IteratorBindingInitialization for BindingElementList with iteratorRecord and environment as arguments.
  2. Return the result of performing IteratorDestructuringAssignmentEvaluation of Elision with iteratorRecord as the argument.
    ArrayBindingPattern : `[` BindingElementList `,` Elision? BindingRestElement `]`
++  ExtractorBindingPattern : `(` BindingElementList `,` Elision? BindingRestElement `)`
  1. Perform ? IteratorBindingInitialization for BindingElementList with iteratorRecord and environment as arguments.
  2. If Elision is present, then
    1. Perform ? IteratorDestructuringAssignmentEvaluation of Elision with iteratorRecord as the argument.
  3. Return the result of performing IteratorBindingInitialization for BindingRestElement with iteratorRecord and environment as arguments.

13.15.1 โ€” Static Semantics: Early Errors

    AssignmentExpression : LeftHandSideExpression = AssignmentExpression

If LeftHandSideExpression is an ObjectLiteral or, an ArrayLiteral, or a FunctionCall the following Early Error rules are applied:

  • It is a Syntax Error if LeftHandSideExpression is not covering an AssignmentPattern.
  • All Early Error rules for AssignmentPattern and its derived productions also apply to the AssignmentPattern that is covered by LeftHandSideExpression.

If LeftHandSideExpression is neither an ObjectLiteral, nor an ArrayLiteral, nor a FunctionCall, the following Early Error rule is applied:

  • It is a Syntax Error if AssignmentTargetType of LeftHandSideExpression is not simple.
    AssignmentExpression :
        LeftHandSideExpression AssignmentOperator AssignmentExpression
        LeftHandSideExpression `&&=` AssignmentExpression
        LeftHandSideExpression `||=` AssignmentExpression
        LeftHandSideExpression `??=` AssignmentExpression
  • It is a Syntax Error if AssignmentTargetType of LeftHandSideExpression is not simple.

13.15.2 โ€” Runtime Semantics: Evaluation

    AssignmentExpression : LeftHandSideExpression `=` AssignmentExpression
  1. If LeftHandSideExpression is neither an ObjectLiteral, nor an ArrayLiteral, nor a FunctionCall, then
    1. Let lref be the result of evaluating LeftHandSideExpression.
    2. ReturnIfAbrupt(lref).
    3. If IsAnonymousFunctionDefinition(AssignmentExpression) and IsIdentifierRef of LeftHandSideExpression are both true, then
      1. Let rval be NamedEvaluation of AssignmentExpression with argument lref.[[ReferencedName]].
    4. Else,
      1. Let rref be the result of evaluating AssignmentExpression.
      2. Let rval be ? GetValue(rref).
    5. Perform ? PutValue(lref, rval).
    6. Return rval.
  2. Let assignmentPattern be the AssignmentPattern that is covered by LeftHandSideExpression.
  3. Let rref be the result of evaluating AssignmentExpression.
  4. Let rval be ? GetValue(rref).
  5. Perform ? DestructuringAssignmentEvaluation of assignmentPattern using rval as the argument.
  6. Return rval.

13.15.5.2 โ€” Runtime Semantics: DestructuringAssignmentEvaluation

The syntax-directed operation DestructuringAssignmentEvaluation takes argument value. It is defined piecewise over the following productions:

++  AssignmentPattern : QualifiedName ExtractorAssignmentPattern
  1. Let ref be the result of evaluating QualifiedName.
  2. Let extractor be ? GetValue(ref).
  3. Let obj be ? InvokeCustomMatcherOrThrow(extractor, value).
  4. Return the result of performing DestructuringAssignmentEvaluation of ExtractorAssignmentPattern with argument obj.
    ArrayAssignmentPattern : `[` `]`
++  ExtractorArrayAssignmentPattern : `(` `)`
  1. Let iteratorRecord be ? GetIterator(value).
  2. Return ? IteratorClose(iteratorRecord, NormalCompletion(empty)).
    ArrayAssignmentPattern : `[` Elision `]`
++  ExtractorArrayAssignmentPattern : `(` Elision `)`
  1. Let iteratorRecord be ? GetIterator(value).
  2. Let result be IteratorDestructuringAssignmentEvaluation of Elision with argument iteratorRecord.
  3. If iteratorRecord.[[Done]] is false, return ? IteratorClose(iteratorRecord, result).
  4. Return result.
    ArrayAssignmentPattern : `[` Elision? AssignmentRestElement `]`
++  ExtractorArrayAssignmentPattern : `(` Elision? AssignmentRestElement `)`
  1. Let iteratorRecord be ? GetIterator(value).
  2. If Elision is present, then
    1. Let status be IteratorDestructuringAssignmentEvaluation of Elision with argument iteratorRecord.
    2. If status is an abrupt completion, then
      1. Assert: iteratorRecord.[[Done]] is true.
      2. Return Completion(status).
  3. Let result be IteratorDestructuringAssignmentEvaluation of AssignmentRestElement with argument iteratorRecord.
  4. If iteratorRecord.[[Done]] is false, return ? IteratorClose(iteratorRecord, result).
  5. Return result.
    ArrayAssignmentPattern : `[` AssignmentElementList `]`
++  ExtractorArrayAssignmentPattern : `(` AssignmentElementList `)`
  1. Let iteratorRecord be ? GetIterator(value).
  2. Let result be IteratorDestructuringAssignmentEvaluation of AssignmentElementList with argument iteratorRecord.
  3. If iteratorRecord.[[Done]] is false, return ? IteratorClose(iteratorRecord, result).
  4. Return result.
    ArrayAssignmentPattern : `[` AssignmentElementList `,` Elision? AssignmentRestElement? `]`
++  ExtractorArrayAssignmentPattern : `(` AssignmentElementList `,` Elision? AssignmentRestElement? `)`
  1. Let iteratorRecord be ? GetIterator(value).
  2. Let status be IteratorDestructuringAssignmentEvaluation of AssignmentElementList with argument iteratorRecord.
  3. If status is an abrupt completion, then
    1. If iteratorRecord.[[Done]] is false, return ? IteratorClose(iteratorRecord, status).
    2. Return Completion(status).
  4. If Elision is present, then
    1. Set status to the result of performing IteratorDestructuringAssignmentEvaluation of Elision with iteratorRecord as the argument.
    2. If status is an abrupt completion, then
      1. Assert: iteratorRecord.[[Done]] is true.
      2. Return Completion(status).
  5. If AssignmentRestElement is present, then
    1. Set status to the result of performing IteratorDestructuringAssignmentEvaluation of AssignmentRestElement with iteratorRecord as the argument.
  6. If iteratorRecord.[[Done]] is false, return ? IteratorClose(iteratorRecord, status).
  7. Return Completion(status).

API

This proposal would adopt (and continue to align with) the behavior of Custom Matchers from the Pattern Matching proposal:

  • A Custom Matcher is a regular ECMAScript Object value with a [Symbol.matcher] method that accepts a single argument and returns a Match Result.
  • A Match Result is a regular ECMAScript Object value with a matched property whose value is a Boolean, and a value property whose value will be destructured by the relevant Extractor pattern.
  • Symbol.matcher is a built-in Symbol value.

Relation to Pattern Matching

We believe that Extractors would also be extremely valuable as part of the Pattern Matching Proposal, and intend to discuss adoption with the champions should this proposal be adopted.

Extractors could easily be added to MatchPattern using the same syntax as proposed for destructuring, which would allow for more concise and potentially more readily understood code:

match (opt) {
  // without extractors
  when (${Option.Some} with [value]): ...;

  // with extractors
  when (Option.Some(value)): ...;
}

match (msg) {
  // without extractors
  when (${Message.Move} with { x, y }): ...;

  // with extractors
  when (Message.Move{ x, y }): ...;
}

This is even more evident with respect to complex, nested patterns:

match (opt) {
  // without extractors
  when (${Option.Some} with [${Message.Move} with { x, y }]): ...;
  when (${Option.Some} with [${Message.Write} with [text]]): ...;

  // with extractors
  when (Option.Some(Message.Move{ x, y })): ...;
  when (Option.Some(Message.Write(text))): ...;
}

Relation to Enums and Algebraic Data Types

We strongly believe that ECMAScript will eventually adopt some form of the current enum proposal, given the particular value that Algebraic Data Types could provide. The Enum proposal would strongly favor consistent and coherent syntax between declaration, construction, destructuring, and pattern matching, as in the following example:

enum Message of ADT {
  Quit,
  Move{x, y},
  Write(message),
  ChangeColor(r, g, b),
}

// construction
const msg1 = Message.Move{ x: 10, y: 10 };
const msg2 = Message.Write("Hello");
const msg3 = Message.ChangeColor(0x00, 0xff, 0xff);

// destructuring
const Message.Move{x, y} = msg1;        // x: 10, y: 10
const Message.Write(message) = msg2;    // message: "Hello"
const Message.ChangeColor(r, g, b);     // r: 0, g: 255, b: 255

// pattern matching
match (msg) {
  when Message.Move{x, y}: ...;
  when Message.Write(message): ...;
  when Message.ChangeColor(r, g, b): ...;
  when Message.Quit: ...;
}

Here, declaration, construction, destructuring, and pattern matching are consistent for ADT enum members and values:

enum Message of ADT { Move{ x, y } }      // declaration
const msg =   Message.Move{ x, y };       // construction
const         Message.Move{ x, y } = msg; // destructuring
match (msg) {
  when        Message.Move{ x, y }: ...;  // pattern matching
}
enum Message of ADT { Write(message) }      // declaration
const msg =   Message.Write(message);       // construction
const         Message.Write(message) = msg; // destructuring
match (msg) {
  when        Message.Write(message): ...;  // pattern matching
}

TODO

The following is a high-level list of tasks to progress through each stage of the TC39 proposal process:

Stage 1 Entrance Criteria

  • Identified a "champion" who will advance the addition.
  • Prose outlining the problem or need and the general shape of a solution.
  • Illustrative examples of usage.
  • High-level API.

Stage 2 Entrance Criteria

Stage 3 Entrance Criteria

Stage 4 Entrance Criteria

  • Test262 acceptance tests have been written for mainline usage scenarios and merged.
  • Two compatible implementations which pass the acceptance tests: [1], [2].
  • A pull request has been sent to tc39/ecma262 with the integrated spec text.
  • The ECMAScript editor has signed off on the pull request.

More Repositories

1

proposals

Tracking ECMAScript Proposals
17,177
star
2

ecma262

Status, process, and documents for ECMA-262
HTML
14,437
star
3

proposal-pipeline-operator

A proposal for adding a useful pipe operator to JavaScript.
HTML
7,534
star
4

proposal-pattern-matching

Pattern matching syntax for ECMAScript
HTML
5,498
star
5

proposal-optional-chaining

HTML
4,942
star
6

proposal-type-annotations

ECMAScript proposal for type syntax that is erased - Stage 1
JavaScript
4,252
star
7

proposal-signals

A proposal to add signals to JavaScript.
3,387
star
8

proposal-temporal

Provides standard objects and functions for working with dates and times.
HTML
3,321
star
9

proposal-observable

Observables for ECMAScript
JavaScript
3,058
star
10

proposal-decorators

Decorators for ES6 classes
2,640
star
11

proposal-record-tuple

ECMAScript proposal for the Record and Tuple value types. | Stage 2: it will change!
HTML
2,496
star
12

test262

Official ECMAScript Conformance Test Suite
JavaScript
2,073
star
13

proposal-dynamic-import

import() proposal for JavaScript
HTML
1,863
star
14

proposal-bind-operator

This-Binding Syntax for ECMAScript
1,742
star
15

proposal-class-fields

Orthogonally-informed combination of public and private fields proposals
HTML
1,722
star
16

proposal-async-await

Async/await for ECMAScript
HTML
1,578
star
17

proposal-object-rest-spread

Rest/Spread Properties for ECMAScript
HTML
1,493
star
18

proposal-shadowrealm

ECMAScript Proposal, specs, and reference implementation for Realms
HTML
1,429
star
19

proposal-iterator-helpers

Methods for working with iterators in ECMAScript
HTML
1,307
star
20

proposal-nullish-coalescing

Nullish coalescing proposal x ?? y
HTML
1,232
star
21

proposal-top-level-await

top-level `await` proposal for ECMAScript (stage 4)
HTML
1,083
star
22

proposal-partial-application

Proposal to add partial application to ECMAScript
HTML
1,002
star
23

proposal-do-expressions

Proposal for `do` expressions
HTML
990
star
24

proposal-binary-ast

Binary AST proposal for ECMAScript
961
star
25

agendas

TC39 meeting agendas
JavaScript
952
star
26

proposal-built-in-modules

HTML
891
star
27

proposal-async-iteration

Asynchronous iteration for JavaScript
HTML
857
star
28

proposal-explicit-resource-management

ECMAScript Explicit Resource Management
JavaScript
746
star
29

proposal-set-methods

Proposal for new Set methods in JS
HTML
655
star
30

proposal-string-dedent

TC39 Proposal to remove common leading indentation from multiline template strings
HTML
614
star
31

proposal-operator-overloading

JavaScript
610
star
32

proposal-import-attributes

Proposal for syntax to import ES modules with assertions
HTML
591
star
33

proposal-async-context

Async Context for JavaScript
HTML
587
star
34

proposal-bigint

Arbitrary precision integers in JavaScript
HTML
561
star
35

ecmascript_simd

SIMD numeric type for EcmaScript
JavaScript
540
star
36

ecma402

Status, process, and documents for ECMA 402
HTML
529
star
37

proposal-slice-notation

HTML
523
star
38

proposal-change-array-by-copy

Provides additional methods on Array.prototype and TypedArray.prototype to enable changes on the array by returning a new copy of it with the change.
HTML
511
star
39

notes

TC39 meeting notes
JavaScript
496
star
40

proposal-class-public-fields

Stage 2 proposal for public class fields in ECMAScript
HTML
489
star
41

proposal-iterator.range

A proposal for ECMAScript to add a built-in Iterator.range()
HTML
483
star
42

proposal-decimal

Built-in exact decimal numbers for JavaScript
HTML
477
star
43

proposal-uuid

UUID proposal for ECMAScript (Stage 1)
JavaScript
463
star
44

proposal-module-expressions

HTML
433
star
45

proposal-throw-expressions

Proposal for ECMAScript 'throw' expressions
JavaScript
425
star
46

proposal-UnambiguousJavaScriptGrammar

413
star
47

proposal-weakrefs

WeakRefs
HTML
409
star
48

proposal-array-grouping

A proposal to make grouping of array items easier
HTML
407
star
49

proposal-error-cause

TC39 proposal for accumulating errors
HTML
380
star
50

proposal-cancelable-promises

Former home of the now-withdrawn cancelable promises proposal for JavaScript
Shell
376
star
51

proposal-ecmascript-sharedmem

Shared memory and atomics for ECMAscript
HTML
374
star
52

proposal-module-declarations

JavaScript Module Declarations
HTML
369
star
53

proposal-first-class-protocols

a proposal to bring protocol-based interfaces to ECMAScript users
352
star
54

proposal-relative-indexing-method

A TC39 proposal to add an .at() method to all the basic indexable classes (Array, String, TypedArray)
HTML
351
star
55

proposal-global

ECMAScript Proposal, specs, and reference implementation for `global`
HTML
346
star
56

proposal-private-methods

Private methods and getter/setters for ES6 classes
HTML
345
star
57

proposal-numeric-separator

A proposal to add numeric literal separators in JavaScript.
HTML
330
star
58

proposal-private-fields

A Private Fields Proposal for ECMAScript
HTML
319
star
59

tc39.github.io

Get involved in specifying JavaScript
HTML
318
star
60

proposal-object-from-entries

TC39 proposal for Object.fromEntries
HTML
318
star
61

proposal-promise-allSettled

ECMAScript Proposal, specs, and reference implementation for Promise.allSettled
HTML
314
star
62

proposal-await.ops

Introduce await.all / await.race / await.allSettled / await.any to simplify the usage of Promises
HTML
310
star
63

proposal-regex-escaping

Proposal for investigating RegExp escaping for the ECMAScript standard
JavaScript
309
star
64

proposal-export-default-from

Proposal to add `export v from "mod";` to ECMAScript.
HTML
306
star
65

proposal-logical-assignment

A proposal to combine Logical Operators and Assignment Expressions
HTML
302
star
66

proposal-promise-finally

ECMAScript Proposal, specs, and reference implementation for Promise.prototype.finally
HTML
279
star
67

proposal-json-modules

Proposal to import JSON files as modules
HTML
272
star
68

proposal-asset-references

Proposal to ECMAScript to add first-class location references relative to a module
270
star
69

proposal-cancellation

Proposal for a Cancellation API for ECMAScript
HTML
267
star
70

proposal-promise-with-resolvers

HTML
255
star
71

proposal-string-replaceall

ECMAScript proposal: String.prototype.replaceAll
HTML
253
star
72

proposal-export-ns-from

Proposal to add `export * as ns from "mod";` to ECMAScript.
HTML
242
star
73

proposal-structs

JavaScript Structs: Fixed Layout Objects
230
star
74

proposal-ses

Draft proposal for SES (Secure EcmaScript)
HTML
223
star
75

proposal-intl-relative-time

`Intl.RelativeTimeFormat` specification [draft]
HTML
215
star
76

proposal-json-parse-with-source

Proposal for extending JSON.parse to expose input source text.
HTML
214
star
77

proposal-flatMap

proposal for flatten and flatMap on arrays
HTML
214
star
78

proposal-defer-import-eval

A proposal for introducing a way to defer evaluate of a module
HTML
208
star
79

ecmarkup

An HTML superset/Markdown subset source format for ECMAScript and related specifications
TypeScript
201
star
80

proposal-promise-any

ECMAScript proposal: Promise.any
HTML
200
star
81

proposal-optional-chaining-assignment

`a?.b = c` proposal
186
star
82

proposal-decorators-previous

Decorators for ECMAScript
HTML
184
star
83

proposal-smart-pipelines

Old archived draft proposal for smart pipelines. Go to the new Hack-pipes proposal at js-choi/proposal-hack-pipes.
HTML
181
star
84

proposal-array-from-async

Draft specification for a proposed Array.fromAsync method in JavaScript.
HTML
178
star
85

proposal-upsert

ECMAScript Proposal, specs, and reference implementation for Map.prototype.upsert
HTML
176
star
86

proposal-collection-methods

HTML
171
star
87

proposal-array-filtering

A proposal to make filtering arrays easier
HTML
171
star
88

proposal-ptc-syntax

Discussion and specification for an explicit syntactic opt-in for Tail Calls.
HTML
169
star
89

proposal-error-stacks

ECMAScript Proposal, specs, and reference implementation for Error.prototype.stack / System.getStack
HTML
166
star
90

proposal-intl-duration-format

164
star
91

how-we-work

Documentation of how TC39 operates and how to participate
161
star
92

proposal-Array.prototype.includes

Spec, tests, reference implementation, and docs for ESnext-track Array.prototype.includes
HTML
157
star
93

proposal-promise-try

ECMAScript Proposal, specs, and reference implementation for Promise.try
HTML
154
star
94

proposal-extensions

Extensions proposal for ECMAScript
HTML
150
star
95

proposal-hashbang

#! for JS
HTML
148
star
96

proposal-import-meta

import.meta proposal for JavaScript
HTML
146
star
97

proposal-intl-segmenter

Unicode text segmentation for ECMAScript
HTML
146
star
98

proposal-resizablearraybuffer

Proposal for resizable array buffers
HTML
145
star
99

proposal-seeded-random

Proposal for an options argument to be added to JS's Math.random() function, and some options to start it with.
HTML
143
star
100

eshost

A uniform wrapper around a multitude of ECMAScript hosts. CLI: https://github.com/bterlson/eshost-cli
JavaScript
142
star