diff --git a/arkui-sem/src/engine.ts b/arkui-sem/src/engine.ts index 15bb0b0..50761e7 100644 --- a/arkui-sem/src/engine.ts +++ b/arkui-sem/src/engine.ts @@ -380,8 +380,9 @@ function describeInputUnbound(c: CandidateOf<'input-unbound'>): Description { const name = c.field.name; const [input] = c.inputs; const option = input.kind === 'Search' ? 'value' : 'text'; - // `$` replaces the onChange: offered only when the onChange does nothing but store the text, as typed, in this field. - const twoWay = c.inputs.every((i) => !i.effects && !i.normalizes && i.writes.every((w) => w.field === name)); + // `$$` replaces the onChange: offered only when the onChange does nothing but store the text in this field, also + // when it stores it normalized (`value.trim()`), which `$$` drops (tech-debt tracker). + const twoWay = c.inputs.every((i) => !i.effects && i.writes.every((w) => w.field === name)); const setters = [ ...new Set( c.sets.map((write) => diff --git a/arkui-sem/src/ets/callbacks.ts b/arkui-sem/src/ets/callbacks.ts index 6f940f8..1c977b0 100644 --- a/arkui-sem/src/ets/callbacks.ts +++ b/arkui-sem/src/ets/callbacks.ts @@ -2,7 +2,7 @@ // access sits (climb). A denylist: a function no rule here names counts as running while the UI is described. import type { BuildRead } from '../facts.js'; import { ts } from './parse.js'; -import { argumentOf, calleeName, drawsRows, isFunction, memberName, onComponent, thisMember } from './syntax.js'; +import { argumentOf, calleeName, isFunction, memberName, onComponent, thisMember } from './syntax.js'; /** The names a component's code can call as builders: its builder methods (`this.B(…)`), the file's builder functions, * and imported names, which may be builders (`B(…)`). */ @@ -153,7 +153,7 @@ export function climb( ) { attribute = callee.name.text; } - if ((ts.isIdentifier(callee) && LOOPS.has(callee.text)) || drawsRows(n)) { + if (ts.isIdentifier(callee) && LOOPS.has(callee.text)) { inForEach = true; } } diff --git a/arkui-sem/src/ets/component.ts b/arkui-sem/src/ets/component.ts index dd78bc0..0e1ec7f 100644 --- a/arkui-sem/src/ets/component.ts +++ b/arkui-sem/src/ets/component.ts @@ -30,7 +30,6 @@ import { isDollarThis, isDoubleBang, isFunction, - isNullish, isZero, memberName, pathBelow, @@ -112,14 +111,13 @@ export function component( const drawing = drawingMethods(scans); const renderOnly = renderOnlyMethods(scans, drawing); const loads = new Set(); - const { arms, repeated } = methodArms(scans); + const arms = methodArms(scans); const initCalls = initializerCalls(s, scan); for (const s of scans) { recordAccesses(s, byName, scan, builderNames, { drawn: drawing.get(s.method), renderOnly: renderOnly.has(s.method), arms: arms.get(s.method.name), - ownArms: !repeated.has(s.method.name), loads, initCalls, }); @@ -153,9 +151,7 @@ export function component( resources: resources(scans, scan), loops: methods .filter((m) => drawing.has(m)) - .flatMap((m) => - loopsIn(m.name, m.body, arms.get(m.name) ?? [], !repeated.has(m.name), scan, builderNames, members), - ), + .flatMap((m) => loopsIn(m.name, m.body, arms.get(m.name) ?? [], scan, builderNames, members)), builders: builderMethods.flatMap((m) => { const name = memberName(m.name); return name === undefined ? [] : [builderFact(name, m, scan, builderNames)]; @@ -195,7 +191,6 @@ function inputFacts( fact.effects || joined.some((t) => t.effects || t.calls.length > 0) || handlers.some((name) => !typingOf.has(name)), - normalizes: fact.normalizes || joined.some((t) => t.normalizes), }; }); } @@ -469,14 +464,12 @@ function recordAccesses( drawn, renderOnly, arms, - ownArms, loads, initCalls, }: { drawn: DrawSite | undefined; renderOnly: boolean; arms: Branch[] | undefined; - ownArms: boolean; loads: Set; initCalls: Map; }, @@ -494,7 +487,6 @@ function recordAccesses( calls: [], tested: new Set(), arms, - ownArms, loads, initCalls, }; @@ -528,8 +520,6 @@ interface AccessContext { tested: Set; /** The `if` arms of build() the method runs in (methodArms); undefined when not known. */ arms: Branch[] | undefined; - /** The `if` arms in the method's own body count too: false when it may run several times at once (methodArms). */ - ownArms: boolean; /** Writes outside callbacks or in promise continuations only (`.then`): run once if their method is. */ loads: Set; /** Each field whose initializer is a call, with that call's text. */ @@ -612,12 +602,9 @@ function access(base: ts.PropertyAccessExpression, field: FieldFact, ctx: Access value: mutatingCall ? undefined : assignedValue(assignment), ...(mutatingCall || updated || (assignment && accumulates(assignment, field.name)) ? { accumulates: true } : {}), ...(callName === undefined ? {} : { call: callName }), - ...(assignment && keepsPositions(assignment) ? { keepsPositions: true } : {}), - ...(assignment ? keptItems(assignment) : {}), - ...(assignment ? spreadSets(assignment) : {}), - ...(ctx.arms - ? { branches: [...ctx.arms, ...(ctx.ownArms ? branchesOf(base, ctx.method.body, ctx.scan.sf) : [])] } - : {}), + ...(assignment && segments.length === 0 && keepsPositions(assignment, field.name) ? { keepsPositions: true } : {}), + ...(assignment && segments.length === 0 ? keptItems(assignment, field.name) : {}), + ...(ctx.arms ? { branches: [...ctx.arms, ...branchesOf(base, ctx.method.body, ctx.scan.sf)] } : {}), ...(rebuilt.length ? { rebuilt } : {}), ...(assignment && segments.length === 0 && repeatsInitializer(assignment, ctx.initCalls.get(field.name), ctx.scan) ? { repeatsInitializer: true } @@ -639,19 +626,16 @@ function accumulates(assignment: ts.BinaryExpression, field: string): boolean { return reads(assignment.right); } -/** `this.F = [...this.F, x]`, `this.F.concat(x)`, `[]`, `null`, `this.F.slice()` or `this.F.slice(0, n)`, also of an array - * below the field (`this.F.tags = [...this.F.tags, x]`): no other item at an old position. */ -function keepsPositions(assignment: ts.BinaryExpression): boolean { +/** `this.F = [...this.F, x]`, `this.F.concat(x)`, `[]`, `this.F.slice()` or `this.F.slice(0, n)`: no other + * item at an old position. */ +function keepsPositions(assignment: ts.BinaryExpression, field: string): boolean { if (assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken) { return false; } const value = unwrap(assignment.right); - if (isNullish(value)) { - return true; - } if (ts.isArrayLiteralExpression(value)) { const [first] = value.elements; - return first === undefined || (ts.isSpreadElement(first) && sameTarget(first.expression, assignment.left)); + return first === undefined || (ts.isSpreadElement(first) && thisMember(unwrap(first.expression)) === field); } if (!(ts.isCallExpression(value) && ts.isPropertyAccessExpression(value.expression))) { return false; @@ -659,64 +643,31 @@ function keepsPositions(assignment: ts.BinaryExpression): boolean { const method = value.expression.name.text; const [start] = value.arguments; const fromStart = method === 'slice' && (start === undefined || isZero(start)); - return (method === 'concat' || fromStart) && sameTarget(value.expression.expression, assignment.left); -} - -/** `this.F = { ...this.F, name: x }`: the properties set next to a spread of the old value. None when another spread - * or a computed name may set any. */ -function spreadSets(assignment: ts.BinaryExpression): Pick { - const value = unwrap(assignment.right); - if (assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken || !ts.isObjectLiteralExpression(value)) { - return {}; - } - let self = false; - const sets: string[] = []; - for (const p of value.properties) { - if (ts.isSpreadAssignment(p) && sameTarget(p.expression, assignment.left)) { - self = true; - } else if (p.name && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) && !ts.isSpreadAssignment(p)) { - sets.push(p.name.text); - } else { - return {}; - } - } - return self ? { sets } : {}; -} - -/** Both name the same place: `this.F.tags` and `(this.F.tags)`. */ -function sameTarget(a: ts.Expression, b: ts.Expression): boolean { - return unwrap(a).getText() === unwrap(b).getText(); + return (method === 'concat' || fromStart) && thisMember(unwrap(value.expression.expression)) === field; } -/** The same items (`[...this.F]`, `this.F.slice()`, `this.F.slice(0)`, `this.F.concat()`) or none (`[]`, `null`, - * `this.F.slice(0, 0)`), also of an array below the field. */ -function keptItems(assignment: ts.BinaryExpression): Pick { +/** The same items (`[...this.F]`, `this.F.slice()`, `this.F.slice(0)`, `this.F.concat()`) or none (`[]`). */ +function keptItems(assignment: ts.BinaryExpression, field: string): Pick { if (assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken) { return {}; } const value = unwrap(assignment.right); - if (isNullish(value)) { - return { keepsItems: 'clear' }; - } if (ts.isArrayLiteralExpression(value)) { const [first, ...rest] = value.elements; if (first === undefined) { return { keepsItems: 'clear' }; } - const copy = rest.length === 0 && ts.isSpreadElement(first) && sameTarget(first.expression, assignment.left); + const copy = rest.length === 0 && ts.isSpreadElement(first) && thisMember(unwrap(first.expression)) === field; return copy ? { keepsItems: 'copy' } : {}; } if ( !(ts.isCallExpression(value) && ts.isPropertyAccessExpression(value.expression)) || - !sameTarget(value.expression.expression, assignment.left) + thisMember(unwrap(value.expression.expression)) !== field ) { return {}; } const method = value.expression.name.text; const args = value.arguments; - if (method === 'slice' && args.length === 2 && isZero(args[0]) && isZero(args[1])) { - return { keepsItems: 'clear' }; - } const copy = (method === 'concat' && args.length === 0) || (method === 'slice' && (args.length === 0 || (args.length === 1 && isZero(args[0])))); @@ -857,46 +808,22 @@ function setupMethods(scans: MethodWalk[], afterAwait: boolean): Set { * shares, each use's arms in its own body after those of the method holding it. A @Builder that only one arm calls, or * a method only a handler in that arm calls, runs only while the arm is shown. A method with a use in a lifecycle hook, * or with no use in the component (other code calls it), has none known. - * - * repeated: the methods that may run several times at once, whose own `if` arms then don't exclude each other (one - * run may take one arm, another the other): a use in a loop row or in a repeated method, or uses not all in exclusive - * arms of one method. They keep only the arms they inherit. */ -function methodArms(scans: MethodScan[]): { arms: Map; repeated: Set } { +function methodArms(scans: MethodScan[]): Map { const arms = new Map([['build', []]]); - const uses = new Map(); + const uses = new Map(); for (const scan of scans) { for (const use of scan.uses) { - const site = { caller: scan.method.name, branches: use.branches, inForEach: use.inForEach }; - uses.set(use.name, [...(uses.get(use.name) ?? []), site]); - } - } - const repeated = new Set(); - // Two uses in different arms of one `if` of the same method (queries.exclusiveArms) never run at once. - const apart = (a: { caller: string; branches: Branch[] }, b: { caller: string; branches: Branch[] }) => - a.caller === b.caller && a.branches.some((x) => b.branches.some((y) => x.at === y.at && x.arm !== y.arm)); - for (let changed = true; changed; ) { - changed = false; - for (const [name, sites] of uses) { - const several = sites.some((a, i) => sites.slice(0, i).some((b) => !apart(a, b))); - if ( - !repeated.has(name) && - name !== 'build' && - (several || sites.some((site) => site.inForEach || repeated.has(site.caller))) - ) { - repeated.add(name); - changed = true; - } + uses.set(use.name, [...(uses.get(use.name) ?? []), { caller: scan.method.name, branches: use.branches }]); } } - const own = (site: { caller: string; branches: Branch[] }) => (repeated.has(site.caller) ? [] : site.branches); for (let changed = true; changed; ) { changed = false; for (const [name, sites] of uses) { if (arms.has(name) || name === 'build' || !sites.every((site) => arms.has(site.caller))) { continue; } - const [first, ...rest] = sites.map((site) => [...(arms.get(site.caller) ?? []), ...own(site)]); + const [first, ...rest] = sites.map((site) => [...(arms.get(site.caller) ?? []), ...site.branches]); arms.set( name, first.filter((arm) => rest.every((other) => other.some((b) => b.at === arm.at && b.arm === arm.arm))), @@ -904,7 +831,7 @@ function methodArms(scans: MethodScan[]): { arms: Map; repeate changed = true; } } - return { arms, repeated }; + return arms; } /** diff --git a/arkui-sem/src/ets/inputs.ts b/arkui-sem/src/ets/inputs.ts index 341d1ba..5e5a046 100644 --- a/arkui-sem/src/ets/inputs.ts +++ b/arkui-sem/src/ets/inputs.ts @@ -42,8 +42,6 @@ export interface Typing { effects: boolean; /** The component methods it hands the text to (`this.setQuery(value)`); their first parameter is the text. */ calls: string[]; - /** A write or a call stores or hands on the text normalized (`value.trim()`), not as typed. */ - normalizes: boolean; } type Handler = ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration | ts.MethodDeclaration; @@ -63,17 +61,15 @@ export function typing(fn: Handler, scan: FileScan, members: { fields: Set { const field = typed(n); if (field !== undefined) { out.writes.push({ field, line: scan.line(n) }); - out.normalizes ||= ts.isBinaryExpression(n) && !ts.isIdentifier(unwrap(n.right)); } const called = handsText(n); if (called !== undefined) { out.calls.push(called); - out.normalizes ||= ts.isCallExpression(n) && !ts.isIdentifier(unwrap(n.arguments[0])); } ts.forEachChild(n, visit); }; @@ -149,7 +145,6 @@ function inputFact( const writes: InputFact['writes'] = []; const handlers = new Set(); let effects = false; - let normalizes = false; for (const handler of attributeArguments(call, 'onChange')) { const fn = unwrap(handler); const passed = isFunction(fn) ? undefined : boundMethod(fn); @@ -157,7 +152,6 @@ function inputFact( const found = typing(fn, scan, members); writes.push(...found.writes); effects ||= found.effects; - normalizes ||= found.normalizes; for (const name of found.calls) { handlers.add(name); } @@ -175,7 +169,6 @@ function inputFact( binding: binding(call.arguments[0], TEXT_OPTION[kind], members.fields), writes, effects, - normalizes, disabledRules: scan.disabledFor(call), }, handlers: [...handlers], diff --git a/arkui-sem/src/ets/loops.ts b/arkui-sem/src/ets/loops.ts index 2f2384e..717349d 100644 --- a/arkui-sem/src/ets/loops.ts +++ b/arkui-sem/src/ets/loops.ts @@ -1,15 +1,5 @@ // ForEach and LazyForEach calls, and what rows and builders do with the values they are given. -import type { - Branch, - BuilderFact, - LoopComparison, - LoopFact, - LoopKey, - LoopSource, - PathSegment, - ShownArray, - ValueUses, -} from '../facts.js'; +import type { Branch, BuilderFact, LoopComparison, LoopFact, LoopKey, LoopSource, ValueUses } from '../facts.js'; import { type BuilderNames, climb, isBuilderCall } from './callbacks.js'; import { ts } from './parse.js'; import type { FileScan } from './scan.js'; @@ -46,8 +36,6 @@ export interface Members { const COMPONENT_NAME = /^[A-Z]/; /** Array calls whose result holds elements of the array itself. */ const KEEPS_ELEMENTS = new Set(['filter', 'slice', 'sort', 'reverse', 'concat', 'toSorted', 'toReversed']); -/** Array calls after which an item that comes before another still does. */ -const KEEPS_PLACES = new Set(['filter', 'map', 'slice']); /** Array calls that put the elements in another order. */ const REORDERS = new Set(['sort', 'reverse', 'toSorted', 'toReversed']); const EQUALITY = new Set([ @@ -65,8 +53,6 @@ export function loopsIn( body: ts.Node, /** The `if` arms of build() the method runs in. */ arms: Branch[], - /** The arms in the method's own body count too: false when it may run several times at once. */ - ownArms: boolean, scan: FileScan, names: BuilderNames, members: Members, @@ -76,7 +62,7 @@ export function loopsIn( if ((ts.isCallExpression(node) || ts.isEtsComponentExpression(node)) && ts.isIdentifier(node.expression)) { const callee = node.expression.text; if (isKeyedLoop(callee) && !climb(node, body, names).inHandler) { - const branches = [...arms, ...(ownArms ? branchesOf(node, body, scan.sf) : [])]; + const branches = [...arms, ...branchesOf(node, body, scan.sf)]; out.push(loopFact(node, callee, method, branches, scan, names, members)); } } @@ -134,18 +120,14 @@ function loopSource(expr: ts.Expression, scan: FileScan, members: Members): Loop const body = helper === undefined ? undefined : members.body(helper); if (helper !== undefined && body && members.isHelper(helper, ts.isCallExpression(value))) { const returns = members.returnsField(helper); - const shown = shownArrays(members.returned(helper), body, members, scan); + const shown = shownArrays(members.returned(helper), body, members); return { text, shape: 'call', helper, ...(returns === undefined ? {} : { returns }), ...(shown.from === undefined ? {} : { returnsFrom: shown.from }), - ...(shown.arrays.length ? { shows: shown.arrays } : {}), ...(shown.reorders ? { reorders: true as const } : {}), - ...(shown.appends ? { appends: true as const } : {}), - ...(shown.tail === undefined ? {} : { tail: shown.tail }), - ...(shown.fallbacks.length ? { fallbacks: shown.fallbacks } : {}), ...(shown.windowEnds.length ? { windowEnds: shown.windowEnds } : {}), fields, }; @@ -154,7 +136,7 @@ function loopSource(expr: ts.Expression, scan: FileScan, members: Members): Loop return { text, shape: 'other', fields }; } const arms = armsOf(value); - const shown = shownArrays(arms, value, members, scan); + const shown = shownArrays(arms, value, members); // Only a source without arms shows the field's own elements. const root = arms.length === 1 ? rootField(value, members) : shown.from; const filteredBy = root === undefined || arms.length > 1 ? undefined : elementFilters(value); @@ -163,52 +145,25 @@ function loopSource(expr: ts.Expression, scan: FileScan, members: Members): Loop text, shape: 'derived', ...(root === undefined ? {} : { root }), - ...(shown.arrays.length ? { shows: shown.arrays } : {}), ...items, ...(shown.reorders ? { reorders: true as const } : {}), - ...(shown.appends ? { appends: true as const } : {}), - ...(shown.tail === undefined ? {} : { tail: shown.tail }), - ...(shown.fallbacks.length ? { fallbacks: shown.fallbacks } : {}), ...(shown.windowEnds.length ? { windowEnds: shown.windowEnds } : {}), fields, }; } /** What the arrays a source may show (`values`: the arms of a conditional, or what a method or getter returns) have in - * common. from: the field every one starts from; a value that shows nothing (`[]`, `null`) or no field's array - * (`DEFAULTS`) shows no other one. arrays: the arrays of fields the values show. reorders: one sorts, reverses or cuts - * from the end. appends: one shows other items after an array's (`.concat(x)`). tail: the field whose array ends - * every one. fallbacks: see `fallbackFields`. windowEnds: the fields read only as - * the end of a `.slice(0, n)` that keeps the items in place, nowhere else in `around` (the conditional or the - * method's body), whose other reads may pick another array; when every value shows nothing or the start of that - * field's array (`this.showAll ? this.F : this.F.slice(0, 3)`), every field `around` reads but that one: a change - * can only show more or fewer items at the end. */ + * common. from: the field every one starts from; a value that shows nothing (`[]`) or no field's array (`DEFAULTS`) + * shows no other one. reorders: one sorts, reverses or cuts from the end. windowEnds: the fields read only as the end + * of a `.slice(0, n)`, nowhere else in `around` (the conditional or the method's body); when every value shows + * nothing or the start of from's array (`this.showAll ? this.F : this.F.slice(0, 3)`), every field `around` reads + * but that one: a change can only show more or fewer items at the end. */ function shownArrays( values: ts.Expression[], around: ts.Node, members: Members, - scan: FileScan, -): { - from?: string; - arrays: ShownArray[]; - reorders: boolean; - appends: boolean; - tail?: string; - fallbacks: string[]; - windowEnds: string[]; -} { - const arrays = new Map(); - for (const e of values) { - const field = isEmptyValue(e) ? undefined : rootField(e, members); - if (field !== undefined) { - const array = { field, path: pathToArray(e, scan) }; - arrays.set(JSON.stringify(array), array); - } - } - const roots = new Set([...arrays.values()].map((a) => a.field)); - const shown = values.filter((e) => !isEmptyValue(e)); - const tails = new Set(shown.map((e) => tailField(e, members))); - const [tail] = tails.size === 1 && shown.length ? tails : []; +): { from?: string; reorders: boolean; windowEnds: string[] } { + const roots = new Set(values.flatMap((e) => (isEmptyValue(e) ? [] : (rootField(e, members) ?? [])))); const [from] = roots.size === 1 ? roots : []; const ends = new Set(values.flatMap(prefixEnds)); const elsewhere = new Set(fieldsRead(around, members, ends)); @@ -218,24 +173,18 @@ function shownArrays( : [...new Set([...ends].flatMap((end) => fieldsRead(end, members)))].filter((f) => !elsewhere.has(f)); return { ...(from === undefined ? {} : { from }), - arrays: [...arrays.values()], - reorders: values.some((e) => inChain(e, reordersCall)), - appends: values.some((e) => inChain(e, appendsCall)), - ...(tail === undefined ? {} : { tail }), - fallbacks: fallbackFields(around, members), + reorders: values.some(reordersArray), windowEnds, }; } -/** The value is the start of this.field's array, or all of it: `this.F`, `this.F.slice(0, n)`, `[...this.F]`. */ +/** The value is the start of this.field's array, or all of it: `this.F`, `this.F.slice(0, n)`. */ function startsOf(expr: ts.Expression, field: string): boolean { for (let value = unwrap(expr); ; ) { if (thisMember(value) === field) { return true; } - if (isSpreadCopy(value)) { - value = unwrap(value.elements[0].expression); - } else if ( + if ( ts.isCallExpression(value) && ts.isPropertyAccessExpression(value.expression) && value.expression.name.text === 'slice' && @@ -248,25 +197,13 @@ function startsOf(expr: ts.Expression, field: string): boolean { } } -/** The ends of each `.slice(0, n)` in the chain followed only by calls that keep the items in place (`filter`, `map`, - * `slice` from the start): a change shows more or fewer items at the end, and the same ones at each position. A - * `concat` after it would move what it appends; a sort, everything. A copy (`[...x]`) keeps the items in place. */ +/** The ends of each `.slice(0, n)` in the chain: a change shows more or fewer items at the end, the same ones at each + * position. */ function prefixEnds(expr: ts.Expression): ts.Expression[] { const ends: ts.Expression[] = []; - for (let value = unwrap(expr); ; ) { - if (isSpreadCopy(value)) { - value = unwrap(value.elements[0].expression); - continue; - } - if (!(ts.isCallExpression(value) && ts.isPropertyAccessExpression(value.expression))) { - break; - } - const method = value.expression.name.text; + for (let value = unwrap(expr); ts.isCallExpression(value) && ts.isPropertyAccessExpression(value.expression); ) { const [start, end] = value.arguments; - if (!KEEPS_PLACES.has(method) || (method === 'slice' && start && fromEnd(start))) { - break; - } - if (method === 'slice' && end && start && isZero(start)) { + if (value.expression.name.text === 'slice' && end && start && isZero(start)) { ends.push(end); } value = unwrap(value.expression.expression); @@ -274,88 +211,24 @@ function prefixEnds(expr: ts.Expression): ts.Expression[] { return ends; } -/** `[]`, `null` or `undefined`. */ +/** `[]`. */ function isEmptyValue(expr: ts.Expression): boolean { const value = unwrap(expr); - return (ts.isArrayLiteralExpression(value) && value.elements.length === 0) || isNullish(value); + return ts.isArrayLiteralExpression(value) && value.elements.length === 0; } -/** A call of the chain passes the test, also through a copy (`[...this.F.slice(-5)]`). */ -function inChain(expr: ts.Expression, test: (call: ts.CallExpression, method: string) => boolean): boolean { - for (let value = unwrap(expr); ; ) { - if (isSpreadCopy(value)) { - value = unwrap(value.elements[0].expression); - continue; - } - if (!(ts.isCallExpression(value) && ts.isPropertyAccessExpression(value.expression))) { - return false; - } - if (test(value, value.expression.name.text)) { +/** The chain sorts or reverses the array, or cuts it from the end (`.slice(-5)`, `.slice(a.length - 5)`), so an item + * appended to the array moves the others. */ +function reordersArray(expr: ts.Expression): boolean { + for (let value = unwrap(expr); ts.isCallExpression(value) && ts.isPropertyAccessExpression(value.expression); ) { + const method = value.expression.name.text; + const [start] = value.arguments; + if (REORDERS.has(method) || (method === 'slice' && start !== undefined && fromEnd(start))) { return true; } value = unwrap(value.expression.expression); } -} - -/** The field whose array ends the value, after other items: the last argument of the outermost `.concat(…)` in the - * chain (`this.F.concat(this.more)`), or the last spread of an array literal (`[...this.F, ...this.more]`). */ -function tailField(expr: ts.Expression, members: Members): string | undefined { - const field = (e: ts.Expression | undefined) => { - const name = e === undefined ? undefined : thisMember(unwrap(e)); - return name !== undefined && members.fields.has(name) ? name : undefined; - }; - for (let value = unwrap(expr); ; ) { - if (ts.isArrayLiteralExpression(value) && value.elements.length > 1) { - const last = value.elements[value.elements.length - 1]; - return ts.isSpreadElement(last) ? field(last.expression) : undefined; - } - if (isSpreadCopy(value)) { - value = unwrap(value.elements[0].expression); - continue; - } - if (!(ts.isCallExpression(value) && ts.isPropertyAccessExpression(value.expression))) { - return undefined; - } - if (appendsCall(value, value.expression.name.text)) { - return field(value.arguments[value.arguments.length - 1]); - } - value = unwrap(value.expression.expression); - } -} - -/** The fields on the left of a `??` or `||` under `around` whose right side may show something (`this.F ?? this.other`, - * not `this.F ?? []`): when one is `null` or `undefined`, the source shows the right side instead. */ -function fallbackFields(around: ts.Node, members: Members): string[] { - const out = new Set(); - const visit = (n: ts.Node) => { - if ( - ts.isBinaryExpression(n) && - (n.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken || - n.operatorToken.kind === ts.SyntaxKind.BarBarToken) && - armsOf(n.right).some((e) => !isEmptyValue(e)) - ) { - for (const e of armsOf(n.left)) { - const field = rootField(e, members); - if (field !== undefined) { - out.add(field); - } - } - } - ts.forEachChild(n, visit); - }; - visit(around); - return [...out]; -} - -/** Sorts or reverses an array, or cuts it from the end (`.slice(-5)`, `.slice(a.length - 5)`), so an item appended to - * the array moves the others. */ -function reordersCall(call: ts.CallExpression, method: string): boolean { - return REORDERS.has(method) || (method === 'slice' && call.arguments[0] !== undefined && fromEnd(call.arguments[0])); -} - -/** Shows other items after the array (`.concat(this.more)`), so any change to its length moves them. */ -function appendsCall(call: ts.CallExpression, method: string): boolean { - return method === 'concat' && call.arguments.length > 0; + return false; } /** A negative number, or a value computed from a length. */ @@ -472,30 +345,6 @@ function rootField(expr: ts.Expression, members: Members): string | undefined { } } -/** The property and element accesses on the field the chain starts from, before any call or copy: `.tags` in - * `this.F.tags.filter(…)`, `[i].tags` in `this.F[i].tags`. */ -function pathToArray(expr: ts.Expression, scan: FileScan): PathSegment[] { - let path: PathSegment[] = []; - for (let value = unwrap(expr); thisMember(value) === undefined; ) { - if (ts.isCallExpression(value) && ts.isPropertyAccessExpression(value.expression)) { - path = []; - value = unwrap(value.expression.expression); - } else if (ts.isPropertyAccessExpression(value)) { - path.unshift({ prop: value.name.text }); - value = unwrap(value.expression); - } else if (ts.isElementAccessExpression(value)) { - path.unshift({ index: scan.text(value.argumentExpression) }); - value = unwrap(value.expression); - } else if (isSpreadCopy(value)) { - path = []; - value = unwrap(value.elements[0].expression); - } else { - return []; - } - } - return path; -} - /** `[...x]`: a copy of one array. */ function isSpreadCopy(value: ts.Expression): value is ts.ArrayLiteralExpression & { elements: [ts.SpreadElement] } { return ts.isArrayLiteralExpression(value) && value.elements.length === 1 && ts.isSpreadElement(value.elements[0]); diff --git a/arkui-sem/src/ets/syntax.ts b/arkui-sem/src/ets/syntax.ts index 1f7309e..9cf323a 100644 --- a/arkui-sem/src/ets/syntax.ts +++ b/arkui-sem/src/ets/syntax.ts @@ -49,18 +49,13 @@ export function unwrap(e: ts.Expression): ts.Expression { return e; } -/** The values an expression may take: each arm of a conditional apart (`this.ready ? this.F.filter(…) : []`), each - * side of a fallback (`this.F ?? []`, `this.F || []`). */ +/** The values an expression may take: each arm of a conditional apart (`this.ready ? this.F.filter(…) : []`). */ export function armsOf(e: ts.Expression): ts.Expression[] { const value = unwrap(e); if (ts.isConditionalExpression(value)) { return [...armsOf(value.whenTrue), ...armsOf(value.whenFalse)]; } - const fallback = - ts.isBinaryExpression(value) && - (value.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken || - value.operatorToken.kind === ts.SyntaxKind.BarBarToken); - return fallback ? [...armsOf(value.left), ...armsOf(value.right)] : [e]; + return [e]; } /** `null` or `undefined`. */ @@ -131,45 +126,17 @@ export function isFunction(n: ts.Node): n is ts.ArrowFunction | ts.FunctionExpre return ts.isArrowFunction(n) || ts.isFunctionExpression(n) || ts.isFunctionDeclaration(n); } -/** The `if` arms between root and node, outermost first. Only those outside the innermost loop row that holds node: - * rows can take different arms of an `if` inside them at once. */ +/** The `if` arms between root and node, outermost first. */ export function branchesOf(node: ts.Node, root: ts.Node, sf: ts.SourceFile): Branch[] { const out: Branch[] = []; for (let child = node, parent = node.parent; parent && child !== root; child = parent, parent = parent.parent) { if (ts.isIfStatement(parent) && child !== parent.expression) { out.unshift({ at: parent.getStart(sf), arm: child === parent.thenStatement ? 'then' : 'else' }); - } else if (drawsRows(child)) { - out.length = 0; } } return out; } -/** fn draws a loop's rows: a function passed to ForEach, LazyForEach or Repeat, or to a Repeat's `.each(…)` or - * `.template(…)`. */ -export function drawsRows(fn: ts.Node): boolean { - const call = isFunction(fn) ? argumentOf(fn) : undefined; - if (call === undefined) { - return false; - } - const callee = call.expression; - if (ts.isIdentifier(callee)) { - return LOOPS.has(callee.text); - } - if (!(ts.isPropertyAccessExpression(callee) && ROW_ATTRIBUTES.has(callee.name.text))) { - return false; - } - // The call the attribute chain starts from: `Repeat(…)` in `Repeat(…).key(…).each(…)`. - let start = callee.expression; - while (ts.isCallExpression(start) && ts.isPropertyAccessExpression(start.expression)) { - start = start.expression.expression; - } - return ts.isCallExpression(start) && ts.isIdentifier(start.expression) && start.expression.text === 'Repeat'; -} - -const LOOPS = new Set(['ForEach', 'LazyForEach', 'Repeat']); -const ROW_ATTRIBUTES = new Set(['each', 'template']); - export function isAssignment(kind: ts.SyntaxKind): boolean { return kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment; } diff --git a/arkui-sem/src/facts.ts b/arkui-sem/src/facts.ts index e9653e6..2eb91b8 100644 --- a/arkui-sem/src/facts.ts +++ b/arkui-sem/src/facts.ts @@ -47,12 +47,8 @@ export interface WriteFact { * clear (`[]`) or a cut from the start (`this.F.slice(0, n)`). */ keepsPositions?: true; /** Of those, one that keeps the same items (`copy`: `[...this.F]`, `this.F.slice()`, `this.F.concat()`) or none - * (`clear`: `[]`, `this.F.slice(0, 0)`). Even a sorted or reversed view of the array shows the same item at each - * position, or no rows. */ + * (`clear`: `[]`). Even a sorted or reversed view of the array shows the same item at each position, or no rows. */ keepsItems?: 'copy' | 'clear'; - /** An object literal that spreads the old value (`this.F = { ...this.F, name: x }`): the properties it sets; the - * others keep their values. */ - sets?: string[]; /** The writing method is reached neither from build()/@Builder nor from lifecycle hooks: other code calls it. */ external?: boolean; /** The write loads what the component starts with: in aboutToAppear or a helper only it calls, outside callbacks @@ -203,8 +199,6 @@ export interface InputFact { * to a handler method and `console` calls; a handler method that does more, hands the text on again or that other * code uses; a handler that can't be read. */ effects: boolean; - /** A typed write stores the text normalized (`value.trim()`), here or in a handler method it joins. */ - normalizes: boolean; disabledRules: string[]; } @@ -252,14 +246,6 @@ export interface Branch { arm: 'then' | 'else'; } -/** An array a loop's source may show: the field it starts from and the accesses on that field before any call (`.tags` - * in `this.F.tags.filter(…)`, `[i].tags` in `this.F[this.sel].tags`). A write of the field at or below that array may - * move it; one beside it (`this.F.name`) does not. */ -export interface ShownArray { - field: string; - path: PathSegment[]; -} - /** * The loop's data source. field: `this.F`. derived: an expression over fields (`this.F.filter(…)`, `this.F[i].p`, * `X[this.S].p`). call: a method call or a getter of the component (`this.visible()`, `this.visible`). new: a `new` @@ -271,9 +257,6 @@ export interface LoopSource { /** The field the source starts from (`F` in `this.F`, `this.F.filter(…)`, `this.F[i].p`); for a conditional, the * field each arm that shows an array starts from (`this.ready ? this.F : []`). */ root?: string; - /** Every array the source may show: of each arm of a conditional or fallback, or each value a method or getter it - * calls returns, that starts from a field. */ - shows?: ShownArray[]; /** The field whose own elements are the items: `this.F`, or this.F through calls that keep its elements * (`this.F.filter(…)`, `.slice(…)`, `.sort(…)`). */ itemsOf?: string; @@ -287,22 +270,13 @@ export interface LoopSource { /** The source, or what the method or getter it calls returns, sorts or reverses an array or cuts it from the end * (`.reverse()`, `.slice(-n)`): an append moves the items at a position too. */ reorders?: true; - /** The source, or what the method or getter it calls returns, shows other items after an array's - * (`this.F.concat(this.more)`): any change to that array's length, a clear too, moves them. */ - appends?: true; - /** The field whose array ends every array the source shows, after others (`this.more` in `this.F.concat(this.more)`, - * `[...this.F, ...this.more]`): a write that keeps its positions only adds or removes rows at the end. */ - tail?: string; - /** Fields on the left of a `??` or `||` in the source, or in the method or getter it calls, whose right side shows - * something (`this.F ?? this.other`): a `null` or `undefined` write of one shows that at the same positions. */ - fallbacks?: string[]; /** For a call: the field every value the method or getter returns starts from (`return this.F.filter(…)`), whose * own array it shows. */ returnsFrom?: string; - /** Fields the source, or the method or getter it calls, reads only as the end of a `.slice(0, n)` followed by - * calls that keep the items in place (`this.F.slice(0, this.n)`), not in a condition or guard; or any field but - * F when every array it may show is F or its start (`this.showAll ? this.F : this.F.slice(0, 3)`): a change shows - * more or fewer items at the end, the same ones at each position. */ + /** Fields the source, or the method or getter it calls, reads only as the end of a `.slice(0, n)` + * (`this.F.slice(0, this.n)`), not in a condition or guard; or any field but F when every array it may show is F + * or its start (`this.showAll ? this.F : this.F.slice(0, 3)`): a change shows more or fewer items at the end, the + * same ones at each position. */ windowEnds?: string[]; /** The component's fields the source accesses, through the methods and getters it calls (outside their handlers), * transitively. */ diff --git a/arkui-sem/src/queries.ts b/arkui-sem/src/queries.ts index ca9b0cc..8f16e21 100644 --- a/arkui-sem/src/queries.ts +++ b/arkui-sem/src/queries.ts @@ -28,11 +28,6 @@ export function feedsRender(w: WriteFact): boolean { /** Array calls that leave every element at its position. */ const KEEPS_POSITIONS = new Set(['push', 'pop']); -/** A mutating array call that leaves every element at its position: `push`, `pop`. */ -export function keepsPositionsCall(call: string): boolean { - return KEEPS_POSITIONS.has(call); -} - /** The write of an array field may put other items at its existing positions: a reassignment other than an append, * a clear or a cut, an index write, or a call that reorders, inserts or removes before the end. */ export function moves(w: WriteFact): boolean { @@ -40,7 +35,7 @@ export function moves(w: WriteFact): boolean { if (first === undefined) { return !w.keepsPositions; } - return isIndex(first) && below.length === 0 && !(w.call !== undefined && keepsPositionsCall(w.call)); + return isIndex(first) && below.length === 0 && !(w.call !== undefined && KEEPS_POSITIONS.has(w.call)); } /** The write runs after the component's first load: not in aboutToAppear or a helper only it calls. */ diff --git a/arkui-sem/src/rules/R1.ts b/arkui-sem/src/rules/R1.ts index fd65f56..197e90a 100644 --- a/arkui-sem/src/rules/R1.ts +++ b/arkui-sem/src/rules/R1.ts @@ -28,7 +28,6 @@ import { isOwnedV2, isReactive, isReactiveV1, - keepsPositionsCall, linkTypesOf, memberOf, moves, @@ -467,45 +466,26 @@ function indexKeyCandidates( /** The writes of a state field the loop's source reads that change which item sits at a position after the first * render. Of the source's own array only writes that move items count, and through a method or getter none that - * keeps the positions of an array it may return (an append), unless the source reorders that array or shows other - * items after it (`.concat(x)`) and the write adds or removes items; none in the other arm of an `if` that holds the - * loop, which runs while the loop is not shown, and switching back recreates it. The array a method or getter - * returns moves like the source's own. */ + * keeps the positions of an array it may return (an append), unless the source reorders that array and the write + * adds or removes items; none in the other arm of an `if` that holds the loop, which runs while the loop is not + * shown, and switching back recreates it. The array a method or getter returns moves like the source's own. */ function shiftsOf(component: ComponentFact, loop: LoopFact, name: string): IndexShift[] { const field = observedField(component, name); if (!field || loop.source.windowEnds?.includes(name)) { return []; } - const arrays = (loop.source.shows ?? []).filter((a) => a.field === name); - const how = arrays.length || name === (loop.source.root ?? loop.source.returnsFrom) ? 'move' : 'select'; - const paths = arrays.length ? arrays.map((a) => a.path) : [[]]; + const how = name === (loop.source.root ?? loop.source.returnsFrom) ? 'move' : 'select'; // An array write that keeps positions: an append, a clear, a cut from the end. Under a source that reorders the // array (`.reverse()`, `.slice(-n)`) one that adds or removes items moves those shown at a position all the same; a // copy or a clear does not. const keepsArray = (write: WriteFact) => !moves(write) && (write.path?.length ?? 0) <= 1 && (write.path === undefined || isIndex(write.path[0])); - // A source that shows other items after the array (`.concat(x)`) moves them on any change to its length, a clear too. - // The array that ends the source (`.concat(this.more)`) has no other items after it. - const tail = name === loop.source.tail; - const slides = (write: WriteFact) => - keepsArray(write) && - write.keepsItems !== 'copy' && - ((loop.source.appends === true && !tail) || (loop.source.reorders === true && write.keepsItems === undefined)); + const slides = (write: WriteFact) => keepsArray(write) && loop.source.reorders === true && !write.keepsItems; const changes = (write: WriteFact) => { if (how === 'select') { - const shown = loop.source.shape === 'call' || tail; - return (write.path?.length ?? 0) <= 1 && !(shown && keepsArray(write) && !slides(write)); + return (write.path?.length ?? 0) <= 1 && !(loop.source.shape === 'call' && keepsArray(write) && !slides(write)); } - // `null` or `undefined` under a fallback (`this.F ?? this.other`) shows the other array at the same positions. - const revealsFallback = (own: WriteFact) => - own.path === undefined && own.value === 'constant' && loop.source.fallbacks?.includes(name) === true; - return paths.some((path) => { - const own = belowArray(write, path); - if (own === 'above') { - return replacesHolder(write, path); - } - return own !== undefined && (moves(own) || slides(own) || revealsFallback(own)); - }); + return moves(write) || slides(write); }; const writes = field.writes.filter( (write) => @@ -602,35 +582,6 @@ function observedField(component: ComponentFact, name: string): FieldFact | unde return field && !isNonState(field) && isReactive(field) && !field.disabledRules.includes('R1') ? field : undefined; } -/** A write of the root field as a write of the array at `path` below it: the rest of its path when it writes there or - * below, `above` when it writes a holder above (`this.F = …`, `this.F.sort()`), none when it writes beside it - * (`this.F.name`). Indexes match whatever their text. */ -function belowArray(write: WriteFact, path: PathSegment[]): WriteFact | 'above' | undefined { - const segments = write.path ?? []; - const same = (a: PathSegment, b: PathSegment) => ('prop' in a ? 'prop' in b && a.prop === b.prop : isIndex(b)); - const n = Math.min(segments.length, path.length); - if (!segments.slice(0, n).every((s, i) => same(s, path[i]))) { - return undefined; - } - if (segments.length < path.length) { - return 'above'; - } - const rest = segments.slice(path.length); - return { ...write, path: rest.length ? rest : undefined }; -} - -/** A write of a holder above the array at `path` (`this.F = …`, `this.F[i] = …`, `this.F.trip = …`, `this.F.sort()`) - * puts another array there, unless it keeps the positions of the holder array it writes (`push`, an append, a clear) - * or spreads the old object and leaves the next property on the path alone (`this.F = { ...this.F, name: x }`). */ -function replacesHolder(write: WriteFact, path: PathSegment[]): boolean { - if (write.call !== undefined) { - return !keepsPositionsCall(write.call); - } - const next = path[write.path?.length ?? 0]; - const kept = write.sets !== undefined && next !== undefined && 'prop' in next && !write.sets.includes(next.prop); - return !write.keepsPositions && !kept; -} - /** The ForEach loops over the field's own elements whose key stays with an element: item properties or the index. */ function keyedLoops(component: ComponentFact, field: FieldFact): LoopFact[] { return component.loops.filter( diff --git a/arkui-sem/test/loops.test.ts b/arkui-sem/test/loops.test.ts index 2af83ca..cf4cf69 100644 --- a/arkui-sem/test/loops.test.ts +++ b/arkui-sem/test/loops.test.ts @@ -90,24 +90,10 @@ describe('loop source', () => { helper: 'all', returns: 'songs', returnsFrom: 'songs', - shows: [{ field: 'songs', path: [] }], fields: ['songs'], }); }); - test('the arrays a source may show: the field each starts from and the accesses on it before any call', () => { - const at = [{ index: 'this.shelf' }, { prop: 'artist' }]; - assert.deepEqual(source('this.songs[this.shelf].artist.slice().reverse()').shows, [{ field: 'songs', path: at }]); - assert.deepEqual(source('this.songs.slice(0, 2)[0].artist').shows, [{ field: 'songs', path: [] }]); - assert.deepEqual(source('this.shelf > 0 ? this.songs[this.shelf].artist : []').shows, [ - { field: 'songs', path: at }, - ]); - const members = ' get artist() { return this.songs[this.shelf]?.artist ?? [] }'; - assert.deepEqual(source('this.artist', members).shows, [ - { field: 'songs', path: [{ index: 'this.shelf' }, { prop: 'artist' }] }, - ]); - }); - test("a helper's accesses in its handlers are left out", () => { const members = ' list(): Song[] { setTimeout(() => { this.shelf++ }, 1)\n return this.songs }'; assert.deepEqual(source('this.list()', members).fields, ['songs']); diff --git a/arkui-sem/test/rules/R1-index.test.ts b/arkui-sem/test/rules/R1-index.test.ts index c1c1892..43bc684 100644 --- a/arkui-sem/test/rules/R1-index.test.ts +++ b/arkui-sem/test/rules/R1-index.test.ts @@ -119,7 +119,6 @@ describe('foreach-index-key fires', () => { [lastFive, 'this.lastFive()'], ['', 'this.names.slice(-5)'], ['', '[...this.names].reverse()'], - ['', '[...this.names.slice(-5)]'], ]) { const [c, ...rest] = indexKeyed(page(members, `${push}\n${loop(source)}`)); assert.equal(rest.length, 0, source); @@ -130,176 +129,6 @@ describe('foreach-index-key fires', () => { ); } }); - - test('a change to the length of an array other items follow (`.concat(x)`), a clear too', () => { - const more = ' @State more: string[] = []'; - const visible = `${more}\n get visible(): string[] {\n return this.names.concat(this.more)\n }`; - for (const write of [ - "this.names.push('x')", - 'this.names.pop()', - "this.names = [...this.names, 'x']", - 'this.names = this.names.slice(0, 2)', - 'this.names = []', - ]) { - for (const [members, source] of [ - [more, 'this.names.concat(this.more)'], - ['', "this.names.concat(['footer'])"], - [visible, 'this.visible'], - ]) { - const src = page(members, ` Button('a').onClick(() => { ${write} })\n${loop(source)}`); - assert.equal(indexKeyed(src).length, 1, `${write} under ${source}`); - } - } - // Control: a copy keeps every item at its position. - for (const write of ['this.names = [...this.names]', 'this.names = this.names.slice()']) { - const src = page('', ` Button('a').onClick(() => { ${write} })\n${loop("this.names.concat(['footer'])")}`); - assert.deepEqual(indexKeyed(src), [], write); - } - }); - - test('a write that moves an array below the field the source starts from', () => { - const trip = " @State trip: Trip = { id: 0, name: '', tags: [] }"; - for (const [source, write] of [ - ['this.trip.tags', 'this.trip.tags = this.trip.tags.filter((t: string) => t.length > 0)'], - ['this.trip.tags', 'this.trip.tags.sort()'], - ['this.trip.tags.slice()', "this.trip.tags[0] = 'x'"], - ['this.trips[this.sel].tags', 'this.trips[this.sel].tags = []\n this.trips[this.sel].tags.reverse()'], - ['this.trips[this.sel].tags', 'this.trips.sort()'], - ]) { - const src = page(trip, ` Button('a').onClick(() => { ${write} })\n${loop(source)}`); - assert.equal(indexKeyed(src).length, 1, `${write} under ${source}`); - } - // Control: a write beside the array, an append, a clear. - for (const [source, write] of [ - ['this.trip.tags', "this.trip.name = 'x'"], - ['this.trip.tags', "this.trip.tags.push('x')"], - ['this.trip.tags', "this.trip.tags = [...this.trip.tags, 'x']"], - ['this.trip.tags', 'this.trip.tags = []'], - ['this.trips[this.sel].tags', "this.trips[this.sel].name = 'x'"], - ['this.trips[this.sel].tags', 'this.trips.push(this.trip)'], - ]) { - const src = page(trip, ` Button('a').onClick(() => { ${write} })\n${loop(source)}`); - assert.deepEqual(indexKeyed(src), [], `${write} under ${source}`); - } - }); - - test('a write of a holder above the array the source shows', () => { - const members = - " @State trip: Trip = { id: 0, name: '', tags: [] }\n @State state: { trip: Trip } = { trip: { id: 0, name: '', tags: [] } }\n @State more: string[] = []"; - const fires = [ - ['this.state.trip.tags', "this.state.trip = { id: 1, name: 'b', tags: ['x'] }"], - ['this.trips[this.sel].tags', 'this.trips[0] = this.trip'], - ['this.trip.tags', 'this.trip = { ...this.trip, tags: this.trip.tags.slice().reverse() }'], - ]; - for (const [source, write] of fires) { - const src = page(members, ` Button('a').onClick(() => { ${write} })\n${loop(source)}`); - assert.equal(indexKeyed(src).length, 1, `${write} under ${source}`); - } - // Control: a holder array that keeps its positions, an object spread that leaves the array alone. - const quiet = [ - ['this.trips[this.sel].tags.slice().reverse()', 'this.trips.push(this.trip)'], - ['this.trips[this.sel].tags.concat(this.more)', 'this.trips = [...this.trips, this.trip]'], - ['this.trip.tags', "this.trip = { ...this.trip, name: 'x' }"], - [ - 'this.state.trip.tags', - 'this.state = { ...this.state }\n this.state.trip = { ...this.state.trip, id: 2 }', - ], - ]; - for (const [source, write] of quiet) { - const src = page(members, ` Button('a').onClick(() => { ${write} })\n${loop(source)}`); - assert.deepEqual(indexKeyed(src), [], `${write} under ${source}`); - } - }); - - test('a nested array under a fallback, a conditional, a getter, or one of two holders', () => { - const members = ` @State trip: Trip = { id: 0, name: '', tags: [] } - @State other: Trip = { id: 0, name: '', tags: [] } - get tags(): string[] { - return this.trip.tags - }`; - for (const source of [ - 'this.trip?.tags ?? []', - 'this.sel > 0 ? this.trip.tags : []', - 'this.tags', - 'this.sel > 0 ? this.trip.tags : this.other.tags', - ]) { - for (const write of [ - 'this.trip.tags = this.trip.tags.filter((t: string) => t.length > 0)', - 'this.trip.tags.sort()', - ]) { - const src = page(members, ` Button('a').onClick(() => { ${write} })\n${loop(source)}`); - assert.equal(indexKeyed(src).length, 1, `${write} under ${source}`); - } - // Control: a write beside the array. - const src = page(members, ` Button('a').onClick(() => { this.trip.name = 'x' })\n${loop(source)}`); - assert.deepEqual(indexKeyed(src), [], `a write beside the array under ${source}`); - } - }); - - test('an append to the array that ends the source, after the others', () => { - const members = ` @State more: string[] = [] - @State last: string[] = [] - get all(): string[] { - return this.names.concat(this.more) - }`; - const append = (field: string) => [`this.${field}.push('x')`, `this.${field} = [...this.${field}, 'x']`]; - for (const source of ['this.names.concat(this.more)', '[...this.names, ...this.more]', 'this.all']) { - for (const write of append('more')) { - const src = page(members, ` Button('a').onClick(() => { ${write} })\n${loop(source)}`); - assert.deepEqual(indexKeyed(src), [], `${write} under ${source}`); - } - } - // Control: an array with others after it, a source that reverses the whole list. - for (const source of ['this.names.concat(this.more, this.last)', 'this.names.concat(this.more).reverse()']) { - for (const write of append('more')) { - const src = page(members, ` Button('a').onClick(() => { ${write} })\n${loop(source)}`); - assert.equal(indexKeyed(src).length, 1, `${write} under ${source}`); - } - } - }); - - test('a write in the other arm of an if inside an outer loop row: other rows take that arm', () => { - const rows = (inner: string) => ` ForEach(this.trips, (g: Trip) => { - if (g.id > 0) { - ${inner} - } else { - Button('sort').onClick(() => { this.names.sort() }) - } - }, (g: Trip) => \`\${g.id}\`)`; - assert.equal(indexKeyed(page('', rows(loop('this.names')))).length, 1); - const repeat = ` Repeat(this.trips).each((r: RepeatItem) => { - if (r.item.id > 0) { - ${loop('this.names')} - } else { - Button('sort').onClick(() => { this.names.sort() }) - } - })`; - assert.equal(indexKeyed(page('', repeat)).length, 1); - }); - - test('a write in the other arm of an if inside a @Builder that runs several times at once', () => { - const panel = ` @Builder Panel(on: boolean) { - if (on) { -${loop('this.names')} - } else { - Button('sort').onClick(() => { this.names.sort() }) - } - }`; - // Each row calls it; build() calls it twice; the else arm hands the write to another @Builder. - const rowCalls = ' ForEach(this.trips, (g: Trip) => { this.Panel(g.id > 0) }, (g: Trip) => `${g.id}`)'; - assert.equal(indexKeyed(page(panel, rowCalls)).length, 1); - const repeatRows = ' Repeat(this.trips).each((r: RepeatItem) => { this.Panel(r.item.id > 0) })'; - assert.equal(indexKeyed(page(panel, repeatRows)).length, 1); - assert.equal(indexKeyed(page(panel, ' this.Panel(true)\n this.Panel(false)')).length, 1); - const sorter = " @Builder Sorter() {\n Button('sort').onClick(() => { this.names.sort() })\n }"; - const handsOn = panel.replace("Button('sort').onClick(() => { this.names.sort() })", 'this.Sorter()'); - assert.equal(indexKeyed(page(`${handsOn}\n${sorter}`, rowCalls)).length, 1); - // Control: called once, or once in each arm of an if, it takes one arm at a time. - assert.deepEqual(indexKeyed(page(panel, ' this.Panel(this.sel > 0)')), []); - const eachArm = - ' if (this.sel > 0) {\n this.Panel(true)\n } else {\n this.Panel(false)\n }'; - assert.deepEqual(indexKeyed(page(panel, eachArm)), []); - }); }); describe('foreach-index-key does not fire', () => { @@ -359,7 +188,6 @@ describe('foreach-index-key does not fire', () => { for (const source of [ 'this.names.slice(0, this.sel)', 'this.names.filter((n: string) => n !== "").slice(0, this.sel)', - '[...this.names.slice(0, this.sel)]', ]) { assert.deepEqual(indexKeyed(page('', `${more}\n${loop(source)}`)), [], source); } @@ -367,14 +195,8 @@ describe('foreach-index-key does not fire', () => { assert.deepEqual(indexKeyed(page(firstSel, `${more}\n${loop('this.firstSel')}`)), []); const guarded = 'this.trips.length > 0 ? this.names.slice(0, this.sel) : []'; assert.deepEqual(indexKeyed(page('', `${more}\n${loop(guarded)}`)), []); - // Controls: a window that starts at the bound, one reversed after the cut, one followed by other items. - for (const source of [ - 'this.names.slice(this.sel)', - 'this.names.slice(0, this.sel).reverse()', - 'this.names.slice(0, this.sel).concat(this.trips[0].tags)', - ]) { - assert.equal(indexKeyed(page('', `${more}\n${loop(source)}`)).length, 1, source); - } + // Control: a window that starts at the bound. + assert.equal(indexKeyed(page('', `${more}\n${loop('this.names.slice(this.sel)')}`)).length, 1); // Nor a bound that also picks which array shows, in a condition or a guard. const picks = 'this.sel > 0 ? this.names.slice(0, this.sel) : this.names.slice().reverse()'; assert.equal(indexKeyed(page('', `${more}\n${loop(picks)}`)).length, 1); @@ -393,48 +215,12 @@ describe('foreach-index-key does not fire', () => { ); }); - test('a null or undefined clear of a nullable source, unless a fallback shows another array', () => { - const maybe = ` @State maybe: string[] | null | undefined = null - get shown(): string[] { - return this.maybe ?? this.names - }`; - for (const write of ['this.maybe = null', 'this.maybe = undefined']) { - for (const source of ['this.maybe ?? []', 'this.maybe || []']) { - const src = page(maybe, ` Button('a').onClick(() => { ${write} })\n${loop(source)}`); - assert.deepEqual(indexKeyed(src), [], `${write} under ${source}`); - } - // Control: the fallback shows another array at the same positions. - for (const source of ['this.maybe ?? this.names', 'this.maybe || DEFAULTS', 'this.shown']) { - const src = page(maybe, ` Button('a').onClick(() => { ${write} })\n${loop(source)}`); - assert.equal(indexKeyed(src).length, 1, `${write} under ${source}`); - } - } - }); - - test('an append to one of the arrays a conditional or a fallback may show', () => { - const more = ' @State more: string[] = []\n @State maybe: string[] | null = null'; - for (const source of ['this.sel > 0 ? this.names : this.more', 'this.maybe ?? []', 'this.maybe || this.names']) { - for (const field of ['names', 'more', 'maybe']) { - const write = `if (this.${field}) { this.${field}.push('x') }`; - const src = page(more, ` Button('a').onClick(() => { ${write} })\n${loop(source)}`); - assert.deepEqual(indexKeyed(src), [], `${write} under ${source}`); - } - } - // Control: the toggle switches arrays; appending to the first of two arrays shown one after the other moves the - // second's items. - const toggle = page(more, `${tabs}\n${loop('this.sel > 0 ? this.names : this.more')}`); - assert.equal(indexKeyed(toggle).length, 1); - const push = " Button('a').onClick(() => { this.names.push('x') })"; - assert.equal(indexKeyed(page(more, `${push}\n${loop('[...this.names, ...this.more]')}`)).length, 1); - }); - test('a toggle between the list, its first items or nothing: only rows at the end come and go', () => { const more = " Button('more').onClick(() => { this.sel += 5 })"; const getter = ' get shown(): string[] {\n if (this.sel > 0) {\n return this.names\n }\n return this.names.slice(0, 3)\n }'; for (const [members, source] of [ ['', 'this.sel > 0 ? this.names : this.names.slice(0, 3)'], - ['', 'this.sel > 0 ? [...this.names] : []'], [getter, 'this.shown'], ]) { assert.deepEqual(indexKeyed(page(members, `${more}\n${loop(source)}`)), [], source); @@ -451,7 +237,6 @@ describe('foreach-index-key does not fire', () => { 'this.names = this.names.slice()', 'this.names = this.names.concat()', 'this.names = []', - 'this.names = this.names.slice(0, 0)', ]) { for (const [members, source] of [ [recent, 'this.recent'], diff --git a/arkui-sem/test/rules/R4.test.ts b/arkui-sem/test/rules/R4.test.ts index 97be809..420d42f 100644 --- a/arkui-sem/test/rules/R4.test.ts +++ b/arkui-sem/test/rules/R4.test.ts @@ -296,15 +296,4 @@ test('input-unbound: the $$ fix is offered only when the onChange does nothing b const [unbound] = findings.filter((f) => f.kind === 'input-unbound'); assert.match(unbound.fix, /keep the onChange\.$/); assert.doesNotMatch(unbound.fix, /\$\$/); - // The onChange trims the text, here or through a handler method: `$$` would store it untrimmed. - for (const store of ['this.name = value.trim()', 'this.setName(value.trim())']) { - put( - file, - editDialog({ extra: 'setName(v: string) {\n this.name = v\n }' }).replace('this.name = value', store), - ); - const [trimmed] = (await checkFiles([file], { backend: noJudge })).findings.filter( - (f) => f.kind === 'input-unbound', - ); - assert.match(trimmed.fix, /keep the onChange\.$/, store); - } }); diff --git a/docs/exec-plans/active/coverage-extensions.md b/docs/exec-plans/active/coverage-extensions.md index fb7c75b..edfe2a7 100644 --- a/docs/exec-plans/active/coverage-extensions.md +++ b/docs/exec-plans/active/coverage-extensions.md @@ -49,7 +49,8 @@ evaluates each PR on its committed tree (regression over recorded agent sessions (a finding) and `input-never-read` (a question); R4 widened in the roadmap and design docs; demo page `Notes.ets`. - Step 5a: done (branch `foreach-index-lazy`, stacked on #36): `foreach-index-key` (finding; a question when only methods move the list); write facts gain the array call, reassignments that keep positions, initial loads and the `if` - arms in build(); loop facts gain their `if` arms. + arms in build(); loop facts gain their `if` arms. Compacted afterwards (branch `compact-foreach-index-key`): the + source shapes review fixes added for rare code were cut and are listed in the tech-debt tracker. - Step 5b: done (branch `lazyforeach-source-rebuilt`, stacked on #37): `lazyforeach-source-rebuilt` (a finding when a state change redraws the source, else a question); loop sources gain the field a getter returns as is, write facts mark a reassignment that repeats the initializer's call. The empty-`registerDataChangeListener` evidence clause was diff --git a/docs/exec-plans/tech-debt-tracker.md b/docs/exec-plans/tech-debt-tracker.md index 7185dfd..55fd599 100644 --- a/docs/exec-plans/tech-debt-tracker.md +++ b/docs/exec-plans/tech-debt-tracker.md @@ -27,33 +27,26 @@ the first load counts as before the first render, also one after an await over a field that starts with items (`= ['a', 'b']`), whose rows then keep the old items. A source reorders the array (an append moves its items) only through a sort, reverse or cut from the end written in its chain or a helper's `return`, not through a local. -- `foreach-index-key` (R1), source shapes. A source is read by its syntax only; these rarer shapes are left as they are: - - A condition that reads the array it picks (`this.a.length > 0 ? this.a : this.b`): an append to `a`, or a clear - (`this.a = []`, `pop`), switches to the other arm at the same positions, and goes quiet. - - A holder picked through a call (`this.trips.filter(…)[0].tags`): the path to the array starts after the call, so a - write of `this.trips[i].tags` goes quiet. - - Indexes in a path match whatever their text: `this.trips[0].tags.sort()` fires for a loop over - `this.trips[this.sel].tags` even when `sel` is never 0. - - A source that is an element of an array (`this.matrix[this.sel]`): `push` or `pop` on the outer array counts as a - move of the shown one and fires. - - An array literal of several items (`[...this.a, ...this.b]`, `[...this.a, 'footer']`) has no root: written in - place, any write of `a` fires, a copy too, and a move in a method is a finding, not a question; returned by a - method or getter, an append to `a` goes quiet. - - The tail of a `.concat(…)` is taken to appear once, at the end: an append to it goes quiet when the field also - comes earlier (`this.a.concat(this.a)`) or feeds the items before it (a filter reading it); it fires when a reorder - comes before the concat (`this.a.slice().reverse().concat(this.b)`); a move of it in a method is a finding, not a - question. A field that ends one arm and is shown alone in another (`c ? this.a.concat(this.b) : this.b`) counts as - an array with items after it, so an append to `b` fires. - - What a source shows is read one helper deep: a getter that returns another helper, or a derived source over a - helper call (`this.visible().slice().reverse()`), has no shown arrays, reorders or window ends. An append under a - reversing helper goes quiet; a copy, or a change of a window's bound, fires; a move in a method is a finding, not - a question. - - A write keeps an array's positions only when it names the array as the source does: `this.trip!.tags = - [...this.trip.tags, x]` and other spellings count as a move and fire. - - An object spread keeps the array only as `{ ...this.F, p: x }` with plain property names; `Object.assign`, another - spread or a computed name counts as replacing the holder and fires. - - A `null` write shows a fallback (`this.F ?? this.other`) when any `??` or `||` in the source, or in the method or - getter it calls, has `this.F` on its left, including one that doesn't decide what the source returns. +- `foreach-index-key` (R1), source shapes. A source is read by its syntax only, by the field it starts from; these + rarer shapes are left as they are: + - An array below a holder (`this.trip.tags`, `this.trips[this.sel].tags`) is judged by the holder field: a + reassignment of the holder fires, an object spread that keeps the array too (`{ ...this.trip, name: x }`); a write + below it (`this.trip.tags.sort()`, `this.trips[0].tags = …`) goes quiet. + - A source with no single root field: a conditional between two fields (`c ? this.a : this.b`), a fallback + (`this.F ?? []`), an array literal of several items (`[...this.a, ...this.b]`), a source over a helper call + (`this.visible().slice().reverse()`) or a getter that returns another helper. Its fields count as a selection: + written in place, a write of a field or one level below it fires, an append too; through a method or getter, a + write that keeps positions (append, clear, copy) goes quiet. The rules for every source still apply: under a + reorder an append fires, and a `.slice(0, n)` bound never counts. A move in a method is a finding, not a question. + A `null` or `undefined` write counts as a reassignment. + - Under `this.a.concat(this.b)` written in place, an append or a clear of `a` goes quiet though it moves the items + of `b`, and an append to `b` fires. + - The bound of a `.slice(0, n)` counts as a window end anywhere in the chain: under a later reorder or concat + (`this.F.slice(0, this.n).reverse()`), a change of `n` goes quiet. + - The `if` arms around the loop exclude a write in the other arm also inside an outer loop row, a @Builder called + more than once or a `Repeat` row, where another row or call takes that arm at the same time: it goes quiet. The + same holds for `lazyforeach-source-rebuilt`, which shares the arms. Reads in a `Repeat(…).each` or `.template` row + are not marked as inside a loop (`inForEach`), as before #37. - `&&` is not split into arms (`this.ready && this.a`). - R4 input kinds are V1 only and see whole-field writes of the typed text (`this.f = value`), in the onChange or one method only inputs use and the onChange hands the text to: a path write (`this.form.name = value`) is not followed, @@ -61,7 +54,8 @@ line, so another write of the field on the input's line is taken for typing. A write of the field in the input's own onChange that isn't the text (`value.slice(0, -1) + '*'`) counts as code setting it, so the finding says another handler sets the field. A constant set by code (`this.title = 'Untitled'`) counts as a reset, so an input that never - shows it is not asked about; a field rendered anywhere is not asked about either. + shows it is not asked about; a field rendered anywhere is not asked about either. The `$$` fix is offered also when + the onChange stores the text normalized (`this.f = value.trim()`), which `$$` would drop. - `selection-never-written` (R4) is V1 only and sees comparisons written in the ForEach/LazyForEach row itself: rows drawn by a `@Builder` (`this.Cell(item, index)`) and comparisons with a converted index (`index.toString()`, `String(index)`) are not followed. A write in a `set` accessor is not recorded, so a field set only through a setter