@barefootjs/jsx 0.39.6 → 0.39.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/attr-plan.d.ts +8 -1
- package/dist/adapters/attr-plan.d.ts.map +1 -1
- package/dist/adapters/callback-method.d.ts +44 -0
- package/dist/adapters/callback-method.d.ts.map +1 -1
- package/dist/adapters/component-props.d.ts +80 -13
- package/dist/adapters/component-props.d.ts.map +1 -1
- package/dist/adapters/computed-const.d.ts +52 -0
- package/dist/adapters/computed-const.d.ts.map +1 -0
- package/dist/adapters/dangerous-inner-html.d.ts +10 -0
- package/dist/adapters/dangerous-inner-html.d.ts.map +1 -1
- package/dist/adapters/dsl-template-adapter.d.ts +151 -0
- package/dist/adapters/dsl-template-adapter.d.ts.map +1 -0
- package/dist/adapters/element-shell.d.ts +44 -0
- package/dist/adapters/element-shell.d.ts.map +1 -0
- package/dist/adapters/interface.d.ts +2 -0
- package/dist/adapters/interface.d.ts.map +1 -1
- package/dist/adapters/jsx-adapter.d.ts +4 -0
- package/dist/adapters/jsx-adapter.d.ts.map +1 -1
- package/dist/adapters/literal-value.d.ts +2 -2
- package/dist/adapters/literal-value.d.ts.map +1 -1
- package/dist/adapters/parsed-expr-emitter.d.ts +27 -0
- package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
- package/dist/adapters/style-object.d.ts +33 -0
- package/dist/adapters/style-object.d.ts.map +1 -0
- package/dist/analyzer.d.ts.map +1 -1
- package/dist/augment-inherited-props.d.ts +7 -0
- package/dist/augment-inherited-props.d.ts.map +1 -1
- package/dist/children-nullish.d.ts +22 -0
- package/dist/children-nullish.d.ts.map +1 -0
- package/dist/errors.d.ts +1 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/expression-parser.d.ts +9 -19
- package/dist/expression-parser.d.ts.map +1 -1
- package/dist/fold-render-reassignments.d.ts +43 -0
- package/dist/fold-render-reassignments.d.ts.map +1 -0
- package/dist/free-refs.d.ts +15 -0
- package/dist/free-refs.d.ts.map +1 -1
- package/dist/index.d.ts +21 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +24620 -23233
- package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +2 -1
- package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -2
- package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts +10 -9
- package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts.map +1 -1
- package/dist/ir-to-client-js/csr-substitute.d.ts +0 -13
- package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
- package/dist/ir-to-client-js/emit-reactive.d.ts +1 -1
- package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
- package/dist/ir-to-client-js/emit-registration.d.ts +10 -8
- package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
- package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
- package/dist/ir-to-client-js/html-template.d.ts +9 -19
- package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
- package/dist/ir-to-client-js/identifiers.d.ts +6 -8
- package/dist/ir-to-client-js/identifiers.d.ts.map +1 -1
- package/dist/ir-to-client-js/imports.d.ts +23 -2
- package/dist/ir-to-client-js/imports.d.ts.map +1 -1
- package/dist/ir-to-client-js/index.d.ts.map +1 -1
- package/dist/ir-to-client-js/phases/props-extraction.d.ts +3 -2
- package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
- package/dist/ir-to-client-js/plan/declaration-emit.d.ts +5 -0
- package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
- package/dist/ir-to-client-js/prop-handling.d.ts +11 -12
- package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
- package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +1 -1
- package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
- package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
- package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +1 -1
- package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -1
- package/dist/ir-to-client-js/safe-html.d.ts +20 -2
- package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
- package/dist/ir-to-client-js/types.d.ts +3 -3
- package/dist/ir-to-client-js/types.d.ts.map +1 -1
- package/dist/ir-to-client-js/utils.d.ts +15 -11
- package/dist/ir-to-client-js/utils.d.ts.map +1 -1
- package/dist/jsx-to-ir.d.ts.map +1 -1
- package/dist/nullable-signal-attr.d.ts +43 -12
- package/dist/nullable-signal-attr.d.ts.map +1 -1
- package/dist/prop-rewrite.d.ts +18 -0
- package/dist/prop-rewrite.d.ts.map +1 -1
- package/dist/props-binding.d.ts +43 -6
- package/dist/props-binding.d.ts.map +1 -1
- package/dist/relocate.d.ts +16 -0
- package/dist/relocate.d.ts.map +1 -1
- package/dist/scanner/js-scanner.d.ts.map +1 -1
- package/dist/scanner/js-scanner.js +30 -2
- package/dist/signal-prop-name-collision.d.ts +6 -5
- package/dist/signal-prop-name-collision.d.ts.map +1 -1
- package/dist/ssr-defaults.d.ts +28 -0
- package/dist/ssr-defaults.d.ts.map +1 -1
- package/dist/ssr-seed-plan.d.ts +37 -18
- package/dist/ssr-seed-plan.d.ts.map +1 -1
- package/dist/types.d.ts +162 -20
- package/dist/types.d.ts.map +1 -1
- package/dist/value-references.d.ts +21 -0
- package/dist/value-references.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +18 -18
- package/src/__tests__/adapter-output.test.ts +5 -3
- package/src/__tests__/analyzer.test.ts +33 -0
- package/src/__tests__/arithmetic-lowering.test.ts +44 -0
- package/src/__tests__/block-memo-type.test.ts +51 -0
- package/src/__tests__/callback-method.test.ts +75 -0
- package/src/__tests__/children-read.test.ts +226 -0
- package/src/__tests__/client-only-date-lowering.test.ts +2 -2
- package/src/__tests__/client-template-escape-soundness.test.ts +31 -1
- package/src/__tests__/component-props.test.ts +68 -1
- package/src/__tests__/computed-const.test.ts +101 -0
- package/src/__tests__/constant-inlining-tree.test.ts +136 -0
- package/src/__tests__/destructure-default-reads-earlier-param.test.ts +138 -0
- package/src/__tests__/dsl-template-adapter.test.ts +173 -0
- package/src/__tests__/element-shell.test.ts +78 -0
- package/src/__tests__/event-handler-verbatim.test.ts +73 -0
- package/src/__tests__/expression-parser.test.ts +1 -44
- package/src/__tests__/fold-render-reassignments.test.ts +96 -0
- package/src/__tests__/inlinable-local-method-call.test.ts +81 -0
- package/src/__tests__/memo-body-expr.test.ts +120 -0
- package/src/__tests__/nullable-signal-attr.test.ts +67 -3
- package/src/__tests__/prop-handling.test.ts +35 -16
- package/src/__tests__/props-alias-const.test.ts +65 -0
- package/src/__tests__/reference-graph-identifiers.test.ts +161 -0
- package/src/__tests__/runtime-import-detection.test.ts +134 -0
- package/src/__tests__/signal-prop-name-collision.test.ts +30 -0
- package/src/__tests__/signal-prop-seed.test.ts +90 -0
- package/src/__tests__/ssr-defaults.test.ts +19 -1
- package/src/__tests__/ssr-seed-plan.test.ts +173 -1
- package/src/__tests__/static-template-reachability.test.ts +137 -0
- package/src/__tests__/style-object-plan.test.ts +54 -0
- package/src/__tests__/zero-param-helper-inline.test.ts +57 -0
- package/src/adapters/attr-plan.ts +29 -1
- package/src/adapters/callback-method.ts +85 -0
- package/src/adapters/component-props.ts +130 -12
- package/src/adapters/computed-const.ts +185 -0
- package/src/adapters/dangerous-inner-html.ts +33 -0
- package/src/adapters/dsl-template-adapter.ts +248 -0
- package/src/adapters/element-shell.ts +160 -0
- package/src/adapters/interface.ts +8 -0
- package/src/adapters/jsx-adapter.ts +12 -6
- package/src/adapters/literal-value.ts +2 -2
- package/src/adapters/parsed-expr-emitter.ts +34 -0
- package/src/adapters/style-object.ts +61 -0
- package/src/analyzer.ts +382 -94
- package/src/augment-inherited-props.ts +12 -0
- package/src/children-nullish.ts +33 -0
- package/src/debug.ts +2 -2
- package/src/errors.ts +12 -0
- package/src/expression-parser.ts +56 -53
- package/src/fold-render-reassignments.ts +314 -0
- package/src/free-refs.ts +77 -17
- package/src/index.ts +27 -10
- package/src/ir-to-client-js/compute-inlinability.ts +122 -19
- package/src/ir-to-client-js/control-flow/plan/event-collision.ts +2 -1
- package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -2
- package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +3 -2
- package/src/ir-to-client-js/control-flow/stringify/event-listener.ts +13 -12
- package/src/ir-to-client-js/csr-substitute.ts +25 -37
- package/src/ir-to-client-js/emit-reactive.ts +2 -2
- package/src/ir-to-client-js/emit-registration.ts +31 -59
- package/src/ir-to-client-js/generate-init.ts +17 -1
- package/src/ir-to-client-js/html-template.ts +56 -120
- package/src/ir-to-client-js/identifiers.ts +75 -24
- package/src/ir-to-client-js/imports.ts +56 -19
- package/src/ir-to-client-js/index.ts +5 -3
- package/src/ir-to-client-js/init-declarations.ts +1 -1
- package/src/ir-to-client-js/phases/event-handlers.ts +2 -2
- package/src/ir-to-client-js/phases/props-extraction.ts +16 -15
- package/src/ir-to-client-js/plan/build-declaration-emit.ts +26 -52
- package/src/ir-to-client-js/plan/declaration-emit.ts +5 -0
- package/src/ir-to-client-js/prop-handling.ts +13 -54
- package/src/ir-to-client-js/prune-unused-prop-extractions.ts +7 -4
- package/src/ir-to-client-js/reactivity.ts +2 -2
- package/src/ir-to-client-js/rewrite-destructured-props.ts +27 -9
- package/src/ir-to-client-js/safe-html.ts +29 -35
- package/src/ir-to-client-js/stringify/declaration-emit.ts +1 -1
- package/src/ir-to-client-js/types.ts +3 -2
- package/src/ir-to-client-js/utils.ts +13 -26
- package/src/jsx-to-ir.ts +318 -130
- package/src/nullable-signal-attr.ts +156 -37
- package/src/prop-rewrite.ts +41 -0
- package/src/props-binding.ts +117 -7
- package/src/relocate.ts +40 -8
- package/src/scanner/__tests__/js-scanner.test.ts +37 -0
- package/src/scanner/js-scanner.ts +64 -4
- package/src/signal-prop-name-collision.ts +50 -24
- package/src/ssr-defaults.ts +47 -20
- package/src/ssr-seed-plan.ts +121 -29
- package/src/types.ts +165 -21
- package/src/value-references.ts +132 -0
|
@@ -90,6 +90,18 @@ export function collectContextConsumers(metadata: IRMetadata): ContextConsumer[]
|
|
|
90
90
|
return consumers
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
+
/**
|
|
94
|
+
* The SSR seed of a component's context consumers: one `line` per consumer,
|
|
95
|
+
* each binding the local to the active provider value (or the
|
|
96
|
+
* `createContext` default), newline-terminated; `''` when it consumes no
|
|
97
|
+
* context (#1297).
|
|
98
|
+
*/
|
|
99
|
+
export function contextConsumerSeed(metadata: IRMetadata, line: (consumer: ContextConsumer) => string): string {
|
|
100
|
+
const consumers = collectContextConsumers(metadata)
|
|
101
|
+
if (consumers.length === 0) return ''
|
|
102
|
+
return consumers.map(line).join('\n') + '\n'
|
|
103
|
+
}
|
|
104
|
+
|
|
93
105
|
/** Parse `useContext(Ident)` → `Ident`, else `null`. */
|
|
94
106
|
function parseUseContextArg(source: string): string | null {
|
|
95
107
|
const expr = parseSingleExpression(source)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The parts of a `??` / `||` read of the children prop, shared by the Phase 1
|
|
3
|
+
* classifier (`IRExpression.childrenRead`, #3539, #3554) and the emitters
|
|
4
|
+
* that splice the children markup and escape only the fallback.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { ParsedExpr } from './expression-parser.ts'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Split a left-nested chain of one fallback operator (`??` or `||`) into the
|
|
11
|
+
* value it reads first and the fallback taken when that value is nullish
|
|
12
|
+
* (`??`) or falsy (`||`): `(c ?? x) ?? y` reads `c`, else `x ?? y`, the same
|
|
13
|
+
* as `c ?? (x ?? y)`. `null` when `parsed` is not a `op` chain.
|
|
14
|
+
*/
|
|
15
|
+
export function fallbackChainParts(
|
|
16
|
+
parsed: ParsedExpr,
|
|
17
|
+
op: '??' | '||',
|
|
18
|
+
): { head: ParsedExpr; fallback: ParsedExpr } | null {
|
|
19
|
+
if (parsed.kind !== 'logical' || parsed.op !== op) return null
|
|
20
|
+
const fallbacks: ParsedExpr[] = []
|
|
21
|
+
let head: ParsedExpr = parsed
|
|
22
|
+
while (head.kind === 'logical' && head.op === op) {
|
|
23
|
+
fallbacks.unshift(head.right)
|
|
24
|
+
head = head.left
|
|
25
|
+
}
|
|
26
|
+
const fallback = fallbacks.reduceRight((right, left) => ({ kind: 'logical', op, left, right }))
|
|
27
|
+
return { head, fallback }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** {@link fallbackChainParts} of a `??` chain. */
|
|
31
|
+
export function nullishChainParts(parsed: ParsedExpr): { head: ParsedExpr; fallback: ParsedExpr } | null {
|
|
32
|
+
return fallbackChainParts(parsed, '??')
|
|
33
|
+
}
|
package/src/debug.ts
CHANGED
|
@@ -23,7 +23,7 @@ import type {
|
|
|
23
23
|
SourceLocation,
|
|
24
24
|
OriginInfo,
|
|
25
25
|
} from './types.ts'
|
|
26
|
-
import { isElidedFactoryGetter } from './types.ts'
|
|
26
|
+
import { isElidedFactoryGetter, isChildrenPropParam } from './types.ts'
|
|
27
27
|
import { analyzeComponent, listComponentFunctions } from './analyzer.ts'
|
|
28
28
|
import { jsxToIR } from './jsx-to-ir.ts'
|
|
29
29
|
import { buildMetadata } from './compiler.ts'
|
|
@@ -411,7 +411,7 @@ export function buildGraphFromIR(ir: ComponentIR): ComponentGraph {
|
|
|
411
411
|
// `reactive: true` (#2903). The collector therefore returns the prop NAMES
|
|
412
412
|
// (not a boolean), so a prop read lands in `DomBinding.deps` on the same
|
|
413
413
|
// footing as a signal or memo read.
|
|
414
|
-
const destructuredPropNames = new Set(meta.propsParams.
|
|
414
|
+
const destructuredPropNames = new Set(meta.propsParams.filter(p => !isChildrenPropParam(p)).map(p => p.name))
|
|
415
415
|
const propsObjectName = meta.propsObjectName
|
|
416
416
|
const propMemberDep = (member: string): string => `${propsObjectName}.${member}`
|
|
417
417
|
|
package/src/errors.ts
CHANGED
|
@@ -127,6 +127,14 @@ export const ErrorCodes = {
|
|
|
127
127
|
// adapter including Hono. See `format-date-refusal.ts`.
|
|
128
128
|
FORMAT_DATE_AUTHORED_CALL: 'BF056',
|
|
129
129
|
|
|
130
|
+
// A module-level declaration or a value import binds the name of a
|
|
131
|
+
// `@barefootjs/client/runtime` helper (`insert`, `hydrate`, `qsa`, …) and
|
|
132
|
+
// the compiled client JS calls that name (#3537). The call may be the
|
|
133
|
+
// compiler's own, which the user's binding would capture. Before import
|
|
134
|
+
// detection resolved scopes, this shape emitted the binding next to a
|
|
135
|
+
// runtime import of the same name: a duplicate-declaration SyntaxError.
|
|
136
|
+
RUNTIME_HELPER_NAME_COLLISION: 'BF057',
|
|
137
|
+
|
|
130
138
|
// Init statement errors (BF052)
|
|
131
139
|
UNDECLARED_INIT_STATEMENT_REFERENCE: 'BF052',
|
|
132
140
|
|
|
@@ -281,6 +289,10 @@ const errorMessages: Record<ErrorCode, string> = {
|
|
|
281
289
|
[ErrorCodes.FORMAT_DATE_AUTHORED_CALL]:
|
|
282
290
|
'formatDate cannot be called directly — it is compiler ABI, not an authored API.',
|
|
283
291
|
|
|
292
|
+
[ErrorCodes.RUNTIME_HELPER_NAME_COLLISION]:
|
|
293
|
+
'This module-level name is also a BarefootJS runtime helper, and the compiled client JS calls it. ' +
|
|
294
|
+
'Rename the declaration, or import it under an alias.',
|
|
295
|
+
|
|
284
296
|
[ErrorCodes.BUILTIN_REQUIRES_IMPORT]:
|
|
285
297
|
"Built-in <Async> / <Region> must be imported from '@barefootjs/client'. " +
|
|
286
298
|
'The compiler recognises these tags by their import (not by tag name), ' +
|
package/src/expression-parser.ts
CHANGED
|
@@ -61,8 +61,10 @@ export type ParsedExpr =
|
|
|
61
61
|
// callbacks (`.filter`/`.sort`/`.reduce`/`.flatMap`) arrive as a generic
|
|
62
62
|
// `call` whose argument is this kind; the adapter serializes `body` to the
|
|
63
63
|
// runtime evaluator (#2018). Block bodies with locals / multiple statements,
|
|
64
|
-
// and array-binding-pattern params, stay `unsupported`.
|
|
65
|
-
|
|
64
|
+
// and array-binding-pattern params, stay `unsupported`. `callKind` marks an
|
|
65
|
+
// async arrow / function or a generator function: calling one returns a
|
|
66
|
+
// Promise or an iterator, not `body`'s value (#3562 review).
|
|
67
|
+
| { kind: 'arrow'; params: string[]; body: ParsedExpr; callKind?: 'async' | 'generator' }
|
|
66
68
|
// A regex literal carried as its exact source text (`/\/+$/`), so the Go
|
|
67
69
|
// ctor lowering matches the one trailing-slash-strip pattern it recognises
|
|
68
70
|
// (`String.replace`). Outside that narrow surface a regex resolves to
|
|
@@ -707,10 +709,6 @@ export function parseProviderObjectLiteral(source: string): ProviderObjectMember
|
|
|
707
709
|
* either a static string literal or a raw JS expression for the adapter to
|
|
708
710
|
* lower (`color` → its template interpolation).
|
|
709
711
|
*/
|
|
710
|
-
export type StyleObjectEntry =
|
|
711
|
-
| { cssKey: string; kind: 'literal'; value: string }
|
|
712
|
-
| { cssKey: string; kind: 'expr'; expr: string }
|
|
713
|
-
|
|
714
712
|
/** camelCase → kebab-case for CSS property names (`backgroundColor` →
|
|
715
713
|
* `background-color`, `WebkitTransform` → `-webkit-transform`). The `ms`
|
|
716
714
|
* vendor prefix is lowercase in React style keys (`msTransform`) yet the CSS
|
|
@@ -772,40 +770,6 @@ export function hasUnsafeStyleValue(value: string): boolean {
|
|
|
772
770
|
return quote !== 0 || blockStack.length !== 0 // unterminated quote/bracket
|
|
773
771
|
}
|
|
774
772
|
|
|
775
|
-
/**
|
|
776
|
-
* Parse a JSX `style={{ … }}` object-literal source into CSS entries, or
|
|
777
|
-
* `null` when the shape isn't a plain object of static-keyed properties
|
|
778
|
-
* (spread, computed key, shorthand, method, getter) — the adapter then keeps
|
|
779
|
-
* refusing it. A bare `{…}` parses as a block statement, so the source is
|
|
780
|
-
* wrapped in parens to force expression context. Used by the template adapters
|
|
781
|
-
* to lower `style={{ backgroundColor: color, padding: '8px' }}` to a CSS
|
|
782
|
-
* string instead of emitting BF101.
|
|
783
|
-
*/
|
|
784
|
-
export function parseStyleObjectEntries(source: string): StyleObjectEntry[] | null {
|
|
785
|
-
const sf = ts.createSourceFile('__style__.ts', `(${source})`, ts.ScriptTarget.Latest, true)
|
|
786
|
-
const stmt = sf.statements[0]
|
|
787
|
-
if (!stmt || !ts.isExpressionStatement(stmt) || sf.statements.length !== 1) return null
|
|
788
|
-
let expr: ts.Expression = stmt.expression
|
|
789
|
-
while (ts.isParenthesizedExpression(expr)) expr = expr.expression
|
|
790
|
-
if (!ts.isObjectLiteralExpression(expr)) return null
|
|
791
|
-
const entries: StyleObjectEntry[] = []
|
|
792
|
-
for (const prop of expr.properties) {
|
|
793
|
-
if (!ts.isPropertyAssignment(prop)) return null // shorthand/spread/method/getter
|
|
794
|
-
let key: string
|
|
795
|
-
if (ts.isIdentifier(prop.name)) key = prop.name.text
|
|
796
|
-
else if (ts.isStringLiteral(prop.name)) key = prop.name.text
|
|
797
|
-
else return null // computed / numeric key
|
|
798
|
-
const cssKey = cssKebabCase(key)
|
|
799
|
-
const init = prop.initializer
|
|
800
|
-
if (ts.isStringLiteral(init) || ts.isNoSubstitutionTemplateLiteral(init)) {
|
|
801
|
-
entries.push({ cssKey, kind: 'literal', value: init.text })
|
|
802
|
-
} else {
|
|
803
|
-
entries.push({ cssKey, kind: 'expr', expr: init.getText(sf).trim() })
|
|
804
|
-
}
|
|
805
|
-
}
|
|
806
|
-
return entries.length > 0 ? entries : null
|
|
807
|
-
}
|
|
808
|
-
|
|
809
773
|
/**
|
|
810
774
|
* Parse a JavaScript expression string into a ParsedExpr tree.
|
|
811
775
|
*/
|
|
@@ -1159,6 +1123,7 @@ function convertNode(node: ts.Node, raw: string): ParsedExpr {
|
|
|
1159
1123
|
// a generic `call` whose argument is this kind; the adapter serializes
|
|
1160
1124
|
// `body` to the runtime evaluator.
|
|
1161
1125
|
if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
|
|
1126
|
+
const callKind = arrowCallKind(node)
|
|
1162
1127
|
// Resolve the body expression: an expression-bodied arrow carries it
|
|
1163
1128
|
// directly; a block body (arrow `=> { … }` or a function expression)
|
|
1164
1129
|
// must reduce to exactly one `return <expr>;`. Multi-statement /
|
|
@@ -1287,7 +1252,7 @@ function convertNode(node: ts.Node, raw: string): ParsedExpr {
|
|
|
1287
1252
|
}
|
|
1288
1253
|
const syntheticParam = pickSyntheticParam(fieldMap, body)
|
|
1289
1254
|
const rewritten = substituteDestructuredFields(body, fieldMap, syntheticParam, restName)
|
|
1290
|
-
return { kind: 'arrow', params: [syntheticParam], body: rewritten }
|
|
1255
|
+
return { kind: 'arrow', params: [syntheticParam], body: rewritten, ...callKind }
|
|
1291
1256
|
}
|
|
1292
1257
|
|
|
1293
1258
|
// Every (remaining) parameter must be a plain identifier. Multi-param
|
|
@@ -1300,7 +1265,7 @@ function convertNode(node: ts.Node, raw: string): ParsedExpr {
|
|
|
1300
1265
|
}
|
|
1301
1266
|
params.push(p.name.text)
|
|
1302
1267
|
}
|
|
1303
|
-
return { kind: 'arrow', params, body }
|
|
1268
|
+
return { kind: 'arrow', params, body, ...callKind }
|
|
1304
1269
|
}
|
|
1305
1270
|
|
|
1306
1271
|
// Default: unsupported
|
|
@@ -2961,6 +2926,30 @@ function usesPerPath(name: string, expr: ParsedExpr): { min: number; max: number
|
|
|
2961
2926
|
return walk(expr)
|
|
2962
2927
|
}
|
|
2963
2928
|
|
|
2929
|
+
/** `{ callKind }` for an async or generator function, else nothing (see the `arrow` kind). */
|
|
2930
|
+
function arrowCallKind(node: ts.ArrowFunction | ts.FunctionExpression): { callKind?: 'async' | 'generator' } {
|
|
2931
|
+
if (ts.isFunctionExpression(node) && node.asteriskToken) return { callKind: 'generator' }
|
|
2932
|
+
if (node.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword)) return { callKind: 'async' }
|
|
2933
|
+
return {}
|
|
2934
|
+
}
|
|
2935
|
+
|
|
2936
|
+
/**
|
|
2937
|
+
* The value a call of `value` with no arguments evaluates to, when that is
|
|
2938
|
+
* just its body: a zero-param, synchronous, non-generator arrow whose body
|
|
2939
|
+
* is a pure value expression. Null otherwise (an async call returns a
|
|
2940
|
+
* Promise, a generator an iterator, and a body that mutates state, like
|
|
2941
|
+
* `++nextId`, must run where it is declared).
|
|
2942
|
+
*/
|
|
2943
|
+
export function zeroArgCallBody(value: ParsedExpr): ParsedExpr | null {
|
|
2944
|
+
if (value.kind !== 'arrow' || value.params.length !== 0 || value.callKind) return null
|
|
2945
|
+
return isSupportedValue(value.body).supported ? value.body : null
|
|
2946
|
+
}
|
|
2947
|
+
|
|
2948
|
+
/** `name()` with no arguments, where `name` is not shadowed by an enclosing param. */
|
|
2949
|
+
function isBareCallOf(e: Extract<ParsedExpr, { kind: 'call' }>, name: string, enclosing: ReadonlySet<string>): boolean {
|
|
2950
|
+
return e.args.length === 0 && e.callee.kind === 'identifier' && e.callee.name === name && !enclosing.has(name)
|
|
2951
|
+
}
|
|
2952
|
+
|
|
2964
2953
|
/**
|
|
2965
2954
|
* Inline `name → value` everywhere it appears free in `expr` (the let-inline
|
|
2966
2955
|
* step). Returns `null` if the substitution would capture a free variable of
|
|
@@ -2989,6 +2978,27 @@ export function inlineBinding(
|
|
|
2989
2978
|
const valueFree = new Set<string>()
|
|
2990
2979
|
collectIdentifiers(value, valueFree)
|
|
2991
2980
|
let captured = false
|
|
2981
|
+
// A zero-param arrow (`const isWide = () => props.mode === 'wide'`) called
|
|
2982
|
+
// with no arguments inlines as its body, so `isWide()` reads what the call
|
|
2983
|
+
// returns (#3562; `zeroArgCallBody` says which arrows qualify). Calling it
|
|
2984
|
+
// evaluates the body in the same scope the substitution resolves it in;
|
|
2985
|
+
// the capture check covers the body's free variables, which are `value`'s.
|
|
2986
|
+
const callBody = zeroArgCallBody(value)
|
|
2987
|
+
// Inlining here: does any enclosing param capture a free var of `value`?
|
|
2988
|
+
const capturesValueFree = (enclosing: ReadonlySet<string>): boolean => {
|
|
2989
|
+
for (const p of enclosing) {
|
|
2990
|
+
if (valueFree.has(p)) {
|
|
2991
|
+
captured = true
|
|
2992
|
+
return true
|
|
2993
|
+
}
|
|
2994
|
+
}
|
|
2995
|
+
return false
|
|
2996
|
+
}
|
|
2997
|
+
|
|
2998
|
+
const walkCall = (e: Extract<ParsedExpr, { kind: 'call' }>, enclosing: ReadonlySet<string>): ParsedExpr => {
|
|
2999
|
+
if (callBody && isBareCallOf(e, name, enclosing)) return capturesValueFree(enclosing) ? e : callBody
|
|
3000
|
+
return { kind: 'call', callee: walk(e.callee, enclosing), args: e.args.map(a => walk(a, enclosing)) }
|
|
3001
|
+
}
|
|
2992
3002
|
|
|
2993
3003
|
const walk = (e: ParsedExpr, enclosing: ReadonlySet<string>): ParsedExpr => {
|
|
2994
3004
|
switch (e.kind) {
|
|
@@ -2997,17 +3007,10 @@ export function inlineBinding(
|
|
|
2997
3007
|
// Shadowed by an enclosing callback param → this is the parameter, not
|
|
2998
3008
|
// the binding; leave it.
|
|
2999
3009
|
if (enclosing.has(e.name)) return e
|
|
3000
|
-
|
|
3001
|
-
for (const p of enclosing) {
|
|
3002
|
-
if (valueFree.has(p)) {
|
|
3003
|
-
captured = true
|
|
3004
|
-
return e
|
|
3005
|
-
}
|
|
3006
|
-
}
|
|
3007
|
-
return value
|
|
3010
|
+
return capturesValueFree(enclosing) ? e : value
|
|
3008
3011
|
}
|
|
3009
3012
|
case 'call':
|
|
3010
|
-
return
|
|
3013
|
+
return walkCall(e, enclosing)
|
|
3011
3014
|
case 'member':
|
|
3012
3015
|
return { kind: 'member', object: walk(e.object, enclosing), property: e.property, computed: e.computed, optional: e.optional }
|
|
3013
3016
|
case 'index-access':
|
|
@@ -3029,7 +3032,7 @@ export function inlineBinding(
|
|
|
3029
3032
|
}
|
|
3030
3033
|
case 'arrow': {
|
|
3031
3034
|
const innerEnclosing = e.params.length === 0 ? enclosing : new Set([...enclosing, ...e.params])
|
|
3032
|
-
return {
|
|
3035
|
+
return { ...e, body: walk(e.body, innerEnclosing) }
|
|
3033
3036
|
}
|
|
3034
3037
|
case 'array-literal':
|
|
3035
3038
|
return { kind: 'array-literal', elements: e.elements.map(el => walk(el, enclosing)) }
|
|
@@ -3425,7 +3428,7 @@ export function materializeGetterCalls(expr: ParsedExpr, names: ReadonlySet<stri
|
|
|
3425
3428
|
properties: expr.properties.map(p => (p.kind === 'spread' ? { ...p, expr: rw(p.expr) } : { ...p, value: rw(p.value) })),
|
|
3426
3429
|
}
|
|
3427
3430
|
case 'arrow':
|
|
3428
|
-
return {
|
|
3431
|
+
return { ...expr, body: rw(expr.body) }
|
|
3429
3432
|
// Leaves / opaque shapes — nothing to rewrite.
|
|
3430
3433
|
case 'identifier':
|
|
3431
3434
|
case 'literal':
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fold render-time reassignments of a component-scope `let` into its
|
|
3
|
+
* initializer (#3501).
|
|
4
|
+
*
|
|
5
|
+
* A template evaluates a binding's value, never the statements that follow
|
|
6
|
+
* its declaration, so a `let` reassigned before the component returns had
|
|
7
|
+
* no value a template could read:
|
|
8
|
+
*
|
|
9
|
+
* let label = props.label ?? 'Default'
|
|
10
|
+
* if (!label) label = 'Fallback'
|
|
11
|
+
*
|
|
12
|
+
* This pre-pass rewrites that to the single value the binding holds at
|
|
13
|
+
* render time, binding each intermediate value once, and removes the
|
|
14
|
+
* reassigning statements:
|
|
15
|
+
*
|
|
16
|
+
* const label_1 = props.label ?? 'Default'; let label = ((!(label_1)) ? ('Fallback') : (label_1))
|
|
17
|
+
*
|
|
18
|
+
* Every later stage (the analyzer, the CSR template, the template adapters,
|
|
19
|
+
* the client init body) then sees ordinary bindings with one value each, so
|
|
20
|
+
* they agree by construction.
|
|
21
|
+
*
|
|
22
|
+
* The rewrite only applies where it cannot change behaviour:
|
|
23
|
+
* - the reassigning statements directly follow the declaration, and each
|
|
24
|
+
* is an assignment to the binding (`x = e`, `x += e`, `x ??= e`, …), an
|
|
25
|
+
* `if`/`else` whose branches are such assignments, or a block of them;
|
|
26
|
+
* - the initializer, every assigned value and every condition is free of
|
|
27
|
+
* side effects (no calls, no assignments, no functions);
|
|
28
|
+
* - every expression is evaluated exactly as often, and in the same order,
|
|
29
|
+
* as the original statements evaluate it, since a member read may run a
|
|
30
|
+
* getter. Each statement's incoming value is a binding (a read of it is
|
|
31
|
+
* unobservable) or a literal, a conditional evaluates only the branch it
|
|
32
|
+
* takes, and inside a statement a computed value may only flow into a
|
|
33
|
+
* compound assignment (see `foldStatement`).
|
|
34
|
+
* Anything else leaves the binding as it is (and `markMutatedConstants`
|
|
35
|
+
* flags it as before).
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
import ts from 'typescript'
|
|
39
|
+
|
|
40
|
+
/** Folded values longer than this are left unfolded. */
|
|
41
|
+
const MAX_FOLDED_LENGTH = 4000
|
|
42
|
+
|
|
43
|
+
interface Edit {
|
|
44
|
+
start: number
|
|
45
|
+
end: number
|
|
46
|
+
text: string
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The source with each foldable `let` folded, or `null` when nothing was
|
|
51
|
+
* folded. Line count is preserved where possible (removed statements are
|
|
52
|
+
* blanked rather than deleted), so later source locations stay valid.
|
|
53
|
+
*/
|
|
54
|
+
export function foldRenderReassignmentsInSource(source: string, filePath: string): string | null {
|
|
55
|
+
if (!source.includes('let ')) return null
|
|
56
|
+
const sf = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)
|
|
57
|
+
const edits: Edit[] = []
|
|
58
|
+
const names = new FreshNames(sf)
|
|
59
|
+
for (const body of topLevelFunctionBodies(sf)) foldBlock(body.statements, sf, names, edits)
|
|
60
|
+
if (edits.length === 0) return null
|
|
61
|
+
edits.sort((a, b) => b.start - a.start)
|
|
62
|
+
let out = source
|
|
63
|
+
for (const e of edits) out = out.slice(0, e.start) + e.text + out.slice(e.end)
|
|
64
|
+
return out
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function topLevelFunctionBodies(sf: ts.SourceFile): ts.Block[] {
|
|
68
|
+
const bodies: ts.Block[] = []
|
|
69
|
+
const add = (fn: ts.Node | undefined) => {
|
|
70
|
+
if (fn && (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) && fn.body && ts.isBlock(fn.body)) bodies.push(fn.body)
|
|
71
|
+
}
|
|
72
|
+
for (const stmt of sf.statements) {
|
|
73
|
+
if (ts.isFunctionDeclaration(stmt) && stmt.body) bodies.push(stmt.body)
|
|
74
|
+
else if (ts.isVariableStatement(stmt)) for (const d of stmt.declarationList.declarations) add(d.initializer)
|
|
75
|
+
else if (ts.isExportAssignment(stmt)) add(stmt.expression)
|
|
76
|
+
}
|
|
77
|
+
return bodies
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Identifiers not yet used anywhere in the file, for the intermediate bindings. */
|
|
81
|
+
class FreshNames {
|
|
82
|
+
private readonly used = new Set<string>()
|
|
83
|
+
constructor(sf: ts.SourceFile) {
|
|
84
|
+
const visit = (node: ts.Node): void => {
|
|
85
|
+
if (ts.isIdentifier(node)) this.used.add(node.text)
|
|
86
|
+
ts.forEachChild(node, visit)
|
|
87
|
+
}
|
|
88
|
+
visit(sf)
|
|
89
|
+
}
|
|
90
|
+
next(base: string): string {
|
|
91
|
+
let k = 1
|
|
92
|
+
while (this.used.has(`${base}_${k}`)) k++
|
|
93
|
+
const name = `${base}_${k}`
|
|
94
|
+
this.used.add(name)
|
|
95
|
+
return name
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A value: its source text, and whether it is a literal or a plain identifier, which may be repeated freely. */
|
|
100
|
+
interface Value {
|
|
101
|
+
text: string
|
|
102
|
+
trivial: boolean
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function foldBlock(statements: ts.NodeArray<ts.Statement>, sf: ts.SourceFile, names: FreshNames, edits: Edit[]): void {
|
|
106
|
+
for (let i = 0; i < statements.length; i++) {
|
|
107
|
+
const decl = foldableLet(statements[i]!)
|
|
108
|
+
if (!decl) continue
|
|
109
|
+
const name = decl.name.text
|
|
110
|
+
// `value` is the binding's value so far. Each statement reads it through
|
|
111
|
+
// a binding of its own (or directly, when it is a literal or identifier),
|
|
112
|
+
// so its expression is evaluated once, where the original evaluated it.
|
|
113
|
+
let value: Value = { text: decl.initializer.getText(sf), trivial: isTrivial(decl.initializer) }
|
|
114
|
+
const bindings: string[] = []
|
|
115
|
+
let last = i
|
|
116
|
+
for (let j = i + 1; j < statements.length; j++) {
|
|
117
|
+
const ref = value.trivial ? value.text : names.next(name)
|
|
118
|
+
const next = foldStatement(statements[j]!, name, { text: ref, trivial: true }, sf)
|
|
119
|
+
if (next === null || next.text.length > MAX_FOLDED_LENGTH) break
|
|
120
|
+
if (!value.trivial) bindings.push(`const ${ref} = ${value.text}; `)
|
|
121
|
+
value = next
|
|
122
|
+
last = j
|
|
123
|
+
}
|
|
124
|
+
if (last === i) continue
|
|
125
|
+
const stmt = statements[i]!
|
|
126
|
+
const initText = decl.initializer.getText(sf)
|
|
127
|
+
const prefix = bindings.join('')
|
|
128
|
+
edits.push({ start: stmt.getStart(sf), end: stmt.getStart(sf), text: prefix })
|
|
129
|
+
edits.push({ start: decl.initializer.getStart(sf), end: decl.initializer.getEnd(), text: value.text })
|
|
130
|
+
const surplus = countNewlines(prefix) + countNewlines(value.text) - countNewlines(initText)
|
|
131
|
+
edits.push(...blankStatements(statements.slice(i + 1, last + 1), sf, surplus))
|
|
132
|
+
i = last
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function isTrivial(expr: ts.Expression): boolean {
|
|
137
|
+
return PURE_LEAF_KINDS.has(skipParens(expr).kind)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** `let x = <pure initializer>` with a single identifier binding. */
|
|
141
|
+
function foldableLet(stmt: ts.Statement): (ts.VariableDeclaration & { name: ts.Identifier; initializer: ts.Expression }) | null {
|
|
142
|
+
if (!ts.isVariableStatement(stmt)) return null
|
|
143
|
+
const list = stmt.declarationList
|
|
144
|
+
if (!(list.flags & ts.NodeFlags.Let) || list.declarations.length !== 1) return null
|
|
145
|
+
const d = list.declarations[0]!
|
|
146
|
+
if (!ts.isIdentifier(d.name) || !d.initializer || !isPure(d.initializer)) return null
|
|
147
|
+
return d as ts.VariableDeclaration & { name: ts.Identifier; initializer: ts.Expression }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const COMPOUND_OPERATORS = new Map<ts.SyntaxKind, string>([
|
|
151
|
+
[ts.SyntaxKind.PlusEqualsToken, '+'],
|
|
152
|
+
[ts.SyntaxKind.MinusEqualsToken, '-'],
|
|
153
|
+
[ts.SyntaxKind.AsteriskEqualsToken, '*'],
|
|
154
|
+
[ts.SyntaxKind.SlashEqualsToken, '/'],
|
|
155
|
+
[ts.SyntaxKind.PercentEqualsToken, '%'],
|
|
156
|
+
[ts.SyntaxKind.QuestionQuestionEqualsToken, '??'],
|
|
157
|
+
[ts.SyntaxKind.BarBarEqualsToken, '||'],
|
|
158
|
+
[ts.SyntaxKind.AmpersandAmpersandEqualsToken, '&&'],
|
|
159
|
+
])
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The binding's value after `stmt`, given its value `current` before; `null`
|
|
163
|
+
* when `stmt` is not foldable.
|
|
164
|
+
*
|
|
165
|
+
* A trivial `current` (a binding, a literal) may be read any number of times,
|
|
166
|
+
* or not at all. A computed one (left by an earlier assignment inside the
|
|
167
|
+
* same statement) must be evaluated exactly once and before anything else, as
|
|
168
|
+
* the original evaluated it, so only a compound assignment (`x += e`, whose
|
|
169
|
+
* `e` does not read `x`) or an empty statement may follow it: an overwrite
|
|
170
|
+
* would drop its evaluation, and any other read could repeat or reorder it.
|
|
171
|
+
*/
|
|
172
|
+
function foldStatement(stmt: ts.Statement, name: string, current: Value, sf: ts.SourceFile): Value | null {
|
|
173
|
+
if (ts.isEmptyStatement(stmt)) return current
|
|
174
|
+
if (ts.isBlock(stmt)) return foldSequence(stmt.statements, name, current, sf)
|
|
175
|
+
if (ts.isIfStatement(stmt)) return current.trivial ? foldIf(stmt, name, current, sf) : null
|
|
176
|
+
const assignment = reassignment(stmt, name)
|
|
177
|
+
if (!assignment) return null
|
|
178
|
+
const value = substitute(assignment.right, name, current.text, sf)
|
|
179
|
+
if (assignment.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
|
|
180
|
+
return current.trivial ? { text: value.text, trivial: value.reads === 0 && isTrivial(assignment.right) } : null
|
|
181
|
+
}
|
|
182
|
+
const op = COMPOUND_OPERATORS.get(assignment.operatorToken.kind)
|
|
183
|
+
if (op === undefined || (!current.trivial && value.reads > 0)) return null
|
|
184
|
+
return { text: `((${current.text}) ${op} (${value.text}))`, trivial: false }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** `name = e` / `name op= e` with a side-effect-free `e`, as an expression statement. */
|
|
188
|
+
function reassignment(stmt: ts.Statement, name: string): ts.BinaryExpression | null {
|
|
189
|
+
if (!ts.isExpressionStatement(stmt)) return null
|
|
190
|
+
const expr = skipParens(stmt.expression)
|
|
191
|
+
if (!ts.isBinaryExpression(expr)) return null
|
|
192
|
+
const target = skipParens(expr.left)
|
|
193
|
+
return ts.isIdentifier(target) && target.text === name && isPure(expr.right) ? expr : null
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Statements in order: each reads the value the previous one left. */
|
|
197
|
+
function foldSequence(stmts: readonly ts.Statement[], name: string, current: Value, sf: ts.SourceFile): Value | null {
|
|
198
|
+
let value = current
|
|
199
|
+
for (const s of stmts) {
|
|
200
|
+
const next = foldStatement(s, name, value, sf)
|
|
201
|
+
if (next === null) return null
|
|
202
|
+
value = next
|
|
203
|
+
}
|
|
204
|
+
return value
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** A conditional evaluates its test, then only the branch it takes. `current` is trivial here. */
|
|
208
|
+
function foldIf(stmt: ts.IfStatement, name: string, current: Value, sf: ts.SourceFile): Value | null {
|
|
209
|
+
if (!isPure(stmt.expression)) return null
|
|
210
|
+
const whenTrue = foldStatement(stmt.thenStatement, name, current, sf)
|
|
211
|
+
if (whenTrue === null) return null
|
|
212
|
+
const whenFalse = stmt.elseStatement ? foldStatement(stmt.elseStatement, name, current, sf) : current
|
|
213
|
+
if (whenFalse === null) return null
|
|
214
|
+
const test = substitute(stmt.expression, name, current.text, sf)
|
|
215
|
+
return { text: `((${test.text}) ? (${whenTrue.text}) : (${whenFalse.text}))`, trivial: false }
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** `expr`'s source text with every read of `name` replaced by `(current)`, and how many reads there were. */
|
|
219
|
+
function substitute(expr: ts.Expression, name: string, current: string, sf: ts.SourceFile): { text: string; reads: number } {
|
|
220
|
+
const start = expr.getStart(sf)
|
|
221
|
+
const reads: ts.Identifier[] = []
|
|
222
|
+
const visit = (node: ts.Node): void => {
|
|
223
|
+
if (ts.isTypeNode(node)) return
|
|
224
|
+
if (ts.isIdentifier(node) && node.text === name && !isPropertyName(node)) reads.push(node)
|
|
225
|
+
ts.forEachChild(node, visit)
|
|
226
|
+
}
|
|
227
|
+
visit(expr)
|
|
228
|
+
let out = expr.getText(sf)
|
|
229
|
+
for (const id of [...reads].reverse()) {
|
|
230
|
+
const at = id.getStart(sf) - start
|
|
231
|
+
out = `${out.slice(0, at)}(${current})${out.slice(at + id.text.length)}`
|
|
232
|
+
}
|
|
233
|
+
return { text: out, reads: reads.length }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function isPropertyName(id: ts.Identifier): boolean {
|
|
237
|
+
const p = id.parent
|
|
238
|
+
return ts.isPropertyAccessExpression(p) && p.name === id
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const PURE_LEAF_KINDS: ReadonlySet<ts.SyntaxKind> = new Set([
|
|
242
|
+
ts.SyntaxKind.Identifier,
|
|
243
|
+
ts.SyntaxKind.StringLiteral,
|
|
244
|
+
ts.SyntaxKind.NumericLiteral,
|
|
245
|
+
ts.SyntaxKind.BigIntLiteral,
|
|
246
|
+
ts.SyntaxKind.NoSubstitutionTemplateLiteral,
|
|
247
|
+
ts.SyntaxKind.TrueKeyword,
|
|
248
|
+
ts.SyntaxKind.FalseKeyword,
|
|
249
|
+
ts.SyntaxKind.NullKeyword,
|
|
250
|
+
])
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Whether evaluating `expr` has no side effects and reads nothing a
|
|
254
|
+
* statement between the declaration and the reassignment could change:
|
|
255
|
+
* identifiers, literals, member reads and operators only.
|
|
256
|
+
*/
|
|
257
|
+
function isPure(expr: ts.Expression): boolean {
|
|
258
|
+
const e = skipParens(expr)
|
|
259
|
+
if (PURE_LEAF_KINDS.has(e.kind)) return true
|
|
260
|
+
const operands = pureOperands(e)
|
|
261
|
+
return operands !== null && operands.every(isPure)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** The sub-expressions of a side-effect-free form, or `null` for any other form. */
|
|
265
|
+
function pureOperands(e: ts.Expression): readonly ts.Expression[] | null {
|
|
266
|
+
if (ts.isPropertyAccessExpression(e) || ts.isTypeOfExpression(e)) return [e.expression]
|
|
267
|
+
if (ts.isAsExpression(e) || ts.isNonNullExpression(e) || ts.isSatisfiesExpression(e)) return [e.expression]
|
|
268
|
+
if (ts.isElementAccessExpression(e)) return [e.expression, e.argumentExpression]
|
|
269
|
+
if (ts.isConditionalExpression(e)) return [e.condition, e.whenTrue, e.whenFalse]
|
|
270
|
+
if (ts.isTemplateExpression(e)) return e.templateSpans.map(s => s.expression)
|
|
271
|
+
if (ts.isPrefixUnaryExpression(e)) {
|
|
272
|
+
const sideEffect = e.operator === ts.SyntaxKind.PlusPlusToken || e.operator === ts.SyntaxKind.MinusMinusToken
|
|
273
|
+
return sideEffect ? null : [e.operand]
|
|
274
|
+
}
|
|
275
|
+
if (ts.isBinaryExpression(e)) return isPureOperator(e.operatorToken.kind) ? [e.left, e.right] : null
|
|
276
|
+
return null
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** A binary operator that neither assigns nor sequences. */
|
|
280
|
+
function isPureOperator(op: ts.SyntaxKind): boolean {
|
|
281
|
+
const isAssignment = op >= ts.SyntaxKind.FirstAssignment && op <= ts.SyntaxKind.LastAssignment
|
|
282
|
+
return !isAssignment && op !== ts.SyntaxKind.CommaToken
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function skipParens(expr: ts.Expression): ts.Expression {
|
|
286
|
+
let e = expr
|
|
287
|
+
while (ts.isParenthesizedExpression(e)) e = e.expression
|
|
288
|
+
return e
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function countNewlines(text: string): number {
|
|
292
|
+
let n = 0
|
|
293
|
+
for (const ch of text) if (ch === '\n') n++
|
|
294
|
+
return n
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Blank each removed statement to spaces, keeping its newlines so later
|
|
299
|
+
* lines keep their numbers. `surplus` newlines the folded initializer added
|
|
300
|
+
* are taken back out of the blanked text (or, when negative, added to it).
|
|
301
|
+
*/
|
|
302
|
+
function blankStatements(stmts: readonly ts.Statement[], sf: ts.SourceFile, surplus: number): Edit[] {
|
|
303
|
+
let pending = surplus
|
|
304
|
+
return stmts.map((s, k) => {
|
|
305
|
+
let text = ''
|
|
306
|
+
for (const ch of s.getText(sf)) {
|
|
307
|
+
if (ch !== '\n') text += ' '
|
|
308
|
+
else if (pending > 0) pending--
|
|
309
|
+
else text += '\n'
|
|
310
|
+
}
|
|
311
|
+
if (k === stmts.length - 1 && pending < 0) text += '\n'.repeat(-pending)
|
|
312
|
+
return { start: s.getStart(sf), end: s.getEnd(), text }
|
|
313
|
+
})
|
|
314
|
+
}
|