@stateward/core 1.2.0 → 1.2.2

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/ledger.js ADDED
@@ -0,0 +1,423 @@
1
+ import { sha1, summaryOf, summaryValue } from "./cache.js";
2
+ import { noRuleChecks, STATED_RULE_ID } from "./stated.js";
3
+ /**
4
+ * The reference ledger: every reference in a file to a declaration that states a trait an active
5
+ * rule proves, kept in the file's entry of the cache under the same fingerprint as its findings,
6
+ * keyed also by the traits it lists (`ledgerKey`). A rule marks the references it reads
7
+ * (`FileContext.read`); a proof reads every other one as not checked.
8
+ */
9
+ const LEDGER_PREFIX = "stateward/ledger:";
10
+ /** The trait a JSDoc tag states in the ledger: `@neverRejects`. */
11
+ export function tagTrait(tag) {
12
+ return `@${tag}`;
13
+ }
14
+ /** The traits the active rules prove, joined and sorted: what the ledger lists references for. */
15
+ export function provesOf(all) {
16
+ const joined = (pick) => [
17
+ ...new Set(all.flatMap((proves) => (proves === undefined ? [] : (pick(proves) ?? [])))),
18
+ ].sort();
19
+ return {
20
+ traits: joined((proves) => proves.traits),
21
+ returns: joined((proves) => proves.returns),
22
+ made: joined((proves) => proves.made),
23
+ holders: joined((proves) => proves.holders),
24
+ flows: {
25
+ produced: joined((proves) => proves.flows?.produced),
26
+ decided: joined((proves) => proves.flows?.decided),
27
+ escaped: joined((proves) => proves.flows?.escaped),
28
+ },
29
+ tags: joined((proves) => proves.tags),
30
+ };
31
+ }
32
+ /**
33
+ * The rule that proves each tag trait: the first of `rules` (sorted by id) whose `proves.tags`
34
+ * lists the tag.
35
+ */
36
+ export function tagRulesOf(rules) {
37
+ const found = new Map();
38
+ for (const rule of [...rules].sort((a, b) => compareText(a.id, b.id))) {
39
+ for (const tag of rule.proves?.tags ?? []) {
40
+ if (!found.has(tagTrait(tag)))
41
+ found.set(tagTrait(tag), rule.id);
42
+ }
43
+ }
44
+ return found.size === 0
45
+ ? undefined
46
+ : Object.fromEntries([...found].sort(([a], [b]) => compareText(a, b)));
47
+ }
48
+ /** Every trait of `proves`, sorted and each once. */
49
+ export function ledgerTraits(proves) {
50
+ return [
51
+ ...new Set([
52
+ ...proves.traits,
53
+ ...proves.returns,
54
+ ...proves.made,
55
+ ...proves.holders,
56
+ ...proves.flows.produced,
57
+ ...proves.flows.decided,
58
+ ...proves.flows.escaped,
59
+ ...proves.tags.map(tagTrait),
60
+ ]),
61
+ ].sort();
62
+ }
63
+ /** The key of a file's ledger in its cache entry: it changes with the traits it lists. */
64
+ export function ledgerKey(proves) {
65
+ const { flows } = proves;
66
+ const lists = [proves.traits, proves.returns, proves.made, proves.holders];
67
+ // The key of a ledger without flows stays what it was before flows were listed.
68
+ const flowLists = [flows.produced, flows.decided, flows.escaped];
69
+ const flowed = flowLists.some((list) => list.length > 0) ? [...lists, ...flowLists] : lists;
70
+ // Nor does the key of a ledger without tags.
71
+ const keyed = proves.tags.length > 0 ? [...lists, ...flowLists, proves.tags] : flowed;
72
+ return `${LEDGER_PREFIX}${sha1(JSON.stringify(keyed))}`;
73
+ }
74
+ const FORMS = new Set([
75
+ "call",
76
+ "read",
77
+ "write",
78
+ "alias",
79
+ "import",
80
+ "export",
81
+ "argument",
82
+ "stored",
83
+ "returned",
84
+ "jsx-tag",
85
+ "jsx-attribute",
86
+ "type",
87
+ "computed",
88
+ "other",
89
+ "tag",
90
+ "produced",
91
+ "decided",
92
+ "escaped",
93
+ ]);
94
+ const VIAS = new Set([
95
+ "value",
96
+ "cast",
97
+ "any",
98
+ "overload",
99
+ "override",
100
+ "function-type",
101
+ "generic-call",
102
+ "indirect-call",
103
+ "spread",
104
+ "reflect",
105
+ "literal",
106
+ "for-of",
107
+ "derived",
108
+ "call",
109
+ "stopped",
110
+ ]);
111
+ function isVia(value) {
112
+ return typeof value === "string" && VIAS.has(value);
113
+ }
114
+ function isForm(value) {
115
+ return typeof value === "string" && FORMS.has(value);
116
+ }
117
+ function isRecord(value) {
118
+ return typeof value === "object" && value !== null && !Array.isArray(value);
119
+ }
120
+ function parseRef(value) {
121
+ if (!isRecord(value))
122
+ return undefined;
123
+ const { id, declaration, name, marker, trait, form, via, location, text } = value;
124
+ if (typeof id !== "string" ||
125
+ typeof declaration !== "string" ||
126
+ typeof name !== "string" ||
127
+ typeof marker !== "string" ||
128
+ typeof trait !== "string" ||
129
+ !isForm(form) ||
130
+ typeof text !== "string" ||
131
+ (via !== undefined && !isVia(via)) ||
132
+ !isRecord(location)) {
133
+ return undefined;
134
+ }
135
+ const { file, start, end } = location;
136
+ if (typeof file !== "string" || typeof start !== "number" || typeof end !== "number") {
137
+ return undefined;
138
+ }
139
+ return {
140
+ id,
141
+ declaration,
142
+ name,
143
+ marker,
144
+ trait,
145
+ form,
146
+ ...(isVia(via) ? { via } : {}),
147
+ location: { file, start, end },
148
+ text,
149
+ };
150
+ }
151
+ function isList(value) {
152
+ return Array.isArray(value);
153
+ }
154
+ function parseRefs(value) {
155
+ if (!isList(value))
156
+ return undefined;
157
+ const found = [];
158
+ for (const item of value) {
159
+ const one = parseRef(item);
160
+ if (one === undefined)
161
+ return undefined;
162
+ found.push(one);
163
+ }
164
+ return found;
165
+ }
166
+ /**
167
+ * The ledger of one file, read from its cache entry when it has it, else from the program (`read`
168
+ * gives the file's queries and source, and is only called then). A reference to a declaration of
169
+ * another file asks for that declaration (`declarationOf`), so the entry holds only while the
170
+ * declaring file is as it was: its offsets are in the ledger. `stored` is true when this call added
171
+ * it to `results`; a ledger of other traits is dropped then.
172
+ */
173
+ export function fileLedger(results, key, read, proves) {
174
+ const kept = results.get(key);
175
+ if (kept !== undefined) {
176
+ if (kept.summary === undefined)
177
+ return { refs: [], stored: false };
178
+ const parsed = parseRefs(summaryValue(kept.summary));
179
+ if (parsed !== undefined)
180
+ return { refs: parsed, stored: false };
181
+ }
182
+ const opened = read();
183
+ const refs = [];
184
+ if (opened !== undefined && ledgerTraits(proves).length > 0) {
185
+ const { types, sourceFile } = opened;
186
+ const file = sourceFile.fileName;
187
+ const asked = new Set();
188
+ const flows = proves.flows;
189
+ const listsFlows = flows.produced.length > 0 || flows.decided.length > 0 || flows.escaped.length > 0;
190
+ const found = [
191
+ ...types.statedReferencesIn(sourceFile, proves),
192
+ ...(listsFlows ? types.typedFlowsIn(sourceFile, proves) : []),
193
+ ];
194
+ for (const one of found) {
195
+ const start = one.node.getStart(sourceFile);
196
+ if (!one.declaration.startsWith(`${file}#`) && !asked.has(one.symbol.id)) {
197
+ asked.add(one.symbol.id);
198
+ types.declarationOf(one.symbol);
199
+ }
200
+ // A flow is named by its whole expression: one may start where a reference or another flow does.
201
+ const flow = one.via !== undefined;
202
+ refs.push({
203
+ id: flow ? `${file}#${String(start)}-${String(one.node.end)}` : `${file}#${String(start)}`,
204
+ declaration: one.declaration,
205
+ name: one.name,
206
+ marker: one.marker,
207
+ trait: one.trait,
208
+ form: one.form,
209
+ ...(one.via === undefined ? {} : { via: one.via }),
210
+ location: { file, start, end: one.node.end },
211
+ text: one.text,
212
+ });
213
+ }
214
+ refs.sort((a, b) => a.location.start - b.location.start ||
215
+ a.location.end - b.location.end ||
216
+ compareText(a.declaration, b.declaration) ||
217
+ compareText(a.trait, b.trait) ||
218
+ compareText(a.id, b.id));
219
+ }
220
+ for (const other of results.keys()) {
221
+ if (other.startsWith(LEDGER_PREFIX) && other !== key)
222
+ results.delete(other);
223
+ }
224
+ results.set(key, refs.length === 0
225
+ ? { findings: [] }
226
+ : {
227
+ findings: [],
228
+ summary: summaryOf(refs.map((ref) => ({
229
+ id: ref.id,
230
+ declaration: ref.declaration,
231
+ name: ref.name,
232
+ marker: ref.marker,
233
+ trait: ref.trait,
234
+ form: ref.form,
235
+ ...(ref.via === undefined ? {} : { via: ref.via }),
236
+ location: { ...ref.location },
237
+ text: ref.text,
238
+ }))),
239
+ });
240
+ return { refs, stored: true };
241
+ }
242
+ function compareText(a, b) {
243
+ return a < b ? -1 : a > b ? 1 : 0;
244
+ }
245
+ /** Whether a cache entry's key is a ledger's, not a rule's result. */
246
+ export function isLedgerKey(key) {
247
+ return key.startsWith(LEDGER_PREFIX);
248
+ }
249
+ /** A rule's marks with its id, for the run's ledger. */
250
+ export function withRule(ruleId, marks) {
251
+ return marks.map((mark) => ({ ruleId, ...mark }));
252
+ }
253
+ /** What a reference does, after its code: "(another name for it)". */
254
+ const FORM_WORDS = {
255
+ call: "a call",
256
+ read: "a read",
257
+ write: "a write",
258
+ alias: "another name for it",
259
+ import: "an import",
260
+ export: "an export",
261
+ argument: "given as an argument",
262
+ stored: "stored in an object or array literal",
263
+ returned: "returned",
264
+ "jsx-tag": "a JSX tag",
265
+ "jsx-attribute": "a JSX attribute",
266
+ type: "a type",
267
+ computed: "a computed key",
268
+ other: "a use",
269
+ tag: "the tag on its declaration",
270
+ produced: "a value of the type made here",
271
+ decided: "a decision by a value of the type",
272
+ escaped: "a write to an object that holds it",
273
+ };
274
+ /** Where the reader finds the ways a guarantee's rule reads: its page, when a rule proves it. */
275
+ function shownBy(ruleId) {
276
+ return ruleId === STATED_RULE_ID
277
+ ? "write it the way its pack's page shows"
278
+ : `write it the way \`stateward explain ${ruleId}\` shows`;
279
+ }
280
+ /** Why a place past where the file's scan stopped is not checked: the uses after it are not read. */
281
+ export function stoppedReason(ref) {
282
+ return `the file is too large to read past \`${ref.text}\`, so the uses of \`${ref.name}\` after it are not checked: split the file`;
283
+ }
284
+ /**
285
+ * "`w = watchPrices` (another name for it) is a use of `watchPrices` that stateward does not read
286
+ * for `Release`: write it the way `stateward explain ownership/resource-not-released` shows".
287
+ */
288
+ export function unreadReason(ref, ruleId) {
289
+ return `\`${ref.text}\` (${FORM_WORDS[ref.form]}) is a use of \`${ref.name}\` that stateward does not read for \`${ref.marker}\`: ${shownBy(ruleId)}`;
290
+ }
291
+ const RANK = {
292
+ irrelevant: 0,
293
+ decided: 1,
294
+ "handed-on": 2,
295
+ unchecked: 3,
296
+ };
297
+ /**
298
+ * One rule's word on a reference from all its marks: a place it cannot follow wins; a reference
299
+ * its project side settled is read, whatever the file side handed on.
300
+ */
301
+ function settled(marks) {
302
+ const unchecked = marks
303
+ .map((mark) => mark.outcome)
304
+ .filter((outcome) => outcome.kind === "unchecked")
305
+ .sort((a, b) => (a.reason < b.reason ? -1 : a.reason > b.reason ? 1 : 0));
306
+ if (unchecked[0] !== undefined)
307
+ return unchecked[0];
308
+ const read = marks.find((mark) => mark.outcome.kind === "decided" || mark.outcome.kind === "irrelevant");
309
+ if (read !== undefined)
310
+ return read.outcome;
311
+ return [...marks].sort((a, b) => RANK[b.outcome.kind] - RANK[a.outcome.kind])[0]?.outcome;
312
+ }
313
+ export function indexLedger(ledger) {
314
+ const byDeclaration = new Map();
315
+ for (const ref of ledger.refs) {
316
+ const key = `${ref.declaration}\u0000${ref.trait}`;
317
+ const list = byDeclaration.get(key) ?? [];
318
+ list.push(ref);
319
+ byDeclaration.set(key, list);
320
+ }
321
+ const marksOf = new Map();
322
+ for (const mark of ledger.marks) {
323
+ const key = `${mark.ruleId}\u0000${mark.ref}\u0000${mark.trait}`;
324
+ const list = marksOf.get(key) ?? [];
325
+ list.push(mark);
326
+ marksOf.set(key, list);
327
+ }
328
+ return {
329
+ traits: new Set(ledger.traits),
330
+ refsOf: (declaration, trait) => byDeclaration.get(`${declaration}\u0000${trait}`) ?? [],
331
+ uncheckedOf(guarantee, refs) {
332
+ const places = [];
333
+ for (const ref of refs) {
334
+ const outcome = settled(marksOf.get(`${guarantee.ruleId}\u0000${ref.id}\u0000${ref.trait}`) ?? []);
335
+ // Past the flow scan's budget nothing after this place is listed: no mark makes it read.
336
+ const reason = ref.via === "stopped"
337
+ ? stoppedReason(ref)
338
+ : outcome === undefined
339
+ ? unreadReason(ref, guarantee.ruleId)
340
+ : outcome.kind === "unchecked"
341
+ ? outcome.reason
342
+ : outcome.kind === "handed-on"
343
+ ? `\`${ref.text}\` is passed to ${outcome.to}, which stateward does not check for \`${ref.marker}\`: ${shownBy(guarantee.ruleId)}`
344
+ : undefined;
345
+ if (reason !== undefined)
346
+ places.push({ location: ref.location, reason });
347
+ }
348
+ return places;
349
+ },
350
+ };
351
+ }
352
+ /** The forms that run nothing: a declaration only they name is unused. */
353
+ function runsNothing(ref) {
354
+ return ref.form === "import" || ref.form === "export" || ref.form === "type";
355
+ }
356
+ /**
357
+ * The guarantee a JSDoc tag states (`RuleProves.tags`), proven by `ruleId`: its places are the
358
+ * tag itself (the declaration's body) and every reference that runs something.
359
+ */
360
+ function tagGuarantee(first, refs, location, ruleId) {
361
+ const tag = first.trait.slice(1);
362
+ return {
363
+ guarantee: first.trait,
364
+ source: { kind: "tag", tag },
365
+ marker: first.marker,
366
+ name: first.name,
367
+ declaration: first.declaration,
368
+ location,
369
+ ruleId,
370
+ promise: `\`${first.name}\` keeps what \`@${tag}\` states, in its own code and at every use`,
371
+ covers: { one: "place", many: "places" },
372
+ covered: refs
373
+ .filter((ref) => ref.declaration === first.declaration && ref.trait === first.trait && !runsNothing(ref))
374
+ .map((ref) => ({ name: `\`${ref.text}\``, location: ref.location })),
375
+ };
376
+ }
377
+ /**
378
+ * A guarantee for each declaration the ledger has references to and no plugin or core scan lists
379
+ * (by its id and trait): it reads "not checked" (never "unused", never "proven") until a rule lists
380
+ * it. A tag trait's declaration is listed for the rule that proves the tag (`tagRules`).
381
+ */
382
+ export function ledgerGuarantees(refs, listed, tagRules = {}) {
383
+ const known = new Set(listed.map((one) => `${one.declaration}\u0000${one.guarantee}`));
384
+ const found = [];
385
+ for (const ref of refs) {
386
+ const key = `${ref.declaration}\u0000${ref.trait}`;
387
+ if (known.has(key))
388
+ continue;
389
+ known.add(key);
390
+ const at = ref.declaration.lastIndexOf("#");
391
+ const start = Number(ref.declaration.slice(at + 1));
392
+ const location = { file: ref.declaration.slice(0, at), start, end: start };
393
+ // Core lists a declaration it found by its written type from where it starts: a property
394
+ // with a modifier (`static x: Owned<…>`) is listed there, and the ledger names it at its name.
395
+ const scanned = listed.some((one) => one.ruleId === STATED_RULE_ID &&
396
+ one.guarantee === ref.trait &&
397
+ one.location.file === location.file &&
398
+ one.location.start <= start &&
399
+ start <= one.location.end);
400
+ if (scanned)
401
+ continue;
402
+ const prover = tagRules[ref.trait];
403
+ if (prover !== undefined) {
404
+ found.push(tagGuarantee(ref, refs, location, prover));
405
+ continue;
406
+ }
407
+ found.push({
408
+ guarantee: ref.trait,
409
+ source: { kind: "marker" },
410
+ marker: ref.marker,
411
+ name: ref.name,
412
+ declaration: ref.declaration,
413
+ location,
414
+ ruleId: STATED_RULE_ID,
415
+ promise: "nothing yet: no rule proves it",
416
+ covers: { one: "place", many: "places" },
417
+ covered: [],
418
+ unchecked: [{ location, reason: noRuleChecks(ref.marker) }],
419
+ });
420
+ }
421
+ return found;
422
+ }
423
+ //# sourceMappingURL=ledger.js.map
package/dist/release.js CHANGED
@@ -145,6 +145,8 @@ export function describeTraitSource(source) {
145
145
  return `the config's facts for ${source.package}`;
146
146
  case "shipped":
147
147
  return `stateward's facts for ${source.package}`;
148
+ case "tag":
149
+ return `the JSDoc tag \`@${source.tag}\``;
148
150
  default: {
149
151
  const unreachable = source;
150
152
  return unreachable;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Calls of the platform that do not throw on values their types allow: the closed list the proofs
3
+ * share. An entry holds only on the platform's own types, as the type checker sees them: the value
4
+ * a method is called on is typed by the platform's type itself (not an interface or a class of the
5
+ * project, and not a type the project extends), and the arguments' types make the call safe
6
+ * (`String(x)` on a primitive, `join` on an array of primitives). Every other call of the platform
7
+ * or a package may throw (`new URL("x")`, `[].reduce(add)`, `JSON.parse(text)`, `n.toString(36)`,
8
+ * `headers.set(…)`). A function of the project is not on the list: a proof reads it, or counts it
9
+ * as a call that may throw. Core knows no library; these are the language's own built-ins.
10
+ */
11
+ import ts from "typescript";
12
+ import type { TypeQueries } from "./types.js";
13
+ /**
14
+ * Whether a `for…of` over an expression runs no code of the project and cannot throw: over the
15
+ * platform's array, a string, or an iterator of a `Map` or `Set` (`for (const v of m.values())`).
16
+ */
17
+ export declare function iteratesPlainly(node: ts.Expression, types: TypeQueries): boolean;
18
+ /**
19
+ * Whether a call or `new` is on the closed list of the platform's calls that do not throw, on the
20
+ * platform's own types: `console.log(…)`, `Math.max(a, b)` on numbers, `Object.keys(…)` on a
21
+ * known type, `new Map()`, `list.push(…)` on an array, `String(x)` on a primitive, `d.getTime()`,
22
+ * `n.toFixed(2)`, `Array.from(xs)` on an array, a string method on a branded string. The caller checks what a
23
+ * callback given to the call does.
24
+ */
25
+ export declare function isSafePlatformCall(node: ts.CallExpression | ts.NewExpression, types: TypeQueries): boolean;
26
+ //# sourceMappingURL=safe-calls.d.ts.map