Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(ssr): add back references to esTemplate and infer types #4660

Merged
merged 30 commits into from
Oct 21, 2024

Conversation

wjhsf
Copy link
Contributor

@wjhsf wjhsf commented Oct 18, 2024

Before:

const bYieldEscapedString = esTemplateWithYield<
    EsStatement[],
    [
        EsIdentifier,
        EsExpression,
        EsIdentifier,
        EsLiteral,
        EsIdentifier,
        EsIdentifier,
        EsIdentifier,
        EsIdentifier,
        EsIdentifier,
    ]
>`
    const ${is.identifier} = ${is.expression};
    if (typeof ${is.identifier} === 'string') {
        yield (${is.literal} && ${is.identifier} === '') ? '\\u200D' : htmlEscape(${is.identifier});
    } else if (typeof ${is.identifier} === 'number') {
        yield ${is.identifier}.toString();
    } else {
        yield htmlEscape((${is.identifier} ?? '').toString());
    }
`;

const ast = bYieldEscapedString(
    tempVariable,
    valueToYield,
    tempVariable,
    isIsolatedTextNode,
    tempVariable,
    tempVariable,
    tempVariable,
    tempVariable,
    tempVariable
);

After:

const bYieldEscapedString = esTemplateWithYield`
    const ${is.identifier} = ${is.expression};
    if (typeof ${0} === 'string') {
        yield (${is.literal} && ${0} === '') ? '\\u200D' : htmlEscape(${0});
    } else if (typeof ${0} === 'number') {
        yield ${0}.toString();
    } else {
        yield ${0} ? htmlEscape(${0}.toString()) : '\\u200D';
    }
`<EsStatement[]>;

const ast = bYieldEscapedString(
    tempVariable,
    valueToYield,
    isIsolatedTextNode
);

Details

esTemplate is a template tag that can be applied to a string containing JavaScript code, and it returns a function that generates the estree AST for that code. "Holes" can be introduced into the AST by providing node validators as expressions in the template string (e.g. ${is.identifier}, above). When a hole is introduced, it is filled by a parameter passed to the generated template function (e.g. providing tempVariable to bYieldEscapedString, above). The generated function pairs parameters to validators, to ensure that a valid AST is generated. The type signature of the generated function matches the types validated by each validator. The return type is a generic parameter that must be provided explicitly, because TypeScript has no way of knowing what it should be.

With the current implementation, you must provide a parameter once for every hole, even if the value is used more than once (e.g .tempVariable, above). This PR introduces the concept of back references; a hole can now be filled by either a validator or a number. If a validator is provided, that validator corresponds to a parameter in the generated function. If a number is provided, the parameter from the specified index is re-used. In the example above, ${0} is used multiple times to indicate that value from tempVariable should be inserted at multiple points. This reduces the number of parameters required by the function from 9 to 3.

Additionally, in the current implementation, the requirement that the return type is provided as an explicit generic parameter means that the generated function arguments must also be explicitly stated. (Type inference for generic parameters is all or nothing -- it can't infer just one.) However, because esTemplate is a function that returns a function, I've split the two generic parameters and moved the generic for the return type to the generated function. As a result, the generated function arguments can now be inferred! An interesting quirk of doing this is that the generic comes at the end of the statement, rather than the start (e.g .esTemplate`() => {}`<ArrowFunctionExpression>). The astute may note that this is technically not correct, because the return type is determined by the parameters of esTemplate, rather than the parameters of the generated function. I think that it's a fine trade off, though, given our controlled usage.

Does this pull request introduce a breaking change?

  • 😮‍💨 No, it does not introduce a breaking change.

Does this pull request introduce an observable change?

  • 🤞 No, it does not introduce an observable change.

GUS work item

@wjhsf wjhsf requested a review from a team as a code owner October 18, 2024 17:05
Comment on lines 43 to 58
type ToReplacementParameters<Arr extends unknown[]> = Arr extends [infer Head, ...infer Rest]
? // `Checker` is estree's validator type, and has overloads that mess with inferencing
Head extends Checker<infer C>
? [C | C[], ...ToReplacementParameters<Rest>]
: Head extends Validator<infer V>
? // If it's a validator, extract the validated type
null extends V
? // Avoid `(V | null)[]` if it's nullable
[V | (V & {})[], ...ToReplacementParameters<Rest>]
: [V | V[], ...ToReplacementParameters<Rest>]
: Head extends typeof NO_VALIDATION
? // If it's NO_VALIDATION, use `unknown`
[unknown, ...ToReplacementParameters<Rest>]
: // If it's a back ref, just drop it
ToReplacementParameters<Rest>
: [];
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This type does a lot of heavy lifting! To perform array operations (map/filter/etc.) in TypeScript, you have to resort to recursion. The general pattern looks like this:

// T -> Whatever
type ChangeValue<T> = Whatever

// T[] -> Whatever[]
type ChangeArray<Arr extends unknown[]> = Arr extends [infer Head, ...infer Rest]
  // If the array has one or more items, change the first, then recursively change the rest
  ? [ChangeValue<Head>, ...ChangeArray<Rest>]
  // The array is already empty -- don't need to do anything
  : []

// Filter values not assignable to `BaseType`
type FilterArray<Arr extends unknown[], BaseType> = Arr extends [infer Head, ...infer Rest]
  ? Head extends Basetype
    ? [Head, ...FilterArray<Rest>] // keep the value
    : FilterArray<Rest> // ditch the value
  : [] // array is already empty

Within that pattern, we use the infer keyword to extract the validated types from the validators. For example:

type PromiseValue<P extends Promise<any>> = P extends Promise<infer T> ? T : never
type PromisedAbc = Promise<'abc'>
type Abc = PromiseValue<PromisedAbc> // 'abc'

Sprinkle a few edge cases into the mix (as described in code comments), and you get this delightful monstrosity!

Copy link
Collaborator

@nolanlawson nolanlawson left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not going to pretend to understand the TypeScript gymnastics, but I like the backreferences! Amazing work.

packages/@lwc/ssr-compiler/src/__tests__/fixtures.spec.ts Outdated Show resolved Hide resolved
packages/@lwc/ssr-compiler/src/compile-template/index.ts Outdated Show resolved Hide resolved
packages/@lwc/ssr-compiler/src/compile-template/index.ts Outdated Show resolved Hide resolved
packages/@lwc/ssr-compiler/src/compile-template/index.ts Outdated Show resolved Hide resolved
packages/@lwc/ssr-compiler/src/estemplate.ts Outdated Show resolved Hide resolved
packages/@lwc/ssr-compiler/src/estree/validators.ts Outdated Show resolved Hide resolved
Comment on lines +39 to +65
/** Extracts the type being validated from the validator function. */
type ValidatedType<T> =
T extends Validator<infer V>
? // estree's `Checker<T>` satisfies our `Validator<T>`, but has an extra overload that
// messes with the inferred type `V`, so we must check `Checker` explicitly
T extends Checker<infer C>
? // estree validator
C | C[]
: // custom validator
V | Array<NonNullable<V>> // avoid invalid `Array<V | null>`
: T extends typeof NO_VALIDATION
? // no validation = broadest type possible
EsNode | EsNode[] | null
: // not a validator!
never;

/**
* Converts the validators and refs used in the template to the list of parameters required by the
* created template function. Removes back references to previous slots from the list.
*/
type ToReplacementParameters<Arr extends unknown[]> = Arr extends [infer Head, ...infer Rest]
? Head extends number
? // `Head` is a back reference, drop it from the parameter list
ToReplacementParameters<Rest>
: // `Head` is a validator, extract the type that it validates
[ValidatedType<Head>, ...ToReplacementParameters<Rest>]
: []; // `Arr` is an empty array -- nothing to transform
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nolanlawson cleaned this up a bit!

@wjhsf wjhsf merged commit 7802e27 into master Oct 21, 2024
11 checks passed
@wjhsf wjhsf deleted the wjh/ssr-edge branch October 21, 2024 18:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants