diff --git a/CLAUDE.md b/CLAUDE.md index a5055742..788795fb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -91,6 +91,14 @@ packages/vocabulary/ @codegraph/vocabulary — the words of the model's NAMES and SVG; the carriers lookup (which names carry a word). Pure computation. Its `./cloud` entry is the layout alone and imports nothing: the one value a frontend may take. +packages/dataop/ @codegraph/dataop — the model LOWERED into a Specy Data & + Operation model (`.dataop`, `observed` level): `lower(graph)` + → a typed DataOpModel (structs, globals, operations and their + clauses, each with its anchor), `print(model)` → the text. + States what the model holds and nothing else: `opaque`, `?` + or a finding where it holds no fact. Per-language type + tables are data. A projection, never read back. Pure + computation (PLAN §26, docs/dataop.md). packages/insights/ @codegraph/insights — the bottom-up EXPLANATION walk: units (operations → types → modules), SCC-condensed walk order, context packs, prompts, Merkle fingerprints, plan/run, the @@ -153,7 +161,7 @@ fixtures/ Reference corpora + expected model.jsonl snapshots. ### Hard boundaries (convenience does not override architecture) -- **`core`, `analyzer`, `city`, `navigator` and `vocabulary` never import Three.js or React** +- **`core`, `analyzer`, `city`, `navigator`, `vocabulary` and `dataop` never import Three.js or React** — they must run in Node with no DOM. `viz` reads the city model and `navigator-ui` the navigator model; neither mutates its model and neither re-derives graph facts the analyzer already computes. @@ -315,6 +323,10 @@ node scripts/homebrew/render.mjs --version X.Y.Z --sums SHA256SUMS [--npm-sha256 ./bin/codegraph city model.jsonl --layout --out city.json # the artifacts alone ./bin/codegraph navigator model.jsonl --out navigator.json ./bin/codegraph vocabulary model.jsonl [--level module|type] [--scope ID] [--drift FILE] [--svg FILE] # the names' words +./bin/codegraph dataop model.jsonl [--out FILE] [--name NAME] [--boundaries FILE] [--scope SEL] # a Specy Data & Operation +# model (.dataop, observed): structs, globals, operations with depends on / uses / reads / writes / errors; the summary of +# what was not lowered on stderr; docs/dataop.md. Snapshot: fixtures/java/expected/model.dataop +# (CODEGRAPH_UPDATE_SNAPSHOTS=1 pnpm --filter @codegraph/dataop test fixtures) ./bin/codegraph serve model.jsonl --height vocabulary:order --height-scale sqrt # where one word lives, in the city ./bin/codegraph explain model.jsonl --src DIR --dry-run # the walk plan, no call ./bin/codegraph explain model.jsonl --src DIR --estimate --price-in 0.10 --price-out 0.60 # tokens in/out + cost, no call diff --git a/METAMODEL.md b/METAMODEL.md index 447202ee..16ba28c4 100644 --- a/METAMODEL.md +++ b/METAMODEL.md @@ -69,8 +69,8 @@ cross-validation meaningful. It is deliberately *not* the same as sorting the rendered ids as strings, where `/` and `.` are ordinary characters. **Relations:** every reference between concepts (edge endpoints, `parent`, -`children`, `attachedTo`, `declaredType`, `candidates`) identifies an entity by -its natural key. The v1 file format spells each of those as the rendered id +`children`, `attachedTo`, `declaredType`, `candidates`, and the ids inside a +Literal or a TypeExpr, §1.6–§1.7) identifies an entity by its natural key. The v1 file format spells each of those as the rendered id string (`EntityId` in core); an encoding is free to spell them otherwise — M6 uses file-scoped integer surrogates — as long as they resolve to the same key. A surrogate is **not** identity and never crosses a file boundary. @@ -156,6 +156,38 @@ Two rules: **Relations:** carried by Entities via `TWithValue` (§3.6) and by `annotationUse` edges (§4). +### 1.7 TypeExpr + +The **type a declaration writes**, as a tree: `List`, `int[]`, +`String?`. `declaredType` (§3.4) keeps only the erased head, as a reference — +the raw `List`, nothing for a primitive or an array — so the written type was +not in the model before contract 1.2.0 (MM-7). A tagged union whose tags are a +closed core-owned vocabulary (MM-3), built as Literal is: + +| Form | Shape | Notes | +|---|---|---| +| `named` | `{k: "named", type: EntityId, args?: TypeExpr[]}` | a declared type or a stub, with its written type arguments in order. `args` absent when none is written, never empty | +| `primitive` | `{k: "primitive", name: string}` | the language's own word: `int`, `long`, `boolean`, `char` | +| `array` | `{k: "array", of: TypeExpr}` | | +| `nullable` | `{k: "nullable", of: TypeExpr}` | where the language writes it (`T?`, `T \| null`); never inferred from an annotation | +| `function` | `{k: "function", params: TypeExpr[], returns?: TypeExpr}` | `returns` absent = the function returns no value | +| `union` | `{k: "union", of: TypeExpr[]}` | written alternatives, in written order; at least two | +| `variable` | `{k: "variable", name: string}` | a type parameter | +| `unevaluated` | `{k: "unevaluated", source: string}` | a written type the extractor did not structure (a wildcard, an intersection). The source text is still a fact, as for a Literal | + +Three rules: + +- **A type expression is what is written, never what is inferred.** No + `typeExpr` on a `var`, on an untyped parameter, on a `void` return. +- **Ids inside count for closure** (§8a), exactly as a Literal's: a `named` + type resolves to a declared entity or a stub, and in the M6 encoding it is a + file-scoped surrogate, so a dangling one is unwritable. A type the extractor + cannot name is `unevaluated`, never a fabricated id. +- **A value never replaces a dependency.** The `reference` edges a written type + emits — its head, each of its arguments — are still emitted. + +**Relations:** carried by Entities via `TTypedEntity.typeExpr` (§3.4). + --- ## 2. Entity @@ -193,7 +225,7 @@ Traits marked *(marker)* contribute **no attributes**: they declare a capability whose data lives in `edges[]` (edges are stored once, outgoing direction only — see §4). -![The nineteen traits around the entity that composes them, by family; a dashed box is a marker trait](website/assets/diagrams/traits-metamodel.svg) +![The twenty traits around the entity that composes them, by family; a dashed box is a marker trait](website/assets/diagrams/traits-metamodel.svg) The whole vocabulary on one sheet: an entity composes at most one of each trait, a dashed box is a marker, and the three red dots are the composition of @@ -244,7 +276,7 @@ attachment distinction needs. Only the serialized key goes, in M6. | `TType` | `isStub: boolean` | any type-like entity: class, interface, struct, enum, protocol, PHP/Rust trait | | `TWithInheritances` | *(marker)* — see `Inheritance` edges | multiple inheritance = N edges (Python). Absent from Go/Rust profiles — that absence is profile information, not a gap | | `TWithImplements` | *(marker)* — see `InterfaceImplementation` edges | | -| `TTypedEntity` | `declaredType?: EntityId` | optional even when the trait is present: absent value in JS/Python/Clojure, C# `var`, inferred Go/TS/Rust | +| `TTypedEntity` | `declaredType?: EntityId`, `typeExpr?: TypeExpr` (§1.7) | both optional even when the trait is present: absent value in JS/Python/Clojure, C# `var`, inferred Go/TS/Rust. `declaredType` is the erased head, a reference; `typeExpr` (since contract 1.2.0, MM-7) the type as written, a tree. Neither replaces the other, and neither replaces the `reference` edges the written type emits | ### 3.5 Behavior @@ -255,6 +287,9 @@ attachment distinction needs. Only the serialized key goes, in M6. | `TWithLocalVariables` | `localVariables: EntityId[]` | | | `TWithInvocations` | *(marker)* — see `Invocation` edges | outgoing only; incoming is derived by the analyzer, never stored | +An invocable that needs an instance — a Java instance method, a constructor — +carries the marker `TWithReceiver` (§3.6), as an instance field does. + ### 3.6 Structure | Trait | Attributes contributed | Notes | @@ -262,6 +297,17 @@ attachment distinction needs. Only the serialized key goes, in M6. | `TStructural` | *(marker)* — value holder | attributes, variables, parameters, Clojure vars. Legal target of `Access` edges | | `TWithAccesses` | *(marker)* — see `Access` edges | outgoing only | | `TWithValue` | `value: Literal` (§1.6) | the entity's declaration-site constant value: a Java `static final` constant initializer, an annotation element's `default`, a TS enum member's value, a Clojure def'd constant. Optional wherever licensed — an attribute whose initializer is not a compile-time constant simply carries no value, and absence means "not constant", never "empty" | +| `TWithReceiver` | *(marker)* | the entity is evaluated against an instance of the type it is written in or attached to: a Java instance field, instance method, constructor. Since contract 1.2.0 (MM-8) | + +**The receiver marker (MM-8).** Java's `attribute` kind has no word for +static: `Order.MAX_LINES` and `Order.channel` differ only by a constant value, +and an instance method and a static one only by what they may touch. +`TWithReceiver` says it, on the kinds a profile can decide it for, and is +licensed optional there. **In a profile that licenses it on a kind, absence +means "no receiver"** — a static member, an enum constant; in a profile that +does not, absence means nothing. A lambda never carries it: it is evaluated +against what it captures, not against an instance of its own. The `receiver` +of an `access` edge (§4) is its counterpart on the edge. ### 3.7 The composition that motivates the whole design @@ -373,6 +419,20 @@ two edges, ordered by member after provenance (absent first). A consumer reads Decision and evidence: `docs/model-metamodel.md` MM-6. Not to be confused with the navigator's dependency `member`, which is the corpus entity a row reaches. +**The receiver of an access (MM-8).** An `access` edge may carry +`receiver: "self" | "other"`: `self` when the target is reached through the +accessor's own receiver, written (`this.lines`) or implied (`lines`); `other` +through any other expression (`other.lines`). It is absent when the target has +no receiver (a static field, a local) or when the extractor does not say. It is +legal on `access` only — core's schema refuses it elsewhere — and only when the +target is **not** a stub: a stub has no members (§6), so nothing in the model +says the field reached needs an instance; the integrity rule (`codegraph +validate`, rule `receiver`) reports one that is. Like `member`, it is part of +the edge: `this.lines = other.lines` is a `self` write and an `other` read at +one site — two facts — so it orders edges after `member`, absent first. A +consumer reads `edge.receiver`; `model.db` holds it in `edge.receiver` and the +`dep` view. Decision and evidence: `docs/model-metamodel.md` MM-8. + ![The edge in the middle: its eleven kinds in four families, its four provenance values, the entities at its ends, its anchor and the profile that licenses it](website/assets/diagrams/edges-metamodel.svg) The relation on one sheet: an edge has exactly one kind, so at most one of a @@ -406,7 +466,7 @@ Eleven kinds, in four families by what an edge connects. | Kind | From → To | Extra attributes | Notes | |---|---|---|---| | `invocation` | Invocable → Invocable | `candidates`, `member` (to a stub) | uncertain dispatch → `provenance: dynamic-candidate` + candidates list | -| `access` | Invocable → Structural | `isRead: bool`, `isWrite: bool`, `member` (to a stub) | field/variable reads and writes | +| `access` | Invocable → Structural | `isRead: bool`, `isWrite: bool`, `member` (to a stub), `receiver` (not to a stub) | field/variable reads and writes | | `throws` | Invocable → Type (exception) | | a written `throw` statement whose static exception type resolved; the anchor is the throw SITE — the evidence a guard clause leaves. A declared propagation clause (Java `throws E`) is a plain `reference`, not this. Distinct from `reference` so failure exits are selectable without reading the target's kind, which a stub target cannot answer | #### References @@ -603,7 +663,11 @@ already knows the per-frame sha. The integrity properties a model must satisfy, whatever encodes it: - **closure** — every reference resolves to a declared entity or a stub (§4, - §6), the ids inside `Literal` values included (§1.6); + §6), the ids inside `Literal` values and `TypeExpr` trees included (§1.6, + §1.7); +- **member and receiver legality** — an edge's `member` only on an + `invocation`, `access` or `reference` to a stub, its `receiver` only on an + `access` to an entity that is not one (§4); - **no self-reference** — `from ≠ to` on every edge; - **provenance set** on every edge, from the closed set of §1.3; - **profile validity** for every entity (§5); diff --git a/PLAN.md b/PLAN.md index 87d5e9a2..857c5f87 100644 --- a/PLAN.md +++ b/PLAN.md @@ -2736,7 +2736,7 @@ under one command-line contract (§13.5, schemas/README.md §8) exactly so this could be true: the app needs to know nothing about them but that contract and the file extensions they claim. -Locked decisions, each with its reason (the delta table in §27 repeats them): +Locked decisions, each with its reason (the delta table in §28 repeats them): - **Tauri is the shell, not a runtime.** Window, native menu, folder dialog, drag-and-drop, sidecar lifecycle, bundling, signing and notarization. No @@ -3642,7 +3642,7 @@ file without one of them lying, so they do not share one: | will not open | degrade to the `.jsonl`, silently | a usage error naming the file; never overwritten | | committed / shared | never | never — the JSONL export is what is committed, diffed and handed to Specy | -Locked decisions, each with its reason (the delta table in §27 repeats them): +Locked decisions, each with its reason (the delta table in §28 repeats them): - **The db is the working copy; the JSONL becomes its deterministic export.** `.insights.jsonl` keeps its format, its byte-determinism and its @@ -8859,7 +8859,463 @@ asks for anchors. - The Navigate panel showing claims, and choosing among several walks' stores. - Any path from a claim into `model.jsonl`. -## 26. Milestones +## 26. Phase 23 — The Data & Operation model: a code graph lowered into Specy's `.dataop` (M25) + +> Decisions taken by the owner on 2026-11-30: a codegraph model is lowered into +> a Specy Data & Operation model at the `observed` level; the type expression +> (§26.2), the receiver marker and the receiver on an access (§26.3) are added +> to the metamodel; flows and contracts are not extracted, a walk writes them +> later (§26.7). The Specy side changed the same day, for this phase: seven +> changes to its metamodel and grammar (§26.1). Started 2026-11-30 on +> `feat/m25-dataop`. + +Specy's Data & Operation metamodel describes what data exists, what operations +exist over it, and what each operation needs and guarantees. It has two +conformance levels: `strict`, written by a designer, and `observed`, "lowered +from a code graph". Its trait table is this metamodel's without the `T` prefix, +and its rule that exactly two things are external-declarable is §6's rule that +exactly two things are stubbable. This phase writes the lowering. + +The reference on the Specy side is its `metamodels` repository: +`src/metamodels/DATA-OPERATION-METAMODEL.md` (the concepts) and +`src/grammars/data-operation.ebnf` (the syntax and its 29 numbered rules). No +parser of `.dataop` exists there yet. This phase therefore carries its own +check of what it prints (§26.6), and a parser is Specy's to write. + +**The rule of the phase: the lowering states what the model holds and nothing +else.** Where the model does not hold a fact, the output says so in the form +Specy gives it (`opaque`, `?`, a finding), and never guesses. The output is a +projection: it is never read back, and nothing of it enters `model.jsonl`. + +### 26.1 What Specy changed for this phase + +Seven changes, written into both Specy files on 2026-11-30. The lowering may +use each of them. + +| # | Change | What the lowering does with it | +|---|---|---| +| 1 | A name is bare (letters, digits, `_`) or quoted `@"…"`; `\"` and `\\` in strings; the case convention is checked under `strict` only | every name is printed as the code spells it, quoted when it is not a bare name or is a keyword of the grammar | +| 2 | `uses { … }`: the external structs and modules an operation calls into | an `invocation` whose target is a stub | +| 3 | `= opaque` and `= opaque "…"` as a global's initial value | a value holder with no `TWithValue`, or an `unevaluated` one | +| 4 | an operation needs an observable effect (a finding under `observed`); the declared errors of an `observed` model are the operation's own raise sites | `errors` is the `throws` edges and nothing else; nothing is invented to satisfy rule 5 | +| 5 | `on module` on a nested operation; `global` in a struct body; identity follows containment | a member with no receiver stays where it is written | +| 6 | `writes { param.field }`, `observed` only | a write on an instance that is not the receiver | +| 7 | `// FINDING: : ` with a closed list of codes; a provenance word on `// source:` | testimonies are written (`branching`, `blind-spot`); recomputable findings are left to a validator | + +### 26.2 MM-7 · A typed entity carries its type expression + +Measured on `fixtures/java` before this phase: a primitive-typed field +(`Money.cents`, `Basket.total`) has no `declaredType` at all; `Basket.lines` +is the raw `List`, its argument a separate `reference` edge; an array is its +component, since an array type is not an entity. So `amount: number`, +`lines: array` and `T?` cannot be written from the model, and +neither can an honest `opaque "java.util.Map"`: the written +text is not kept. + +- **The attribute.** `TTypedEntity` gains an optional `typeExpr: TypeExpr`. + `declaredType` is unchanged, in meaning and in bytes. +- **The value.** A closed tagged union, core-owned, built as `Literal` is + (METAMODEL.md §1.6): + + | Form | Shape | Notes | + |---|---|---| + | `named` | `{k: "named", type: EntityId, args?: TypeExpr[]}` | a declared type or a stub, with its written type arguments in order | + | `primitive` | `{k: "primitive", name: string}` | the language's own word: `int`, `long`, `boolean`, `char` | + | `array` | `{k: "array", of: TypeExpr}` | | + | `nullable` | `{k: "nullable", of: TypeExpr}` | where the language writes it (`T?`, `T \| null`); never inferred from an annotation | + | `function` | `{k: "function", params: TypeExpr[], returns?: TypeExpr}` | `returns` absent = no value | + | `union` | `{k: "union", of: TypeExpr[]}` | | + | `variable` | `{k: "variable", name: string}` | a type parameter | + | `unevaluated` | `{k: "unevaluated", source: string}` | a written type the extractor did not structure (a wildcard, an intersection); the text is still a fact | + +- **A type expression is what is written, never what is inferred.** No + `typeExpr` on a `var`, on an untyped parameter, on a `void` return. +- **Closure.** The ids inside count as an edge endpoint does and are surrogates + on the wire, so a dangling one is unwritable. A type the extractor cannot + name is `unevaluated`, never a fabricated id. +- **A value never replaces a dependency.** The `reference` edges a written type + emits today are still emitted. +- **The wire.** One key on the entity record; `SCHEMA_VERSION` 1.1.0 → 1.2.0 + (additive, optional: a 1.1.0 file decodes unchanged). `model.db` gains + `entity.type_expr` (JSON, as `value`); the store is a cache and is rebuilt. +- **Extractors.** Java in this phase. The others keep their bytes; each + profile note says the extractor does not emit it yet. + +### 26.3 MM-8 · A member that needs an instance says so + +Java's `attribute` kind has no word for static: `Order.MAX_LINES` and +`Order.channel` differ only by a constant value. Specy needs the difference +twice: a schema field or a global, an attached operation or one written +`on module`. And an `access` edge does not say whether the field was reached +through the receiver: `this.lines` and `other.lines` are one edge. + +- **The trait.** `TWithReceiver`, a marker: the entity is evaluated against an + instance of the type it is written in or attached to. Licensed, optional, on + the kinds a profile can decide it for. In a profile that licenses it on a + kind, absence means "no receiver"; in a profile that does not, it means + nothing. A Java instance field, instance method and constructor carry it; a + static member, an enum constant and a lambda do not. +- **The edge.** `access` gains an optional `receiver: "self" | "other"`: + `self` when the target is reached through the accessor's own receiver, + written or implied; `other` through any other expression. Absent when the + target has no receiver, or when the extractor does not say. Legal only when + the target is not a stub. Whether it takes part in an edge's canonical order + is decided as M24a decided `member`: a `self` and an `other` access from one + operation to one field are two facts. +- **The wire.** The marker is one more name in the trait dictionary; `receiver` + one key on the `x` record. Same version step as §26.2; `model.db` gains + `edge.receiver`. +- **The log.** `docs/model-metamodel.md` gains MM-7 and MM-8; METAMODEL.md + §3.4, §3.5/§3.6 and §4 each gain their paragraph, and the trait count and + the two generated diagrams follow. + +### 26.4 The lowering: `@codegraph/dataop` + +A model package beside `city`, `navigator` and `vocabulary`: pure computation +over the analyzer's graph, no DOM, no I/O. Two functions and a value between +them: `lower(graph, options)` returns a `DataOpModel` (modules, external +declarations, structs, globals, operations, each with its anchor and its +findings), and `print(model)` returns the `.dataop` text. Everything a rule +below needs is read from traits, edges and keys, never from a parsed id. + +**Declarations.** + +| Model | `.dataop` | Notes | +|---|---|---| +| a non-stub `TModule` | `module` | named by its key's module component, segment by segment | +| a stub `TModule`, a stub `TType` | `external module`, `external struct` | only those the text references; a parentless stub is declared at model level | +| a named non-stub `TType` | `struct` | named by its symbol; a nested type keeps its path as one quoted name (`@"Basket.Line"`), since a struct is written at module level only | +| a nameless `TType` | nothing | its invocables fold into the nearest named operation, as lambdas do | +| a `TStructural` child of a type, with a receiver | a schema field | fields of corpus supertypes (`inheritance`, `embedding`, transitively) are flattened in, each with its own anchor; a `// NOTE:` names the supertypes, since Specy has no inheritance | +| a `TStructural` child of a type, without a receiver | a `global` in the struct | initial value from `TWithValue` when it is JSON-like, `opaque "…"` for `unevaluated`, bare `opaque` otherwise | +| a `TStructural` child of a module | a `global` at module level | | +| a named `TInvocable` | an `operation` | nested where it is written; attached to that struct with a receiver, `on module` without; `on Struct` when `attachedTo` differs from `parent` | +| a constructor (a nameless invocable whose parent is a type) | `operation new(…): Struct on module` | overloads told apart by their parameter types; its writes to the instance it builds are not declared | +| any other nameless invocable | nothing | its outgoing edges fold into the nearest named enclosing operation | + +Where a profile does not license `TWithReceiver`, every field of a type is a +schema field and every method is attached: the fallback is stated once in the +output's header comment. + +**Types.** From `typeExpr`, through one table per language held as data +(which primitives and which stub types are `string`, `number`, `boolean`; +which generic stubs are a sequence; which are an optional): + +| `typeExpr` | `.dataop` | +|---|---| +| `primitive`, or `named` on a scalar of the table | `string`, `number`, `boolean` | +| `named` on a sequence of the table with one argument, `array` | `array` | +| `named` on an optional of the table, `nullable` | `T?` | +| `named` with no argument | a struct reference, qualified across modules | +| `function` | `(T, U) -> R`, `void` when nothing is returned | +| anything else (`named` with other arguments, `union`, `variable`, `unevaluated`) | `opaque ""` | +| no `typeExpr`: `declaredType` present | a struct reference to it (the erased head: all the model knows) | +| neither | `opaque "?"` | + +**Clauses.** One edge kind each, after the fold of nameless invocables. + +| Clause | From | +|---|---| +| `errors` | `throws` edges: the operation's own raise sites, named by the exception type | +| `depends on` | `invocation` to a corpus invocable; `dynamic-candidate` and every `candidates` entry are written `?` | +| `uses` | `invocation` to a stub: the external struct, or the external module when the stub is one | +| `reads`, `writes` | `access` by `isRead` / `isWrite`: a global by its path; `_.field` for `receiver: self`; `param.field` in `writes` for `receiver: other` when exactly one parameter is typed by the field's owner, and a `blind-spot` finding when none or several are; a read through `other` is not declared | + +Without `receiver` on the edge, an access to a field of the operation's own +struct (or of a flattened supertype) is read as `self`, any other as `other`. + +**Entries.** `entry` on every operation the boundary rules (§25.2) put in the +entry inventory, when a rules file is given; none otherwise. The mark is firm: +a rule is a declaration-site fact. + +**Evidence and findings.** `// source: file:start-end` on every declaration. +`// FINDING: branching: cyclomatic N` on an operation whose `cyclomatic` is +above 1. Recomputable findings are not written. + +**Order.** Canonical: modules, then within each, structs, globals and +operations by natural key. Two runs over one model print the same bytes. + +### 26.5 `codegraph dataop` + +```bash +codegraph dataop model.jsonl [--out FILE] [--name NAME] [--boundaries FILE] [--scope SELECTOR] +``` + +Prints the `.dataop` text (stdout, or `--out`). `--name` is the model's name +(default: the model root's last segment, made kebab-case). `--boundaries` +takes a `codegraph.boundaries/1` file or a shipped stack name, as +`analyze --report entrypoints` does. `--scope` restricts the modules lowered +with the analyzer's selectors; what falls outside becomes external. A summary +on stderr counts what was lowered and what was not (opaque types, folded +invocables, accesses not declared). + +### 26.6 Checking the output without a parser + +Specy has no `.dataop` parser, so three properties stand in for one, each run +on every fixture model that lowers: + +- **Lexical.** A test-side lexer written from the EBNF's token rules accepts + every token of the printed text, braces balance, and every name that is not + a bare identifier or is a grammar keyword is quoted. +- **Closure.** Every reference in the `DataOpModel` resolves to a declaration + of the model or to an external declaration it prints (Specy's rule 9). +- **Agreement with the graph.** Every `depends on`, `uses`, `reads`, `writes` + and `errors` item is backed by at least one edge of the right kind from the + operation or from an invocable folded into it, and every such edge is either + declared or counted in the summary. + +### 26.7 What is not lowered + +States, contracts (`requires`, `ensures`), flows, `::` descriptions, lineage +and domain links. A flow needs the order of calls, the names bound to their +results and the arguments passed; the model holds the first to the line and +neither of the others, and it will not: def-use is an intermediate +representation, not a dependency graph. These are a walk's to write, bottom-up, +with the clauses as context, and Specy's rule 18 (a flow agrees with its +clauses) is then a mechanical check of the answer. That walk definition is the +next phase, not this one. + +### 26.8 Milestone split — four steps, each with its verification + +1. **M25a · the contract.** MM-7 and MM-8 in core: `TypeExpr`, `typeExpr`, + `TWithReceiver`, `receiver`; `SCHEMA_VERSION` 1.2.0; `schemas/` + regenerated; the JSONL codec with surrogates inside a type expression; the + closure and legality checks; `model.db`; the Java profile licensing the + marker; METAMODEL.md, `docs/model-metamodel.md`, the generated diagrams. + *Verified by:* a 1.1.0 file decodes unchanged; every fixture model of every + extractor is byte-identical before and after; the property suite green; a + dangling id inside a type expression is unwritable. + + **As built** (2026-11-30, on `feat/m25-dataop`). The decisions are MM-7 and + MM-8 in `docs/model-metamodel.md`; in short: + - `TypeExpr` is `packages/core/src/type-expr.ts`, `$defs/TypeExpr` in + `schemas/e.record.schema.json`. One canonical spelling per written type: + a present `args` is non-empty, a `union` has at least two members, and + inside a tree the keys are written `k` first, then the form's in table + order, whatever order the producer built them in. One walk + (`mapTypeExpr`) turns ids into surrogates and back, so the encoder and + the decoder cannot disagree on where a reference is. On the entity + record `typeExpr` follows `declaredType`. + - `receiver` is in the canonical order, as `member` is: the last + tiebreak, after `member`, absent first, then code units (`other` before + `self`), so `this.x = other.x` stays two edges in one order. On the + record it follows `isWrite`. Java's `AccessKey` is hand-listed and must + take it in M25b; no other producer emits one. + - Legality: core's `Edge` schema refuses `receiver` on every kind but + `access`; `receiverViolations` (`codegraph validate`, rule `receiver`, + codes `receiver-kind`, `receiver-target-stub`) refuses it on an access + to a stub. `TWithReceiver` sits in the Structure family (§3.6), after + `TWithAccesses` in the trait enum. + - The Java profile licenses `TWithReceiver` optional on `attribute`, + `method` and `constructor`; its note scopes "absence means no receiver" + to a model whose header states 1.2.0 or later, since the released + extractor writes 1.1.0 and carries the marker nowhere. The ten other + profiles say MM-7 and MM-8 are not emitted. + - `model.db` version 6: `entity.type_expr` (JSON, surrogates inside, as + `value`), `edge.receiver`, and a `receiver` column on the `dep` view. + - Verified: no file under `fixtures/` moved (24 snapshots, sha256 before + and after), each re-encodes byte for byte through core, and a 1.1.0 and + a 1.0.0 file decode keeping the version they state. + - Left for later: no JSON selector term reads `receiver`, and `validate` + counts no receiver coverage (MM-6 counts members); no extractor writes + 1.2.0 yet. +2. **M25b · the Java extractor.** `typeExpr` on every typed entity whose type + is written, `TWithReceiver`, `receiver` on accesses. *Verified by:* the + fixture asserts, hand-counted, a primitive, a generic with its argument, an + array, a wildcard as `unevaluated`, a static and an instance member, a + `this` and a non-`this` access; the snapshot regenerated and every snapshot + derived from it; PetClinic and commons-lang `validate`-clean. + + **As built** (2026-11-30, on `feat/m25-dataop`, uncommitted). The rulings + are in the Java profile's notes; in short: + - `typeExpr` (`TypeExprs`, `model/TypeExpr`) on fields, parameters, locals, + method returns, record components and explicitly typed lambda + parameters. `named` takes the id `declaredType` and the edges take; a + varargs parameter is an `array`; a wildcard, an intersection, an outer + type's arguments and an unnameable type are `unevaluated` with their + source text, whitespace folded. None on `var`, an implicit lambda + parameter, `void`, a constructor; a record's implicit canonical + constructor keeps its components' written types. Closure: the type + expression never feeds stub synthesis (the stub set is unchanged); a + `named` node nothing declares degrades to `unevaluated` after pass 4 + (none on the fixture or PetClinic). + - `TWithReceiver` (`Receivers`, shared by both passes): instance fields and + record components, instance methods (abstract, default and annotation + elements included: an element is read on an annotation instance), every + constructor. Not: static members, enum constants, interface and + annotation-type fields, lambdas and anonymous classes. + - `receiver`: `self` through the innermost enclosing type's own `this` + (written, implied, `super.x`, inherited; a lambda's `this` is its + method's); `other` otherwise, an inner or anonymous class reaching its + outer instance included; absent on a static or stub target. In `Edge`, + its comparator after `member`, the writer after `isWrite`, and + `AccessKey`. + - The fixture: one source line moved, `archive(java.util.List)` → + `List`, so the wildcard case costs no entity or edge; + with the new keys and the marker stripped, the snapshot equals the 1.1.0 + one record for record. `TypeExprAndReceiverTest` pins the hand counts + (96 of 105 typed entities carry a `typeExpr`; 33 accesses: 29 `self`, + 1 `other`, 3 none). + - Regenerated: `model.jsonl`, `model.metrics.jsonl`, the explain goldens + (`java`, `java-scope-order`, `java-max-scc-1`: the archive unit, its type + and its module, by the source line). Core's decoder now places + `receiver` where the `Edge` schema does, so a decoded and a parsed edge + agree key for key. + - PetClinic: 460 of 590 typed entities carry a `typeExpr` (5 `unevaluated` + nodes, all `?`); 289 `TWithReceiver`; of 371 accesses 183 `self`, 46 + `other`, 142 none. commons-lang: no checkout on this machine, not run. +3. **M25c · the lowering and the command.** `@codegraph/dataop` and + `codegraph dataop`, developed against hand-built graphs so that it does not + wait on M25b. *Verified by:* the three properties of §26.6; unit tests for + each row of §26.4's tables; the boundary test that the package imports + neither a frontend nor a provider. + + **As built** (2026-11-30, on `feat/m25-dataop`, uncommitted). + `packages/dataop`: `lower(graph, {name, entries, candidateEntries, scope})` + → `DataOpModel` (modules, model-level externals, a per-language header + note, a LEDGER of every `invocation`/`access`/`throws` edge leaving a + lowered declaration with the clause it declared or the reason it did not, + and the summary counted from all of it); `print(model)`; + `formatSummary`. The Java type table is data (`type-tables.ts`); the ten + others are empty and the header says so. Decisions the plan left open, or + where the EBNF and the Specy document overrule it: + - **No order, no name, from an id.** Declarations sort by printed name, + then parameter types, then anchor; clause items by their text. A module + is split into segments only where its profile's lexicon qualifies its kind + with `.` (Java, C#), else it is one quoted segment (a file path). A + struct's name is its ancestors' names joined by `.` below the module, + except where the profile qualifies the kind (Ruby `::`, Elixir `.`): the + name already is the path. + - **Constructors** are named by DATA, the table's `constructorKinds` + (`constructor` in Java, C#, TypeScript): "nameless, parent is a type" + alone made `new` of a Java field initializer's lambda. + - **Java anonymous classes** are `lambda` entities, so their named methods + are named invocables nested in an invocable: lowered as operations with a + path name (`@"running.price"`), `on module` (their receiver is no struct + of the model), counted on stderr. + - **Returns.** No `typeExpr` and no `declaredType` means "returns nothing" + only where the model writes type expressions (contract ≥ 1.2.0 and one + present) and the table says the language writes every return + (`returnAlwaysWritten`: Java); elsewhere it is `opaque "?"`. A + `declaredType` that is a scalar of the table prints the scalar (a scalar + has no argument to lose), otherwise the erased struct reference. + - **Errors** are `Name of Ref`: the payload links the error to the + exception type (closure-checked) and keeps two exceptions of one simple + name apart. + - **Externals.** A stub whose parent is a lowered module is declared in it; + a stub under a stub module and every corpus declaration outside `--scope` + at model level with its `external module`; a parentless stub at model + level, unqualified (Specy's rule 9 does not say an unqualified name + reaches a model-level external; its parser will). + - **Entries.** The inventory's `annotation`, `supertype`, `by hand` and + `type name` rows are rules read at the declaration: `entry`. A `concept` + row, and a `no caller` row an `operations` rule names (`main`, + `perform`), are inferences: `entry?`. A `no caller` row no rule names is + not marked at all (corrected in M25d): Specy says that "no operation of + the model calls it" is a position in the dependency graph and not what + the mark means. On the Java fixture with `spring.json` all 32 rows are + that residue, so none is marked, and stderr counts them. + - **Provenance.** Only `dynamic-candidate` (and every `candidates` entry) + is written `?`; `derived` and `generated` edges are firm, since Specy + has no third mark on a clause item. A `dynamic-candidate` access is not + declared (`reads`/`writes` take no `?`), and counted. + - **Undeclared writes.** Every write not declared is a `blind-spot` + finding naming why (outside the scope, an external, through another + instance with no or several parameters typed by the owner, `self` on a + field outside the receiver's schema), except a constructor's writes to + the instance it builds and writes to locals. + - **Flattening.** Corpus supertypes outside `--scope` are flattened too; + a field a subtype redeclares is not flattened again (counted); supertypes + outside the model get a second `// NOTE:`. A type that is also invocable + (a C# delegate) is a struct only. A nullable function type prints as + `opaque` (`(T) -> R?` would read as a nullable return). + - **Unnamed parameters** (Elixir patterns) print `@"#1"`, by position. + Nested named functions (a Python `def` in a `def`) keep the path below + their struct as one name, `on module`. + - **The command** reads the `.jsonl`, never `model.db` (the header's + contract version decides `TWithReceiver`). `--boundaries` takes a file + (a boundaries file or a stack table) as `analyze` does: neither resolves + a bare stack name. `--scope` is repeatable (any of them) and keeps a + module it matches or one holding a match. `--name` is checked against the + grammar's `modelName`; the default from the fixtures' roots is `src`. + Nothing to lower, or an empty scope, is a usage error. + - **The properties** run on all seven `fixtures/*/expected/model.jsonl`: + a test-side lexer AND a parser of the printed subset, written from the + EBNF (clause order enforced; a keyword where a name stands fails), the + closure check on the model value, the agreement check both ways against + the graph's own edge set; plus the scrambled-ids property on every + fixture, a table of all 50 EBNF keywords as every kind of name, and + mutants (names unquoted, externals dropped, a ledger entry dropped, + structs ordered by id, the fallback receiver, a flattened field's + anchor) each caught. Tests were written after the code, not before: the + mutants stand in for the red step. + - Left for M25d: the fixture snapshot, PetClinic read by hand, the docs. +4. **M25d · together.** `fixtures/java/expected/model.dataop` as a snapshot; + the command on PetClinic with the `spring` rules, its output read against + the source by hand for one controller, one entity and one repository; + `docs/dataop.md`, `docs/cli.md`, README, CLAUDE.md, the website page. + + **As built (2026-11-30).** + - **The snapshot.** `fixtures/java/expected/model.dataop` (439 lines), + pinned byte for byte by `packages/dataop/test/fixtures.test.ts`; + `CODEGRAPH_UPDATE_SNAPSHOTS=1` rewrites it. + - **One correction to M25c**, found reading that snapshot: every uncalled + operation was marked `entry?`. The inventory's unclassified `no caller` + rows are now left unmarked and counted on stderr (the Entries note of + step 3). Red first: a CLI test with a table that names no operation. + - **PetClinic** (`500158f`, extracted into a scratch directory, `spring` + table): 5 modules, 25 structs, 36 fields of which 15 flattened, 4 + globals, 109 operations of which 22 constructors, 36 `entry` and 1 + `entry?` (`main`); 290 edges declared, 13 not (7 a constructor's own + instance, 5 whose target is not a value holder, 1 external); 9 opaque + types, 21 `branching` findings, 0 `blind-spot`. + - **Read against the source by hand.** `Owner`: its four own fields and the + three flattened from `Person` and `BaseEntity`; `pets` is + `array`; every call of `addPet`, `getPet` ×3, `addVisit` and + `toString` is in `depends on` or `uses`; the three cyclomatic counts (7, + 4, 6) equal a hand count. `OwnerRepository`: `findById(id: number): + Owner?` and the `Page` return as `opaque`. `OwnerController`: the + static `VIEWS_OWNER_CREATE_OR_UPDATE_FORM` is a global with its literal, + `owners` a schema field read through `_`, the nine handler methods + `entry`. + - **What the reading found that the lowering cannot fix.** + `this.owners.save(owner)` is in no clause, because it is in no edge: + `save` is declared by a Spring Data interface that is not on the + classpath, and the extractor drops the site. The controller therefore + shows a read of `owners` and no call. Folding such a call onto the + nearest stub supertype, with its `member`, is an extractor change + (§26.10). + - **Owed.** The website page; commons-lang (no source checkout on the + machine that ran this); an independent review of `packages/dataop`, whose + tests were written after its code. + +### 26.9 Hazards, each with the test that pins it + +| Hazard | Test | +|---|---| +| a type expression renders an id by parsing it | the lowering takes names from entities' `name` and keys' components only; a property lowers a model whose rendered ids are scrambled and prints the same text | +| a fold loses an edge | the agreement property of §26.6, counted both ways | +| a quoted name is printed bare, or a keyword is | the lexical property, plus a table of every keyword of the EBNF as a name | +| the fallback without `TWithReceiver` is taken for a fact | the header comment of the output states it, and a test pins the sentence to the profile's licence | +| a flattened field is anchored on the subtype | a flattened field's `// source:` is its declaring type's file | +| another extractor's bytes move | every fixture snapshot compared before and after M25a | + +### 26.10 Deferred, explicitly + +- The walk definition that writes flows, contracts, states and descriptions. +- Candidate lineage (`derives from { X? }`) inferred from writes. +- `typeExpr` and the receiver in the C#, TypeScript, Elixir, Ruby and Python + extractors. +- Supertype operations: a struct does not list what it inherits, only its own. +- A `.dataop` parser and validator: Specy's. +- The Java extractor folding a call on a corpus type to a member that only a + stub supertype declares (`owners.save(owner)`) onto that stub, with its + `member`, as `derived`: found again on PetClinic in M25d (§25 recorded it + under M24a). PR #55 (`feat/java-ancestor-attribution`) does it and was open + when M25 was written; whichever lands second regenerates the Java snapshots, + `fixtures/java/expected/model.dataop` included. + +## 27. Milestones | # | Milestone | Definition of done | |---|---|---| @@ -8927,8 +9383,12 @@ asks for anchors. | M24e | Boundaries — `boundaries propose` | built on `feat/m24-boundaries` (§25.7 as built), the live runs owed: the rules written by a model from censuses, three checks on receipt, the audit as a sampled walk; live on PetClinic and Plausible against the shipped `spring` and `phoenix` tables | | M24f | Boundaries — the walk turned over | built on `feat/m24-boundaries` (§25.7 as built), the live run owed: `direction: "down"` at operation level, layerings `nearest` and `all-callers`, `context.quotes`; every quoted dependent precedes its unit; an up walk's fingerprints byte-identical | | M24g | Boundaries — rules over insights | built on `feat/m24-boundaries` (§25.7 as built): `concepts` in a boundaries file, matched on a projection the CLI hands the report; M16c's read-only handle test | +| M25a | Data & Operation — the contract | built on `feat/m25-dataop` (§26.8 as built), uncommitted: MM-7 `TypeExpr`/`typeExpr` and MM-8 `TWithReceiver`/`receiver` in core, `schemas/` (`$defs/TypeExpr`) and `model.db` (version 6); `SCHEMA_VERSION` 1.2.0; `receiver` in the edge order after `member`; the `receiver` conformance rule; the Java profile licensing the marker; a 1.1.0 file decodes unchanged and no fixture snapshot moved | +| M25b | Data & Operation — the Java extractor | built on `feat/m25-dataop` (§26.8 as built), uncommitted: `typeExpr`, `TWithReceiver` and `receiver` from Spoon, header 1.2.0; hand-counted on the fixture (one wildcard written into an existing parameter); the snapshot and its metrics and explain goldens regenerated; PetClinic `validate`-clean; commons-lang not run (no checkout) | +| M25c | Data & Operation — the lowering | built on `feat/m25-dataop` (§26.8 as built), uncommitted: `@codegraph/dataop` (`lower`, `print`, the edge ledger and the summary) and `codegraph dataop [--out] [--name] [--boundaries] [--scope]`; the lexical (a test-side lexer and parser from the EBNF), closure and agreement properties of §26.6 and the scrambled-ids property on all seven fixture models; a unit test per row of §26.4; inferred entries written `entry?` | +| M25d | Data & Operation — together | built on `feat/m25-dataop` (§26.8 as built), the website page owed: `fixtures/java/expected/model.dataop` pinned byte for byte; PetClinic lowered with the `spring` table and `Owner`, `OwnerRepository` and `OwnerController` read against their source; uncalled operations no rule names no longer marked; `docs/dataop.md`, `docs/cli.md`, README, CLAUDE.md | -## 27. Decisions made in this plan (deltas vs. the design doc) +## 28. Decisions made in this plan (deltas vs. the design doc) | Topic | Decision | Rationale | |---|---|---| diff --git a/README.md b/README.md index bad922c7..b7904a5b 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ Five questions, five commands: | How did it get this way? | `codegraph scm` / `replay` | churn, hotspots, ownership, co-change, and a city whose timeline scrubs the years | | What does it mean? | `codegraph explain` | one plain-language explanation per method, class and package, written leaves-first so every summary rests on already-explained parts | | What language does it speak? | `codegraph vocabulary` / `serve` → Vocabulary tab | the words of every name, split per language idiom and weighted by what carries them: a word cloud per package or class, drift against your glossary, one word across the city | +| What data and operations does it hold? | `codegraph dataop` | the model as a [Specy](https://specy.ai) Data & Operation model: structs with their fields, operations with what each calls, reads, writes and raises — and `opaque` or a finding wherever the code graph holds no fact ([docs/dataop.md](docs/dataop.md)) | Plus the plumbing you need to trust the answers: `validate` for the model, `analyze` for coupling and cycles, `export` for DOT, CSV, JSON and PlantUML. diff --git a/docs/cli.md b/docs/cli.md index 493ee803..c76ce604 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -82,6 +82,11 @@ codegraph vocabulary [model.jsonl] [--level corpus|module|type] [--scope ID] codegraph domain-facts [model.jsonl] [--framework spring] [--out FILE] [--internal-only] [--declared-only] +codegraph dataop [model.jsonl] [--out FILE] [--name NAME] + [--boundaries FILE] [--scope SEL]... + # the model as a Specy Data & Operation model (.dataop, + # observed); what was not lowered is counted on stderr + codegraph explain [model.jsonl] [--src DIR] [--out FILE] [--dry-run] [--estimate [--price-in USD --price-out USD]] [--provider auto|openrouter|cloudflare|claude-code] @@ -386,6 +391,39 @@ their invocations, accesses and throw sites. `--framework spring` adds the one inference layer (stereotypes, entry points, injection candidates), labelled as such. Deterministic: two runs over one model are byte-identical. +### `dataop` +The model lowered into a Specy Data & Operation model (`.dataop`) at the +`observed` level (PLAN.md §26): corpus modules become `module`s, named types +`struct`s (a nested one keeps its path as one quoted name, `@"Basket.Line"`), +fields with a receiver the `schema` (the fields of corpus supertypes flattened +in, each with its own `// source:`, a `// NOTE:` naming the supertypes), +fields without one and module-level values `global`s, invocables +`operation`s (a constructor `operation new(…): Struct on module`; a lambda's +edges folded into the operation it is written in). An operation's clauses come +from one edge kind each: `errors` from `throws`, `depends on` from calls into +the model (`?` for a `dynamic-candidate` and every candidate), `uses` from +calls into a stub, `reads`/`writes` from accesses (`_.field` through the +receiver, `param.field` for a write through the one parameter typed by the +field's owner). Libraries and the modules `--scope` leaves out are +`external`. Where the model holds no fact the text says `opaque`, `?` or a +finding (`branching` above cyclomatic 1, `blind-spot` for a write the rules +cannot attribute) and never guesses; flows, contracts, states, descriptions, +lineage and domain links are not written. The header comment says, per +language, whether `TWithReceiver` is read as a fact (Java at contract 1.2.0) +or the fallback holds (every field a schema field, every method attached), +and whether the language's type table is empty (every language but Java). +`--boundaries FILE` (a `codegraph.boundaries/1` file or a stack table) marks +the entry inventory's operations `entry`, or `entry?` for a row it inferred +(an uncalled operation an `operations` rule names, a `concept`). An uncalled +operation that no rule names is not marked: that nothing calls it is a +position in the graph, which is not what the mark means, and stderr counts +those rows; `--scope SEL` (repeatable, any of them) lowers only +the modules it matches or that hold a match; `--name` names the model +(default: the last segment of the model's root, kebab-case). stderr counts +what was lowered and what was not: opaque types, folded invocables, and every +`invocation`, `access` and `throws` edge not declared, by reason. Two runs +print the same bytes. It reads the `.jsonl`, never `model.db`. + ### `explain` Walks the graph bottom-up — leaf operations, then callers, then owning types, then modules — and asks a language model to explain each unit, feeding every diff --git a/docs/dataop.md b/docs/dataop.md new file mode 100644 index 00000000..17e2083d --- /dev/null +++ b/docs/dataop.md @@ -0,0 +1,124 @@ +# Lowering a model into a Specy Data & Operation model + +`codegraph dataop` prints a model as a Specy **Data & Operation model** +(`.dataop`): what data exists, what operations exist over it, and what each +operation depends on, reads, writes and raises. The text is at Specy's +`observed` conformance level, the one its metamodel reserves for a model +"lowered from a code graph". The design is PLAN.md §26; the target language is +Specy's `DATA-OPERATION-METAMODEL.md` and `data-operation.ebnf`. + +> **Status (M25):** the lowering and the command, for every extractor's model. +> Type expressions and receivers are emitted by the Java extractor only; the +> other languages lower through the fallback stated below. Flows, contracts, +> states, descriptions and lineage are not written (§5). + +The lowering states what the model holds and nothing else. Where the model +does not hold a fact, the text says so in the form Specy gives it (`opaque`, +`?`, a `// FINDING:`), and never guesses. It is a projection: nothing reads it +back, and nothing of it enters `model.jsonl`. + +## 1. Running it + +```bash +./bin/codegraph-java --src src/main/java --out model.jsonl +./bin/codegraph dataop model.jsonl --out model.dataop +./bin/codegraph dataop model.jsonl --name petclinic --boundaries plugin/references/stacks/spring.json +./bin/codegraph dataop model.jsonl --scope 'module:org.acme.billing' # one module; the rest becomes external +``` + +- `--out FILE` writes the text there; without it, stdout carries the text and + nothing else. +- `--name NAME` names the model (default: the last segment of the model's + root, kebab-case). +- `--boundaries FILE` takes a `codegraph.boundaries/1` file or a stack table + (docs/boundaries.md) and marks entry points (§3). +- `--scope SEL` (repeatable) lowers only the modules a selector matches; every + corpus declaration outside it becomes an `external` one. + +stderr carries a summary: what was lowered, how many types are `opaque`, how +many nameless invocables were folded, and every `invocation`, `access` and +`throws` edge that was not declared, by reason. The command reads the +`.jsonl`, never `model.db`: the contract version in the header decides how a +missing receiver marker is read (§4). + +## 2. What becomes what + +| In the model | In the `.dataop` | +|---|---| +| a module the corpus declares | `module` | +| a stub module or type the text references | `external module`, `external struct` | +| a named type | `struct`; a nested type keeps its path as one quoted name (`@"Basket.Line"`) | +| a field with a receiver | a schema field; the fields of corpus supertypes are flattened in, each with its own anchor, and a `// NOTE:` names the supertypes | +| a field without a receiver (static, an enum constant) | a `global` written in the struct; its initial value is the constant when the model holds one, `opaque` otherwise | +| a named invocable | an `operation`, nested where it is written: attached to the struct with a receiver, `on module` without | +| a constructor | `operation new(…): Struct on module` | +| a lambda, an anonymous invocable | nothing of its own: its edges fold into the nearest named operation | + +And per operation, one clause per edge kind: + +| Clause | From | +|---|---| +| `errors` | `throws` edges: the operation's own raise sites | +| `depends on` | `invocation` to a corpus operation; a `dynamic-candidate` and each of its `candidates` are written `?` | +| `uses` | `invocation` to a stub: the external struct or module called into | +| `reads`, `writes` | `access` edges: a global by its path, `_.field` through the receiver, `param.field` for a write on the one parameter typed by the field's owner | + +Types come from the type expression (METAMODEL.md §1.7) through a table per +language, held as data: which primitives and stubs are `string`, `number` or +`boolean`, which generic stubs are a sequence (`array`) or an optional +(`T?`). A type the closed language cannot say is `opaque "…"` with the +expression rendered. Without a type expression, the erased `declaredType` is +printed, since it is all the model knows. + +A name is printed as the code spells it: bare when it is letters, digits and +`_`, quoted (`@"model"`, `@"src/a.ts"`) when it is not or when it is a keyword +of the grammar. + +## 3. Entries + +With `--boundaries`, an operation the entry inventory finds by a rule read at +its declaration (an annotation, a supertype, a type-name pattern, a rule by +hand) is marked `entry`. One the inventory inferred (an uncalled operation an +`operations` rule names, such as `main`; a concept label) is marked `entry?`. +An uncalled operation that no rule names is **not** marked: that nothing calls +it is a position in the graph, which Specy says the mark does not mean. stderr +counts those rows. + +## 4. When the model does not say + +- **No receiver marker.** `TWithReceiver` is read as a fact, and its absence + as "no receiver", only in a model whose header states contract 1.2.0 or + later and on a kind whose profile licenses the marker. Anywhere else, every + field of a type is a schema field, every method is attached, and an access + to a field of the operation's own struct reads as `_`. The first comment + lines of the output say which reading each language took. +- **No type table.** Every language but Java has an empty table today: a + named type prints as a struct reference, and the header says so. +- **A write that cannot be attributed** (through another instance, with no + single parameter typed by the field's owner) is not declared; a + `// FINDING: blind-spot:` says so. +- **A body that branches** gets `// FINDING: branching: cyclomatic N`, since a + flow could not show it. +- **A call the model does not hold** cannot be printed. On Spring PetClinic, + `this.owners.save(owner)` is such a call: `save` is declared by a Spring + Data interface that is not on the extractor's classpath, the extractor drops + the site, and the controller's operation shows the read of `owners` and no + call. This is the extractor's limit (the `java` profile's notes), not a + choice of the lowering. + +## 5. What is not lowered + +States, contracts (`requires`, `ensures`), flows, `::` descriptions, lineage +and domain links. A flow needs the names bound to results and the arguments +passed, which a dependency graph does not hold. They are for a walk to write, +with these clauses as context (PLAN.md §26.7, §26.10). + +## 6. Checking the output + +Specy has no `.dataop` parser yet. Three properties stand in for one, run on +every fixture model (`packages/dataop/test`): every token is legal and every +name that needs quoting is quoted; every reference resolves to a declaration +or a printed external; every clause item is backed by an edge, and every edge +is declared or counted. `fixtures/java/expected/model.dataop` is the committed +snapshot; `CODEGRAPH_UPDATE_SNAPSHOTS=1 pnpm --filter @codegraph/dataop test fixtures` +rewrites it. diff --git a/docs/model-encoding.md b/docs/model-encoding.md index 7feacba0..43d4a67a 100644 --- a/docs/model-encoding.md +++ b/docs/model-encoding.md @@ -196,7 +196,9 @@ CREATE TABLE entity_metric (entity_id, key, value, PRIMARY KEY (en -- A Literal (§1.6) is a TREE, and nothing queries inside one, so it stays a -- single JSON value on `entity.value` (and on `edge.arguments` for an -- annotationUse). The ids inside it are the wire's own surrogates, so the blob --- round-trips byte for byte. +-- round-trips byte for byte. A TypeExpr (§1.7, MM-7) is kept the same way, on +-- `entity.type_expr`. The edge's MM-6 `member` and MM-8 `receiver` are plain +-- TEXT columns, NULL when the key is absent. CREATE TABLE edge ( id INTEGER PRIMARY KEY, -- position in the edge section diff --git a/docs/model-metamodel.md b/docs/model-metamodel.md index 03884839..1c526e80 100644 --- a/docs/model-metamodel.md +++ b/docs/model-metamodel.md @@ -233,6 +233,110 @@ An extractor upgrade then re-asks nothing on that account. Every other consumer counts edges as they are: fold weights, view sizes and `dep` rows per external module grow by the number of splits. +## MM-7 A typed entity carries its type expression + +Status: **accepted 2026-11-30, core shipped in M25a (PLAN.md §26.2)**. + +Measured on `fixtures/java` before this change: a primitive-typed field +(`Money.cents`) has no `declaredType` at all; `Basket.lines` is the raw `List`, +its argument a separate `reference` edge; an array is its component. So +`List`, `int[]` and `T?` could not be written from the model, and +the written text of a type the extractor cannot structure was not kept. + +- **The attribute.** `TTypedEntity` gains an optional `typeExpr: TypeExpr` + (METAMODEL §1.7). `declaredType` is unchanged, in meaning and in bytes: the + erased head, a reference. +- **The value.** A closed tagged union, core-owned, built as `Literal` is: + `named` (a type or a stub, `args?` its written arguments), `primitive`, + `array`, `nullable`, `function` (`params`, `returns?`), `union`, `variable`, + `unevaluated` (the written text). Two canonical-form bounds the schema states + as plain JSON Schema: a present `args` is non-empty, and a `union` has at + least two members — one spelling per written type. +- **What is written, never what is inferred.** No `typeExpr` on a `var`, an + untyped parameter or a `void` return; `nullable` only where the language + writes it. +- **Closure reaches inside.** The `named` ids count as an edge endpoint does + (`typeExprReferences`, walked by `unknownReferences`), and on the wire they + are surrogates, so a dangling one is unwritable (the encoder has no surrogate + for it) and unreadable (the reader refuses a surrogate past the entity count). + A type the extractor cannot name is `unevaluated`, never a fabricated id. +- **A value never replaces a dependency.** The `reference` edges a written type + emits are still emitted. + +### As built (M25a) + +- `packages/core/src/type-expr.ts`: `TypeExpr` (the type and its Zod schema, + published as `$defs/TypeExpr` in `schemas/e.record.schema.json`), + `TYPE_EXPR_FORMS`, `typeExprReferences`, and `mapTypeExpr` — the ONE walk the + encoder (ids → surrogates) and the decoder (surrogates → ids) both use, so + they cannot disagree on which positions hold a reference, and which writes + each node's keys in one order (`k`, then the form's keys as the table lists + them) whatever order the producer built it in. `WireTypeExpr` is the same + schema over surrogates (`wire.ts`). +- On the entity record `typeExpr` is written right after `declaredType`; an + entity without one writes the bytes it wrote before. +- `model.db`: `entity.type_expr`, the JSON tree with its surrogates, like + `entity.value`. + +## MM-8 A member that needs an instance says so + +Status: **accepted 2026-11-30, core shipped in M25a (PLAN.md §26.3)**. + +Java's `attribute` kind has no word for static: `Order.MAX_LINES` and +`Order.channel` differ only by a constant value. And an `access` edge does not +say whether the field was reached through the receiver: `this.lines` and +`other.lines` were one edge. + +- **The trait.** `TWithReceiver`, a marker: the entity is evaluated against an + instance of the type it is written in or attached to. Licensed, OPTIONAL, on + the kinds a profile can decide it for — Java: `attribute`, `method`, + `constructor`. Optional so that a model written by an extractor that predates + it stays profile-valid. In a profile that licenses it on a kind, absence + means "no receiver"; in a profile that does not, absence means nothing. The + Java profile note scopes the first reading to a model whose header states + contract 1.2.0 or later. +- **The edge.** `access` gains an optional `receiver: "self" | "other"`: `self` + through the accessor's own receiver, written or implied; `other` through any + other expression. Absent when the target has no receiver or the extractor + does not say. Core's `Edge` schema refuses it on the other ten kinds; + `receiverViolations` (and `codegraph validate`, rule `receiver`, codes + `receiver-kind` and `receiver-target-stub`) reports one on an edge to a stub. + +### The decision, from each encoder's code + +**Canonical order: `receiver` joins it, as `member` did, and sorts after it.** +Every writer sorts edges by `f`, `o`, kind, anchor (file, start, end), +provenance, `member` (MM-6). `this.lines = other.lines` is a `self` write and +an `other` read of one field from one operation on one line: with `isRead`/ +`isWrite` not in the order, the two edges tie on all of it, and a stable sort +would leave them in the producer's order — two runs, two byte sequences. So +`receiver` is the last tiebreak, the absent one first, then UTF-16 code units +(`other` before `self`); an edge without one compares as before and never +moves. Core's `jsonl.ts` states it as one rule for both optional keys +(`compareOptional`). + +**On the record** it is written after `isRead`, `isWrite`, the flags it +qualifies: `EDGE_KEY_ORDER = member, candidates, arguments, isRead, isWrite, +receiver, sourceFile, anchor`. + +**Merge keys.** The core encoder, the analyzer and `model.db` merge nothing. +Of the producers that merge (MM-6's table), only Java will write a receiver in +this phase, and it merges twice: its `Edge` record (equal on every component, +so `receiver` joins once it is a component) and `AccessKey(from, to, member, +provenance, anchor)` (`EdgeExtractor.java:1198`), which folds a read and a +write at one site into one edge with both flags — **`receiver` must be added +to `AccessKey`** (M25b), or a `self` write and an `other` read at one site +fold into one edge naming one receiver. The other extractors emit no receiver +and need nothing. + +**Version.** Both MM-7 and MM-8 are one additive step: `SCHEMA_VERSION` +1.1.0 → 1.2.0. A 1.1.0 or 1.0.0 file decodes unchanged and keeps the version it +states; every committed fixture re-encodes byte for byte +(`packages/core/test/type-expr.test.ts`). No extractor writes 1.2.0 yet. The +trait dictionary and the record schemas grow by one name and three optional +keys; `model.db` goes to version 6 (`entity.type_expr`, `edge.receiver`, the +`receiver` column of the `dep` view), so an older cache is regenerated. + ## Task list (metamodel track) - [x] METAMODEL.md: restate identity as the natural key (MM-1, §1.1), extend the diff --git a/docs/sql-cookbook.md b/docs/sql-cookbook.md index b809759d..99207bd7 100644 --- a/docs/sql-cookbook.md +++ b/docs/sql-cookbook.md @@ -91,7 +91,8 @@ SELECT x.id AS ref, p.name AS provenance, f.path AS file, x.anchor_start AS line, - x.member AS member + x.member AS member, + x.receiver AS receiver FROM edge x JOIN edge_kind ek ON ek.id = x.kind_id JOIN provenance p ON p.id = x.provenance_id diff --git a/eslint.config.js b/eslint.config.js index 261d4d27..d69e7ab5 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -59,6 +59,7 @@ export default tseslint.config( "packages/city/**/*.ts", "packages/navigator/**/*.ts", "packages/vocabulary/**/*.ts", + "packages/dataop/**/*.ts", "packages/insights/**/*.ts", "packages/cli/**/*.ts", ], diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/EdgeExtractor.java b/extractors/java/src/main/java/dev/codegraph/spoon/EdgeExtractor.java index 3d984570..14705b63 100644 --- a/extractors/java/src/main/java/dev/codegraph/spoon/EdgeExtractor.java +++ b/extractors/java/src/main/java/dev/codegraph/spoon/EdgeExtractor.java @@ -28,6 +28,9 @@ import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtNewClass; import spoon.reflect.code.CtOperatorAssignment; +import spoon.reflect.code.CtExpression; +import spoon.reflect.code.CtSuperAccess; +import spoon.reflect.code.CtThisAccess; import spoon.reflect.code.CtThrow; import spoon.reflect.code.CtUnaryOperator; import spoon.reflect.code.UnaryOperatorKind; @@ -149,7 +152,8 @@ public final class EdgeExtractor { Edge.DETERMINISTIC_ORDER .thenComparing(e -> e.candidates() == null ? "" : String.join(",", e.candidates())) .thenComparing(e -> String.valueOf(e.isRead())) - .thenComparing(e -> String.valueOf(e.isWrite())); + .thenComparing(e -> String.valueOf(e.isWrite())) + .thenComparing(e -> String.valueOf(e.receiver())); /** Spoon expressions → values (§1.6); stateless apart from its evaluator. */ private final Literals literals = new Literals(); @@ -742,16 +746,58 @@ private void emitAccesses(CtModel model) { if (UNKNOWN_TYPE_ID.equals(typeId)) { droppedUnidentifiedTargets++; } else if (owner.get().kind() == OwnerKind.INVOCABLE) { - addAccess(owner.get().id(), typeId, name, provenance.get(), anchor.get(), read, write); + addAccess(owner.get().id(), typeId, name, null, provenance.get(), anchor.get(), read, write); } else { add(Edge.reference(owner.get().id(), typeId, provenance.get(), anchor.get()).naming(name)); } continue; } - addAccess(owner.get().id(), member.get(), null, provenance.get(), anchor.get(), read, write); + addAccess( + owner.get().id(), member.get(), null, receiverOf(access, field), provenance.get(), anchor.get(), read, write); } } + /** + * MM-8: {@code self} when the field is reached through the accessor's own + * {@code this} — written, implied, or {@code super.x} — and {@code other} + * through any other expression; null when the field has no receiver. + * + *

"Own" is the innermost type the access is written in, anonymous classes + * included. A lambda is no type, so its {@code this.x} is its enclosing + * method's ({@code self}); an inner or anonymous class reaching a field of + * its OUTER instance ({@code lines} in {@code Basket.Cursor}, implied + * {@code Basket.this.lines}) goes through another object: {@code other}. + */ + private static String receiverOf(CtFieldAccess access, CtFieldReference field) { + CtField declaration; + try { + declaration = field.getFieldDeclaration(); + } catch (RuntimeException e) { + return null; + } + if (!Receivers.of(declaration)) { + return null; + } + CtExpression target = access.getTarget(); + if (target instanceof CtSuperAccess) { + return Edge.SELF; + } + if (target instanceof CtThisAccess self) { + CtType own = access.getParent(CtType.class); + CtTypeReference through = self.getType(); + if (own == null || through == null) { + return null; + } + CtType reached = safeTypeDeclaration(through); + if (reached != null) { + return reached == own ? Edge.SELF : Edge.OTHER; + } + return through.getQualifiedName().equals(own.getQualifiedName()) ? Edge.SELF : Edge.OTHER; + } + // No target at all is a tree Spoon could not complete: say nothing. + return target == null ? null : Edge.OTHER; + } + /** {@code x += 1} and {@code x++} read the field they write; {@code x = 1} does not. */ private static boolean readsWhileWriting(CtFieldAccess access) { CtElement parent = parentOf(access); @@ -1238,6 +1284,7 @@ private void addAccess( String from, String to, String member, + String receiver, Provenance provenance, SourceAnchor anchor, boolean read, @@ -1247,7 +1294,8 @@ private void addAccess( return; } boolean[] flags = - accesses.computeIfAbsent(new AccessKey(from, to, member, provenance, anchor), key -> new boolean[2]); + accesses.computeIfAbsent( + new AccessKey(from, to, member, receiver, provenance, anchor), key -> new boolean[2]); flags[0] |= read; flags[1] |= write; } @@ -1261,7 +1309,7 @@ private List assemble() { // An access is a read unless it is exclusively a write; Edge rejects an // access that claims to be neither. boolean read = entry.getValue()[0] || !write; - all.add(Edge.access(key.from(), key.to(), key.provenance(), key.anchor(), read, write).naming(key.member())); + all.add(Edge.access(key.from(), key.to(), key.provenance(), key.anchor(), read, write).naming(key.member()).through(key.receiver())); } all.sort(TOTAL_ORDER); return List.copyOf(all); @@ -1326,5 +1374,7 @@ private record ImportTarget(String id, Provenance provenance) {} private record DeclaredType(String id, CtType type) {} /** {@code member} is null on an access to a corpus field and on a stub field Spoon could not name. */ - private record AccessKey(String from, String to, String member, Provenance provenance, SourceAnchor anchor) {} + /** {@code receiver} too (MM-8): a self write and an other read at one site are two accesses. */ + private record AccessKey( + String from, String to, String member, String receiver, Provenance provenance, SourceAnchor anchor) {} } diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/EntityExtractor.java b/extractors/java/src/main/java/dev/codegraph/spoon/EntityExtractor.java index bfd98395..ef421fc1 100644 --- a/extractors/java/src/main/java/dev/codegraph/spoon/EntityExtractor.java +++ b/extractors/java/src/main/java/dev/codegraph/spoon/EntityExtractor.java @@ -356,13 +356,16 @@ private void method(CtMethod method, String ownerId) { .withParameters(parameters(method, id)) .withLocalVariables(locals(method, id)) .markers(TraitName.TWithInvocations, TraitName.TWithAccesses) - .typed(declaredTypeIdOf(method.getType())) + .typed(declaredTypeIdOf(method.getType()), TypeExprs.of(method.getType())) .childOf(ownerId) .anchoredAt(anchor.get()) .measured(measures.of(method, anchor.get())) // An annotation element's `default` — the one place Java writes a // value on something invocable (§1.6). .valued(annotationDefaultOf(method)); + if (Receivers.of(method)) { + builder.marker(TraitName.TWithReceiver); + } comments(builder, method); add(new Draft(id, ownerId, true, builder)); } @@ -389,6 +392,8 @@ private void constructor(CtConstructor constructor, String ownerId) { .withParameters(parameters(constructor, id)) .withLocalVariables(locals(constructor, id)) .markers(TraitName.TWithInvocations, TraitName.TWithAccesses) + // MM-8: a constructor initializes an instance, its own receiver. + .marker(TraitName.TWithReceiver) .childOf(ownerId) .anchoredAt(anchor.get()) .measured(measures.of(constructor, anchor.get())); @@ -425,12 +430,15 @@ private void field(CtField field, String ownerId) { Entity.builder(id, ATTRIBUTE) .named(field.getSimpleName()) .marker(TraitName.TStructural) - .typed(declaredTypeIdOf(field.getType())) + .typed(declaredTypeIdOf(field.getType()), TypeExprs.of(field.getType())) .childOf(ownerId) .anchoredAt(anchor.get()) // Only a compile-time constant has a declaration-site value; a // `new ArrayList<>()` initializer is code, and carries none. .valued(literals.constantOf(field).orElse(null)); + if (Receivers.of(field)) { + builder.marker(TraitName.TWithReceiver); + } comments(builder, field); add(new Draft(id, ownerId, false, builder)); } @@ -448,7 +456,7 @@ private List parameters(CtExecutable executable, String executableId) Entity.builder(id, PARAMETER) .named(name) .marker(TraitName.TStructural) - .typed(declaredTypeIdOf(parameter.getType())) + .typed(declaredTypeIdOf(parameter.getType()), writtenTypeOf(parameter)) .childOf(executableId); anchors.of(parameter).ifPresent(builder::anchoredAt); add(new Draft(id, executableId, false, builder)); @@ -481,7 +489,10 @@ private List locals(CtExecutable executable, String executableId) { Entity.builder(id, LOCAL_VARIABLE) .named(name) .marker(TraitName.TStructural) - .typed(declaredTypeIdOf(local.getType())) + .typed( + declaredTypeIdOf(local.getType()), + // `var x = …`: the type is inferred, so nothing was written. + local.isInferred() ? null : TypeExprs.of(local.getType())) .childOf(executableId) .anchoredAt(anchor.get()); add(new Draft(id, executableId, false, builder)); @@ -716,6 +727,26 @@ private static String declaredTypeIdOf(CtTypeReference reference) { return UNNAMEABLE_TYPE_ID.equals(id) ? null : id; } + /** + * A parameter's written type (MM-7), or null when none was written: an + * implicitly typed lambda parameter ({@code order -> …}) or a {@code var} one. + * A record's implicit canonical constructor keeps its parameters' types: they + * are the components', written in the header, as its fields' and accessors' are. + */ + private static dev.codegraph.spoon.model.TypeExpr writtenTypeOf(CtParameter parameter) { + CtTypeReference type = parameter.getType(); + if (type == null || parameter.isInferred()) { + return null; + } + boolean recordComponent = + parameter.getParent() instanceof CtConstructor constructor + && constructor.getDeclaringType() instanceof CtRecord; + if (type.isImplicit() && !recordComponent) { + return null; + } + return parameter.isVarArgs() ? TypeExprs.ofVarargs(type) : TypeExprs.of(type); + } + private static void comments(Entity.Builder builder, CtElement element) { String doc = element.getDocComment(); if (doc != null && !doc.isBlank()) { diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/Main.java b/extractors/java/src/main/java/dev/codegraph/spoon/Main.java index c5925605..616c714c 100644 --- a/extractors/java/src/main/java/dev/codegraph/spoon/Main.java +++ b/extractors/java/src/main/java/dev/codegraph/spoon/Main.java @@ -188,6 +188,19 @@ private static void run(Options options, Progress progress) throws Exception { } edges = closed; + // Pass 4.6 — the same rule inside a type expression (MM-7): a `named` node + // whose target nothing declares is kept as its written text. It never feeds + // pass 4, so the stub set is what edges and declaredType make it. + int degradedTypeNodes = 0; + for (int i = 0; i < entities.size(); i++) { + Entity entity = entities.get(i); + Entity closedEntity = entity.withTypeExprClosedOver(declaredIds::contains); + if (closedEntity != entity) { + degradedTypeNodes++; + entities.set(i, closedEntity); + } + } + // Pass 5 — deterministic assembly and output. ExtractorInfo extractor = new ExtractorInfo(NAME, VERSION, Boolean.TRUE); Model model = Model.sorted(extractor, root.toString(), options.repository(), entities, edges); @@ -200,6 +213,10 @@ private static void run(Options options, Progress progress) throws Exception { .withOutput(entities.size(), stubs.size(), edges.size(), droppedSelfEdges) .withAncestorCalls(edgeExtractor.ancestorAttributedCalls(), edgeExtractor.ambiguousAncestorCalls()) .summary()); + if (degradedTypeNodes > 0) { + progress.log( + "note: " + degradedTypeNodes + " type expression(s) kept a node as text: its type is declared nowhere"); + } if (droppedDanglingEdges > 0) { progress.log( "warning: " + droppedDanglingEdges + " edge(s) dropped for an undeclarable endpoint"); diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/Receivers.java b/extractors/java/src/main/java/dev/codegraph/spoon/Receivers.java new file mode 100644 index 00000000..71772c4d --- /dev/null +++ b/extractors/java/src/main/java/dev/codegraph/spoon/Receivers.java @@ -0,0 +1,36 @@ +package dev.codegraph.spoon; + +import spoon.reflect.declaration.CtAnnotationType; +import spoon.reflect.declaration.CtEnumValue; +import spoon.reflect.declaration.CtField; +import spoon.reflect.declaration.CtInterface; +import spoon.reflect.declaration.CtMethod; + +/** + * MM-8's one question, asked of a declaration: is it evaluated against an + * instance of the type it is written in? Pass 2 answers it to put + * {@code TWithReceiver} on an entity and pass 3 to decide whether an access to + * that entity names a receiver, so the two cannot disagree. + * + *

Rulings: an annotation element ({@code String value()}) HAS a receiver — it + * is an abstract method of the annotation interface, read on an annotation + * instance ({@code audited.value()}). A field of an interface or of an + * annotation type has none: it is implicitly static (JLS §9.3), written or not. + * An enum constant has none. + */ +final class Receivers { + + private Receivers() {} + + static boolean of(CtField field) { + if (field == null || field instanceof CtEnumValue || field.isStatic()) { + return false; + } + return !(field.getDeclaringType() instanceof CtInterface) + && !(field.getDeclaringType() instanceof CtAnnotationType); + } + + static boolean of(CtMethod method) { + return method != null && !method.isStatic(); + } +} diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/TypeExprs.java b/extractors/java/src/main/java/dev/codegraph/spoon/TypeExprs.java new file mode 100644 index 00000000..78924c77 --- /dev/null +++ b/extractors/java/src/main/java/dev/codegraph/spoon/TypeExprs.java @@ -0,0 +1,139 @@ +package dev.codegraph.spoon; + +import dev.codegraph.spoon.model.TypeExpr; +import java.util.ArrayList; +import java.util.List; +import spoon.reflect.declaration.CtElement; +import spoon.reflect.reference.CtArrayTypeReference; +import spoon.reflect.reference.CtIntersectionTypeReference; +import spoon.reflect.reference.CtTypeParameterReference; +import spoon.reflect.reference.CtTypeReference; +import spoon.reflect.reference.CtWildcardReference; + +/** + * A written Spoon type reference → its type expression (MM-7). Stateless. + * + *

The forms: a primitive by its keyword; an array (nested, so + * {@code int[][]} is an array of an array); a type parameter as a + * {@code variable}; a class or interface as {@code named}, its id the one + * {@link EntityIds#forTypeReference} gives {@code declaredType} and edges, and + * its written arguments in order. A wildcard, an intersection and anything + * Spoon cannot name ride as {@code unevaluated} with their source text. The + * caller decides whether a type was written at all ({@code var}, an implicit + * lambda parameter and {@code void} were not); ids are closed later, once the + * stubs exist ({@link dev.codegraph.spoon.model.Entity#withTypeExprClosedOver}). + */ +final class TypeExprs { + + private static final String UNNAMEABLE_TYPE_ID = EntityIds.forTypeReference(null); + + private TypeExprs() {} + + /** Null for {@code void} and for no reference at all. */ + static TypeExpr of(CtTypeReference reference) { + if (reference == null || "void".equals(reference.getSimpleName())) { + return null; + } + return expression(reference, 0); + } + + /** + * A varargs parameter: {@code String... rows} is a {@code String[]}. Spoon + * hands back the array form, but the component alone has been seen too + * (the same guard {@link EntityIds} keeps for signatures). + */ + static TypeExpr ofVarargs(CtTypeReference reference) { + TypeExpr expr = of(reference); + if (expr == null || reference instanceof CtArrayTypeReference) { + return expr; + } + return new TypeExpr.Array(expr); + } + + private static TypeExpr expression(CtTypeReference reference, int depth) { + if (depth > 32) { + return unevaluated(reference); + } + if (reference instanceof CtArrayTypeReference array) { + CtTypeReference component = array.getComponentType(); + return component == null + ? unevaluated(reference) + : new TypeExpr.Array(expression(component, depth + 1)); + } + // A wildcard IS a CtTypeParameterReference in Spoon: test it first. + if (reference instanceof CtWildcardReference || reference instanceof CtIntersectionTypeReference) { + return unevaluated(reference); + } + if (reference instanceof CtTypeParameterReference parameter) { + String name = parameter.getSimpleName(); + return name == null || name.isBlank() ? unevaluated(reference) : new TypeExpr.Variable(name); + } + if (reference.isPrimitive()) { + return new TypeExpr.Primitive(reference.getSimpleName()); + } + String id; + try { + id = EntityIds.forTypeReference(reference); + } catch (RuntimeException unnameable) { + return unevaluated(reference); + } + if (UNNAMEABLE_TYPE_ID.equals(id) || hasWrittenOuterArguments(reference)) { + return unevaluated(reference); + } + List args = new ArrayList<>(); + for (CtTypeReference argument : reference.getActualTypeArguments()) { + // A diamond's arguments are inferred, never written. + if (argument.isImplicit()) { + return new TypeExpr.Named(id, null, sourceOf(reference)); + } + args.add(expression(argument, depth + 1)); + } + return new TypeExpr.Named(id, args, sourceOf(reference)); + } + + /** + * {@code Outer.Inner}: the arguments belong to the outer type, which a + * {@code named} node cannot hold, so the whole use is kept as text. + */ + private static boolean hasWrittenOuterArguments(CtTypeReference reference) { + for (CtTypeReference outer = reference.getDeclaringType(); + outer != null; + outer = outer.getDeclaringType()) { + if (!outer.getActualTypeArguments().isEmpty()) { + return true; + } + } + return false; + } + + private static TypeExpr unevaluated(CtTypeReference reference) { + return new TypeExpr.Unevaluated(sourceOf(reference)); + } + + /** + * The text as written, whitespace runs folded to one space (a type split over + * lines is one type); Spoon's printing when the reference has no position. + */ + static String sourceOf(CtElement element) { + String text = null; + try { + if (element.getPosition() != null && element.getPosition().isValidPosition()) { + String source = element.getPosition().getCompilationUnit().getOriginalSourceCode(); + int start = element.getPosition().getSourceStart(); + int end = element.getPosition().getSourceEnd(); + if (source != null && start >= 0 && end >= start && end < source.length()) { + text = source.substring(start, end + 1); + } + } + if (text == null || text.isBlank()) { + text = element.toString(); + } + } catch (RuntimeException unprintable) { + text = null; + } + if (text == null || text.isBlank()) { + return "?"; + } + return text.strip().replaceAll("\\s+", " "); + } +} diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/model/Edge.java b/extractors/java/src/main/java/dev/codegraph/spoon/model/Edge.java index c3f1c803..f827a74e 100644 --- a/extractors/java/src/main/java/dev/codegraph/spoon/model/Edge.java +++ b/extractors/java/src/main/java/dev/codegraph/spoon/model/Edge.java @@ -20,7 +20,7 @@ * the only kind whose schema variant requires them. */ @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({"edge", "from", "to", "provenance", "member", "anchor", "candidates", "arguments", "isRead", "isWrite", "sourceFile"}) +@JsonPropertyOrder({"edge", "from", "to", "provenance", "member", "anchor", "candidates", "arguments", "isRead", "isWrite", "receiver", "sourceFile"}) public record Edge( EdgeKind edge, String from, @@ -39,6 +39,14 @@ public record Edge( List arguments, @JsonProperty("isRead") Boolean isRead, @JsonProperty("isWrite") Boolean isWrite, + /** + * MM-8, access only: {@code self} when the field is reached through the + * accessor's own receiver, {@code other} through any other expression; + * null when the target has no receiver (static) or is a stub. Part of the + * edge's identity: {@code this.x = other.x} is two accesses. Set only + * through {@link #through}. + */ + String receiver, String sourceFile) { public Edge { @@ -59,6 +67,14 @@ public record Edge( throw new IllegalArgumentException("only invocation, access and reference name a member (MM-6), not " + edge); } } + if (receiver != null) { + if (edge != EdgeKind.ACCESS) { + throw new IllegalArgumentException("only an access names a receiver (MM-8), not " + edge); + } + if (!SELF.equals(receiver) && !OTHER.equals(receiver)) { + throw new IllegalArgumentException("a receiver is self or other, not " + receiver); + } + } candidates = candidates == null ? null : List.copyOf(candidates); arguments = arguments == null ? null : List.copyOf(arguments); if ((edge == EdgeKind.ANNOTATION_USE) != (arguments != null)) { @@ -69,18 +85,18 @@ public record Edge( /** Module → Module. The first-class, cross-language comparable layer. */ public static Edge importEdge(String from, String to, Provenance provenance, SourceAnchor anchor) { - return new Edge(EdgeKind.IMPORT, from, to, provenance, anchor, null, null, null, null, null, null); + return new Edge(EdgeKind.IMPORT, from, to, provenance, anchor, null, null, null, null, null, null, null); } /** Type → Type: {@code extends} (classes and interfaces alike). */ public static Edge inheritance(String from, String to, Provenance provenance, SourceAnchor anchor) { - return new Edge(EdgeKind.INHERITANCE, from, to, provenance, anchor, null, null, null, null, null, null); + return new Edge(EdgeKind.INHERITANCE, from, to, provenance, anchor, null, null, null, null, null, null, null); } /** Type → interface: a class/enum/record {@code implements} clause. */ public static Edge interfaceImplementation( String from, String to, Provenance provenance, SourceAnchor anchor) { - return new Edge(EdgeKind.INTERFACE_IMPLEMENTATION, from, to, provenance, anchor, null, null, null, null, null, null); + return new Edge(EdgeKind.INTERFACE_IMPLEMENTATION, from, to, provenance, anchor, null, null, null, null, null, null, null); } /** @@ -91,7 +107,7 @@ public static Edge interfaceImplementation( public static Edge invocation( String from, String to, Provenance provenance, SourceAnchor anchor, List candidates) { List cands = (candidates == null || candidates.isEmpty()) ? null : candidates; - return new Edge(EdgeKind.INVOCATION, from, to, provenance, anchor, null, cands, null, null, null, null); + return new Edge(EdgeKind.INVOCATION, from, to, provenance, anchor, null, cands, null, null, null, null, null); } /** Invocable → Structural. At least one of read/write must be true. */ @@ -105,7 +121,7 @@ public static Edge access( if (!isRead && !isWrite) { throw new IllegalArgumentException("an access that is neither a read nor a write is not an access"); } - return new Edge(EdgeKind.ACCESS, from, to, provenance, anchor, null, null, null, isRead, isWrite, null); + return new Edge(EdgeKind.ACCESS, from, to, provenance, anchor, null, null, null, isRead, isWrite, null, null); } /** @@ -118,12 +134,12 @@ public static Edge annotationUse( String from, String to, Provenance provenance, SourceAnchor anchor, List arguments) { return new Edge( EdgeKind.ANNOTATION_USE, from, to, provenance, anchor, null, null, - arguments == null ? List.of() : arguments, null, null, null); + arguments == null ? List.of() : arguments, null, null, null, null); } /** Entity → Type: a type usage that is none of the above (casts, generics, annotations). */ public static Edge reference(String from, String to, Provenance provenance, SourceAnchor anchor) { - return new Edge(EdgeKind.REFERENCE, from, to, provenance, anchor, null, null, null, null, null, null); + return new Edge(EdgeKind.REFERENCE, from, to, provenance, anchor, null, null, null, null, null, null, null); } /** @@ -132,7 +148,7 @@ public static Edge reference(String from, String to, Provenance provenance, Sour * declares propagation and stays a plain {@link #reference}. */ public static Edge throwsEdge(String from, String to, Provenance provenance, SourceAnchor anchor) { - return new Edge(EdgeKind.THROWS, from, to, provenance, anchor, null, null, null, null, null, null); + return new Edge(EdgeKind.THROWS, from, to, provenance, anchor, null, null, null, null, null, null, null); } /** The kinds MM-6 lets name a member; core's {@code Edge} schema refuses it on the others. */ @@ -149,7 +165,24 @@ public Edge naming(String member) { if (member == null) { return this; } - return new Edge(edge, from, to, provenance, anchor, member, candidates, arguments, isRead, isWrite, sourceFile); + return new Edge(edge, from, to, provenance, anchor, member, candidates, arguments, isRead, isWrite, receiver, sourceFile); + } + + /** MM-8's two values. */ + public static final String SELF = "self"; + + public static final String OTHER = "other"; + + /** + * This access, saying through which receiver its field was reached (MM-8). + * The caller guarantees the target is a corpus field with a receiver; a null + * receiver returns the edge unchanged. + */ + public Edge through(String receiver) { + if (receiver == null) { + return this; + } + return new Edge(edge, from, to, provenance, anchor, member, candidates, arguments, isRead, isWrite, receiver, sourceFile); } /** @@ -171,6 +204,7 @@ public boolean selfReference() { * none never moves, then UTF-16 code units — what {@link String#compareTo} * compares, and what core's {@code compareText} compares. */ + /** Also MM-8's tiebreak after it: absent first, then {@code other} before {@code self}. */ public static final Comparator MEMBER_ORDER = Comparator.nullsFirst(Comparator.naturalOrder()); public static final Comparator DETERMINISTIC_ORDER = @@ -181,7 +215,8 @@ public boolean selfReference() { .thenComparingInt(e -> e.anchor().startLine()) .thenComparingInt(e -> e.anchor().endLine()) .thenComparing(e -> e.provenance().json()) - .thenComparing(Edge::member, MEMBER_ORDER); + .thenComparing(Edge::member, MEMBER_ORDER) + .thenComparing(Edge::receiver, MEMBER_ORDER); private static void requireText(String value, String what) { if (value == null || value.isBlank()) { diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/model/Entity.java b/extractors/java/src/main/java/dev/codegraph/spoon/model/Entity.java index 1513ac1b..0c348df3 100644 --- a/extractors/java/src/main/java/dev/codegraph/spoon/model/Entity.java +++ b/extractors/java/src/main/java/dev/codegraph/spoon/model/Entity.java @@ -41,6 +41,7 @@ "name", "signature", "declaredType", + "typeExpr", "isStub", "parent", "attachedTo", @@ -59,6 +60,7 @@ public record Entity( String name, String signature, String declaredType, + TypeExpr typeExpr, @JsonProperty("isStub") Boolean isStub, String parent, String attachedTo, @@ -86,6 +88,7 @@ public static final class Builder { private String name; private String signature; private String declaredType; + private TypeExpr typeExpr; private Boolean isStub; private String parent; private String attachedTo; @@ -172,6 +175,17 @@ public Builder typed(String declaredTypeId) { return this; } + /** + * TTypedEntity → {@code declaredType} and {@code typeExpr} (MM-7): the erased + * head and the written tree. A null expression means nothing was written — a + * {@code var}, an implicit lambda parameter, a {@code void} return. + */ + public Builder typed(String declaredTypeId, TypeExpr written) { + typed(declaredTypeId); + this.typeExpr = written; + return this; + } + /** TInvocable → {@code signature}. Part of identity for overloads. */ public Builder invocable(String signature) { if (signature == null) { @@ -259,6 +273,7 @@ public Entity build() { name, signature, declaredType, + typeExpr, isStub, parent, attachedTo, @@ -283,6 +298,24 @@ private static String blankToNull(String value) { } } + /** + * This entity with its type expression closed over the ids the model declares + * (MM-7): a {@code named} node no entity covers becomes {@code unevaluated}, + * since a reference the writer cannot turn into a surrogate is unwritable. + */ + public Entity withTypeExprClosedOver(java.util.function.Predicate declared) { + if (typeExpr == null) { + return this; + } + TypeExpr closed = typeExpr.closedOver(declared); + if (closed == typeExpr) { + return this; + } + return new Entity( + id, kind, traits, name, signature, declaredType, closed, isStub, parent, attachedTo, + parameters, localVariables, definedIn, comments, metrics, value, anchor); + } + /** * METAMODEL.md §6: a stub is any entity declaring TType or TModule with * {@code isStub: true} — the two traits that contribute the key. diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/model/JsonlWriter.java b/extractors/java/src/main/java/dev/codegraph/spoon/model/JsonlWriter.java index 43bff259..b68e6502 100644 --- a/extractors/java/src/main/java/dev/codegraph/spoon/model/JsonlWriter.java +++ b/extractors/java/src/main/java/dev/codegraph/spoon/model/JsonlWriter.java @@ -245,6 +245,10 @@ private void writeEntity( if (entity.declaredType() != null) { generator.writeNumberField("declaredType", surrogates.of(entity.declaredType())); } + if (entity.typeExpr() != null) { + generator.writeFieldName("typeExpr"); + writeTypeExpr(generator, entity.typeExpr(), surrogates); + } if (entity.isStub() != null) { generator.writeBooleanField("isStub", entity.isStub()); } @@ -322,6 +326,9 @@ private void writeEdge( if (edge.isWrite() != null) { generator.writeBooleanField("isWrite", edge.isWrite()); } + if (edge.receiver() != null) { + generator.writeStringField("receiver", edge.receiver()); + } if (edge.sourceFile() != null) { generator.writeNumberField("sourceFile", files.of(edge.sourceFile())); } @@ -358,7 +365,9 @@ private static List sortedEdges(List edges, Surrogates surrogates, F .thenComparingInt(e -> e.anchor().endLine()) .thenComparing(e -> e.provenance().json()) // MM-6: two members of one stub at one site, in one order; absent first. - .thenComparing(Edge::member, Edge.MEMBER_ORDER)); + .thenComparing(Edge::member, Edge.MEMBER_ORDER) + // MM-8: a self and an other access at one site, in one order; absent first. + .thenComparing(Edge::receiver, Edge.MEMBER_ORDER)); return sorted; } @@ -444,6 +453,36 @@ private static void writeLiteral(JsonGenerator out, Literal value, Surrogates su out.writeEndObject(); } + /** + * A type expression (MM-7): `k` first, then the form's keys in core's table + * order, every id a surrogate — a dangling one throws, as any reference does. + */ + private static void writeTypeExpr(JsonGenerator out, TypeExpr expr, Surrogates surrogates) + throws IOException { + out.writeStartObject(); + out.writeStringField("k", expr.k()); + if (expr instanceof TypeExpr.Named named) { + out.writeNumberField("type", surrogates.of(named.type())); + if (named.args() != null) { + out.writeArrayFieldStart("args"); + for (TypeExpr arg : named.args()) { + writeTypeExpr(out, arg, surrogates); + } + out.writeEndArray(); + } + } else if (expr instanceof TypeExpr.Primitive primitive) { + out.writeStringField("name", primitive.name()); + } else if (expr instanceof TypeExpr.Array array) { + out.writeFieldName("of"); + writeTypeExpr(out, array.of(), surrogates); + } else if (expr instanceof TypeExpr.Variable variable) { + out.writeStringField("name", variable.name()); + } else if (expr instanceof TypeExpr.Unevaluated unevaluated) { + out.writeStringField("source", unevaluated.source()); + } + out.writeEndObject(); + } + private static void writeArguments( JsonGenerator out, List arguments, Surrogates surrogates) throws IOException { out.writeArrayFieldStart("arguments"); diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/model/Model.java b/extractors/java/src/main/java/dev/codegraph/spoon/model/Model.java index 41d74a59..3112ac7d 100644 --- a/extractors/java/src/main/java/dev/codegraph/spoon/model/Model.java +++ b/extractors/java/src/main/java/dev/codegraph/spoon/model/Model.java @@ -22,8 +22,8 @@ public record Model( List entities, List edges) { - /** Version of the interchange contract (mirrors SCHEMA_VERSION in @codegraph/core); 1.1.0 since edges name members (MM-6). */ - public static final String SCHEMA_VERSION = "1.1.0"; + /** Version of the interchange contract (mirrors SCHEMA_VERSION in @codegraph/core); 1.2.0 since typed entities carry their written type and accesses their receiver (MM-7, MM-8). */ + public static final String SCHEMA_VERSION = "1.2.0"; /** Profile id — frozen (PLAN.md §4.4): it is the prefix of every id emitted. */ public static final String LANG = "java"; diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/model/TraitName.java b/extractors/java/src/main/java/dev/codegraph/spoon/model/TraitName.java index 4cd21417..4d3df8ff 100644 --- a/extractors/java/src/main/java/dev/codegraph/spoon/model/TraitName.java +++ b/extractors/java/src/main/java/dev/codegraph/spoon/model/TraitName.java @@ -26,6 +26,7 @@ public enum TraitName { TWithInvocations, TStructural, TWithAccesses, + TWithReceiver, TMetrics, TWithValue; @@ -42,7 +43,8 @@ public boolean isMarker() { TWithImplements, TWithInvocations, TStructural, - TWithAccesses -> + TWithAccesses, + TWithReceiver -> true; default -> false; }; diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/model/TypeExpr.java b/extractors/java/src/main/java/dev/codegraph/spoon/model/TypeExpr.java new file mode 100644 index 00000000..d677077e --- /dev/null +++ b/extractors/java/src/main/java/dev/codegraph/spoon/model/TypeExpr.java @@ -0,0 +1,166 @@ +package dev.codegraph.spoon.model; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; + +/** + * The type a declaration WRITES (METAMODEL.md §1.7, MM-7), as a tree: + * {@code List} is a {@code named} List with one argument, where + * {@code declaredType} keeps only the erased head. + * + *

Written, never inferred. No expression on a {@code var}, an + * implicitly typed lambda parameter, a {@code void} return or a constructor. + * A written type this extractor does not structure (a wildcard, an + * intersection) is {@link Unevaluated}, its source text kept. + * + *

Ids inside count for closure as an edge endpoint does, and the writer + * turns them into surrogates. {@link #closedOver} is how a {@link Named} whose + * target no entity declares degrades to its own source text instead of + * dangling. The tag set is core's; Java writes five of its eight forms + * ({@code nullable}, {@code function} and {@code union} are not Java syntax). + */ +public sealed interface TypeExpr { + + /** The tag written as `k`. */ + String k(); + + /** Every entity id this expression points at, in written order. */ + List references(); + + /** + * This expression with every {@link Named} whose target {@code declared} + * refuses replaced by an {@link Unevaluated} of its written text — the node, + * not the whole tree, so what did close is kept. + */ + TypeExpr closedOver(Predicate declared); + + /** + * {@code source} is the node's written text, kept only to degrade it when its + * target does not close; it is never written. + */ + record Named(String type, List args, String source) implements TypeExpr { + public Named { + if (type == null || type.isBlank()) { + throw new IllegalArgumentException("a named type expression needs a target id"); + } + // Canonical form: a raw use writes no list at all, never an empty one. + args = args == null || args.isEmpty() ? null : List.copyOf(args); + } + + @Override + public String k() { + return "named"; + } + + @Override + public List references() { + List out = new ArrayList<>(); + out.add(type); + if (args != null) { + for (TypeExpr arg : args) { + out.addAll(arg.references()); + } + } + return List.copyOf(out); + } + + @Override + public TypeExpr closedOver(Predicate declared) { + if (!declared.test(type)) { + return new Unevaluated(source); + } + if (args == null) { + return this; + } + List closed = new ArrayList<>(args.size()); + boolean changed = false; + for (TypeExpr arg : args) { + TypeExpr closedArg = arg.closedOver(declared); + changed |= closedArg != arg; + closed.add(closedArg); + } + // Identity when nothing moved: the caller counts what was degraded. + return changed ? new Named(type, closed, source) : this; + } + } + + /** {@code int}, {@code long}, {@code boolean}: the language's own word. */ + record Primitive(String name) implements TypeExpr { + @Override + public String k() { + return "primitive"; + } + + @Override + public List references() { + return List.of(); + } + + @Override + public TypeExpr closedOver(Predicate declared) { + return this; + } + } + + /** {@code T[]}, a varargs parameter included; {@code int[][]} nests. */ + record Array(TypeExpr of) implements TypeExpr { + @Override + public String k() { + return "array"; + } + + @Override + public List references() { + return of.references(); + } + + @Override + public TypeExpr closedOver(Predicate declared) { + TypeExpr closed = of.closedOver(declared); + return closed == of ? this : new Array(closed); + } + } + + /** A type parameter, by the name it is written with. */ + record Variable(String name) implements TypeExpr { + @Override + public String k() { + return "variable"; + } + + @Override + public List references() { + return List.of(); + } + + @Override + public TypeExpr closedOver(Predicate declared) { + return this; + } + } + + /** A written type not structured here; the text is still a fact. */ + record Unevaluated(String source) implements TypeExpr { + public Unevaluated { + if (source == null || source.isBlank()) { + throw new IllegalArgumentException("an unevaluated type expression keeps its source text"); + } + } + + @Override + public String k() { + return "unevaluated"; + } + + @Override + public List references() { + return List.of(); + } + + @Override + public TypeExpr closedOver(Predicate declared) { + return this; + } + } +} diff --git a/extractors/java/src/test/java/dev/codegraph/spoon/EntityExtractorTest.java b/extractors/java/src/test/java/dev/codegraph/spoon/EntityExtractorTest.java index d71a18ff..07608d9b 100644 --- a/extractors/java/src/test/java/dev/codegraph/spoon/EntityExtractorTest.java +++ b/extractors/java/src/test/java/dev/codegraph/spoon/EntityExtractorTest.java @@ -213,10 +213,13 @@ public class Loose { Map.entry("enum", traits(TraitName.TComment, TraitName.TMetrics)), Map.entry("record", traits(TraitName.TComment, TraitName.TMetrics)), Map.entry("annotation", traits(TraitName.TComment, TraitName.TMetrics)), - Map.entry("method", traits(TraitName.TComment, TraitName.TMetrics, TraitName.TWithValue)), - Map.entry("constructor", traits(TraitName.TComment, TraitName.TMetrics)), + // TWithReceiver (MM-8) on what needs an instance. + Map.entry( + "method", + traits(TraitName.TComment, TraitName.TMetrics, TraitName.TWithValue, TraitName.TWithReceiver)), + Map.entry("constructor", traits(TraitName.TComment, TraitName.TMetrics, TraitName.TWithReceiver)), Map.entry("lambda", traits(TraitName.TTypedEntity, TraitName.TMetrics)), - Map.entry("attribute", traits(TraitName.TComment, TraitName.TWithValue)), + Map.entry("attribute", traits(TraitName.TComment, TraitName.TWithValue, TraitName.TWithReceiver)), Map.entry("parameter", traits(TraitName.TSourceAnchor)), Map.entry("localVariable", traits(TraitName.TSourceAnchor))); diff --git a/extractors/java/src/test/java/dev/codegraph/spoon/EntityTraitConformanceTest.java b/extractors/java/src/test/java/dev/codegraph/spoon/EntityTraitConformanceTest.java index 01f09329..87d1a489 100644 --- a/extractors/java/src/test/java/dev/codegraph/spoon/EntityTraitConformanceTest.java +++ b/extractors/java/src/test/java/dev/codegraph/spoon/EntityTraitConformanceTest.java @@ -74,7 +74,7 @@ class EntityTraitConformanceTest { kind( of("TNamed", "TInvocable", "TWithChildren", "TWithParameters", "TWithLocalVariables", "TWithInvocations", "TWithAccesses", "TTypedEntity", "TChildOf", "TSourceAnchor"), - of("TComment", "TMetrics", "TWithValue"))), + of("TComment", "TMetrics", "TWithValue", "TWithReceiver"))), // No TNamed (a constructor has no name of its own) and no // TTypedEntity (it has no return type). The id's disambiguator is the signature. Map.entry( @@ -82,7 +82,7 @@ class EntityTraitConformanceTest { kind( of("TInvocable", "TWithChildren", "TWithParameters", "TWithLocalVariables", "TWithInvocations", "TWithAccesses", "TChildOf", "TSourceAnchor"), - of("TComment", "TMetrics"))), + of("TComment", "TMetrics", "TWithReceiver"))), // Lambdas and anonymous classes: invocable but nameless. Map.entry( "lambda", @@ -94,7 +94,7 @@ class EntityTraitConformanceTest { "attribute", kind( of("TNamed", "TStructural", "TTypedEntity", "TChildOf", "TSourceAnchor"), - of("TComment", "TWithValue"))), + of("TComment", "TWithValue", "TWithReceiver"))), Map.entry( "parameter", kind(of("TNamed", "TStructural", "TTypedEntity", "TChildOf"), of("TSourceAnchor"))), diff --git a/extractors/java/src/test/java/dev/codegraph/spoon/ExtractorHarness.java b/extractors/java/src/test/java/dev/codegraph/spoon/ExtractorHarness.java index 9d0fff15..c7a0e5d2 100644 --- a/extractors/java/src/test/java/dev/codegraph/spoon/ExtractorHarness.java +++ b/extractors/java/src/test/java/dev/codegraph/spoon/ExtractorHarness.java @@ -329,6 +329,9 @@ static JsonNode decode(List records, Path source) { copyText(record, entity, "name"); copyText(record, entity, "signature"); copyRef(record, entity, "declaredType", ids); + if (record.has("typeExpr")) { + entity.set("typeExpr", typeExpr(record.path("typeExpr"), ids)); + } if (record.has("isStub")) { entity.put("isStub", record.path("isStub").asBoolean()); } @@ -361,6 +364,7 @@ static JsonNode decode(List records, Path source) { if (record.has("isWrite")) { edge.put("isWrite", record.path("isWrite").asBoolean()); } + copyText(record, edge, "receiver"); if (record.has("sourceFile")) { edge.put("sourceFile", files.get(record.path("sourceFile").asInt())); } @@ -377,6 +381,26 @@ static JsonNode decode(List records, Path source) { return model; } + /** MM-7: the same tree, every `named` target's surrogate back to its id. */ + private static JsonNode typeExpr(JsonNode node, List ids) { + var out = MAPPER.createObjectNode(); + node.fields() + .forEachRemaining( + field -> { + switch (field.getKey()) { + case "type" -> out.put("type", ids.get(field.getValue().asInt())); + case "of" -> out.set("of", typeExpr(field.getValue(), ids)); + case "args", "params" -> { + var array = MAPPER.createArrayNode(); + field.getValue().forEach(item -> array.add(typeExpr(item, ids))); + out.set(field.getKey(), array); + } + default -> out.set(field.getKey(), field.getValue()); + } + }); + return out; + } + private static void assertCount(JsonNode eof, String what, int actual, Path source) { int declared = eof.path("counts").path(what).asInt(-1); if (declared != actual) { diff --git a/extractors/java/src/test/java/dev/codegraph/spoon/JsonlWriterTest.java b/extractors/java/src/test/java/dev/codegraph/spoon/JsonlWriterTest.java index a954dcf1..72876c58 100644 --- a/extractors/java/src/test/java/dev/codegraph/spoon/JsonlWriterTest.java +++ b/extractors/java/src/test/java/dev/codegraph/spoon/JsonlWriterTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -16,6 +17,7 @@ import dev.codegraph.spoon.model.Provenance; import dev.codegraph.spoon.model.SourceAnchor; import dev.codegraph.spoon.model.TraitName; +import dev.codegraph.spoon.model.TypeExpr; import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -98,11 +100,89 @@ void entitiesAreWrittenInNaturalKeyOrderWhateverOrderTheyArriveIn() { } } - /** MM-6: an extractor that names members writes the version that defines them. */ + /** MM-7/MM-8: an extractor that writes type expressions and receivers states the version defining them. */ @Test - void theHeaderStatesSchemaVersionOneOneZero() { + void theHeaderStatesSchemaVersionOneTwoZero() { JsonNode header = records(write(representativeModel()), "header").get(0); - assertEquals("1.1.0", header.path("schemaVersion").asText()); + assertEquals("1.2.0", header.path("schemaVersion").asText()); + } + + /** + * MM-7 on the wire: {@code typeExpr} right after {@code declaredType}, `k` + * first and the form's keys in core's order, every target a surrogate. + */ + @Test + void aTypeExprFollowsDeclaredTypeWithSurrogatesInside() { + String list = "java:java.util/List"; + String line = "java:com.acme.order/Line"; + String field = "java:com.acme.order/Basket.lines"; + TypeExpr written = + new TypeExpr.Named(list, List.of(new TypeExpr.Array(new TypeExpr.Named(line, null, "Line"))), "List"); + List entities = + List.of( + Entity.builder("java:com.acme.order", "package").named("com.acme.order").definedIn(List.of(), false).build(), + Entity.builder("java:java.util", "package").named("java.util").definedIn(List.of(), true).build(), + Entity.builder("java:com.acme.order/Basket", "class").named("Basket").type(false).build(), + Entity.builder(line, "class").named("Line").type(false).build(), + Entity.builder(list, "class").named("List").type(true).build(), + Entity.builder(field, "attribute") + .named("lines") + .marker(TraitName.TStructural) + .typed(list, written) + .marker(TraitName.TWithReceiver) + .childOf("java:com.acme.order/Basket") + .build()); + Model model = Model.sorted(new ExtractorInfo("codegraph-spoon", "0.1.0", Boolean.TRUE), "/corpus", entities, List.of()); + String jsonl = write(model); + String record = jsonl.lines().filter(l -> l.contains("\"s\":\"Basket.lines\"")).findFirst().orElseThrow(); + assertTrue( + record.matches(".*\"declaredType\":(\\d+),\"typeExpr\":\\{\"k\":\"named\",\"type\":\\1,\"args\":\\[\\{\"k\":\"array\",\"of\":\\{\"k\":\"named\",\"type\":\\d+\\}\\}\\]\\},\"parent\".*"), + record); + List violations = ExtractorHarness.schemaViolations(jsonl); + assertTrue(violations.isEmpty(), () -> "schema violations: " + violations); + + // A target nothing declares is unwritable; closing degrades the node instead. + Entity dangling = + Entity.builder(field, "attribute") + .named("lines") + .marker(TraitName.TStructural) + .typed(null, new TypeExpr.Named("java:nowhere/Ghost", null, "Ghost")) + .build(); + assertEquals( + new TypeExpr.Unevaluated("Ghost"), dangling.withTypeExprClosedOver(id -> false).typeExpr()); + Entity kept = entities.get(5); + assertSame(kept, kept.withTypeExprClosedOver(id -> true)); + } + + /** + * MM-8 on the wire: {@code receiver} after {@code isWrite}; a self and an + * other access at one site are two edges, absent first, then other, then self. + */ + @Test + void aReceiverFollowsIsWriteAndBreaksTheLastTie() { + String method = "java:p/A.m()"; + String field = "java:p/A.x"; + SourceAnchor anchor = SourceAnchor.of("p/A.java", 3, 3); + List entities = + List.of( + Entity.builder("java:p", "package").named("p").definedIn(List.of(), false).build(), + Entity.builder("java:p/A", "class").named("A").type(false).build(), + Entity.builder(method, "method").named("m").invocable("m()").childOf("java:p/A").build(), + Entity.builder(field, "attribute").named("x").marker(TraitName.TStructural).childOf("java:p/A").build()); + List edges = + List.of( + Edge.access(method, field, Provenance.DECLARED, anchor, false, true).through(Edge.SELF), + Edge.access(method, field, Provenance.DECLARED, anchor, true, false).through(Edge.OTHER), + Edge.access(method, field, Provenance.DECLARED, anchor, true, false)); + Model model = Model.sorted(new ExtractorInfo("codegraph-spoon", "0.1.0", Boolean.TRUE), "/corpus", entities, edges); + List lines = write(model).lines().filter(l -> l.startsWith("{\"t\":\"x\"")).toList(); + assertEquals(3, lines.size()); + assertFalse(lines.get(0).contains("receiver"), lines.get(0)); + assertTrue(lines.get(1).contains("\"isWrite\":false,\"receiver\":\"other\",\"anchor\""), lines.get(1)); + assertTrue(lines.get(2).contains("\"isWrite\":true,\"receiver\":\"self\",\"anchor\""), lines.get(2)); + assertThrows( + IllegalArgumentException.class, + () -> Edge.reference(method, field, Provenance.DECLARED, anchor).through(Edge.SELF)); } /** diff --git a/extractors/java/src/test/java/dev/codegraph/spoon/ModelSchemaValidationTest.java b/extractors/java/src/test/java/dev/codegraph/spoon/ModelSchemaValidationTest.java index fb915307..a89db356 100644 --- a/extractors/java/src/test/java/dev/codegraph/spoon/ModelSchemaValidationTest.java +++ b/extractors/java/src/test/java/dev/codegraph/spoon/ModelSchemaValidationTest.java @@ -110,8 +110,8 @@ void theFixtureModelIsNotVacuouslyValid() { @Test void theHeaderNamesTheContractAndTheProfile() { - // 1.1.0: edges to stubs name the member the site wrote (MM-6). - assertEquals("1.1.0", run.header().path("schemaVersion").asText()); + // 1.2.0: typed entities carry their written type, accesses their receiver (MM-7, MM-8). + assertEquals("1.2.0", run.header().path("schemaVersion").asText()); assertEquals("java", run.header().path("lang").asText()); assertEquals("codegraph-spoon", run.header().path("extractor").path("name").asText()); assertTrue(run.header().path("extractor").path("noClasspath").asBoolean()); diff --git a/extractors/java/src/test/java/dev/codegraph/spoon/TypeExprAndReceiverTest.java b/extractors/java/src/test/java/dev/codegraph/spoon/TypeExprAndReceiverTest.java new file mode 100644 index 00000000..ddc1240c --- /dev/null +++ b/extractors/java/src/test/java/dev/codegraph/spoon/TypeExprAndReceiverTest.java @@ -0,0 +1,266 @@ +package dev.codegraph.spoon; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.function.Function; +import java.util.stream.Collectors; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * MM-7 and MM-8 (contract 1.2.0) on the fixture corpus, every expectation + * counted by hand from {@code fixtures/java/src}: the written type as a tree, + * {@code TWithReceiver} on what needs an instance, and the receiver an access + * goes through. + */ +class TypeExprAndReceiverTest { + + private static final String P = "java:com.acme.order/"; + private static final String LIST = "java:java.util/List"; + + @TempDir static Path outputDirectory; + + private static Map entities; + private static List accesses; + private static String schemaVersion; + + @BeforeAll + static void extract() { + ExtractorHarness.Run run = + ExtractorHarness.runOnFixtures(outputDirectory.resolve("model.jsonl")).succeeded(); + JsonNode model = run.model(); + schemaVersion = model.path("schemaVersion").asText(); + entities = + ExtractorHarness.elements(model.path("entities")).stream() + .collect(Collectors.toMap(e -> e.path("id").asText(), Function.identity())); + accesses = + ExtractorHarness.elements(model.path("edges")).stream() + .filter(e -> e.path("edge").asText().equals("access")) + .toList(); + } + + @Test + void theHeaderStatesContract120() { + assertEquals("1.2.0", schemaVersion); + } + + // ---------------------------------------------------------------- typeExpr + + @Test + void aPrimitiveIsItsKeyword() { + // Basket: `private long total;` + assertEquals("long", render(P + "Basket.total")); + assertEquals("primitive", typeExpr(P + "Basket.total").path("k").asText()); + } + + @Test + void aGenericKeepsItsArgument() { + // Basket: `private final List lines` — the head is the declaredType too. + JsonNode lines = typeExpr(P + "Basket.lines"); + assertEquals("named", lines.path("k").asText()); + assertEquals(LIST, lines.path("type").asText()); + assertEquals(1, lines.path("args").size()); + assertEquals(P + "Basket.Line", lines.path("args").path(0).path("type").asText()); + assertEquals(LIST, entities.get(P + "Basket.lines").path("declaredType").asText()); + } + + @Test + void anArrayWrapsItsComponent() { + // Batch: `int[] counts`, `Money[] prices`; Reporting.lines(String... rows) is varargs. + assertEquals("array(int)", render(P + "Batch.counts")); + assertEquals("array(" + P + "Money)", render(P + "Batch.prices")); + assertEquals( + "array(java:java.lang/String)", render(P + "Reporting.lines(java.lang.String[])#param:rows")); + } + + @Test + void aWildcardIsKeptAsItsText() { + // OrderService.archive: `java.util.List orders` — the only + // wildcard in the corpus. The id stays erased, and the reference to Order stays. + String orders = P + "OrderService.archive(java.util.List)#param:orders"; + assertEquals(LIST + "<«? extends Order»>", render(orders)); + assertEquals(LIST, entities.get(orders).path("declaredType").asText()); + long unevaluated = + entities.values().stream().filter(e -> render(e).contains("«")).count(); + assertEquals(1, unevaluated, "the corpus writes one type this extractor does not structure"); + } + + @Test + void aTypeVariableIsNamedNotErased() { + // Reporting.max: returns T, takes List, declares `T best` and `T value`; + // Reporting.first: returns T, takes List. Six carriers, every one named T. + Set carriers = new TreeSet<>(); + for (JsonNode entity : entities.values()) { + if (render(entity).contains("$")) { + carriers.add(entity.path("id").asText()); + assertTrue(render(entity).matches("[^$]*(\\$T[^$]*)+"), entity.path("id").asText()); + } + } + assertEquals( + new TreeSet<>( + List.of( + P + "Reporting.max(java.util.List)", + P + "Reporting.max(java.util.List)#param:values", + P + "Reporting.max(java.util.List)#local:best:25", + P + "Reporting.max(java.util.List)#local:value:26", + P + "Reporting.first(java.util.List)", + P + "Reporting.first(java.util.List)#param:values")), + carriers); + assertEquals("$T", render(P + "Reporting.first(java.util.List)")); + assertEquals(LIST + "<$T>", render(P + "Reporting.first(java.util.List)#param:values")); + } + + @Test + void nothingIsInferred() { + // A void return, a constructor and an implicitly typed lambda parameter + // (Notifications: `order -> log(…)`) write no type. + assertFalse(entities.get(P + "StockGuard.ensure(int)").has("typeExpr")); + assertFalse(entities.get(P + "Order.(java.lang.String)").has("typeExpr")); + JsonNode lambdaParameter = + entities.values().stream() + .filter(e -> e.path("kind").asText().equals("parameter")) + .filter(e -> e.path("id").asText().startsWith(P + "Notifications#")) + .findFirst() + .orElseThrow(); + assertFalse(lambdaParameter.has("typeExpr")); + assertTrue(ExtractorHarness.traitsOf(lambdaParameter).contains("TTypedEntity")); + } + + @Test + void everyTypedEntityThatWritesATypeCarriesOne() { + // Typed entities with no typeExpr, by hand: the eight void methods + // (Basket.add, Notifications.log/notifyShipped, OrderService.archive ×2, + // StockGuard.ensure/check, LedgerAdapter.post) and the one lambda parameter. + List without = + entities.values().stream() + .filter(e -> ExtractorHarness.traitsOf(e).contains("TTypedEntity")) + .filter(e -> !e.has("typeExpr")) + .map(e -> e.path("id").asText()) + .sorted() + .toList(); + assertEquals(9, without.size(), without.toString()); + } + + // ------------------------------------------------------------ TWithReceiver + + @Test + void anInstanceMemberHasAReceiverAndAStaticOneDoesNot() { + // Order: `static final int MAX_LINES` vs `private final Channel channel`; + // Money: `static Money zero()` vs `Money times(int)`; Channel.WEB is a constant. + assertTrue(hasReceiver(P + "Order.channel")); + assertFalse(hasReceiver(P + "Order.MAX_LINES")); + assertTrue(hasReceiver(P + "Money.times(int)")); + assertFalse(hasReceiver(P + "Money.zero()")); + assertFalse(hasReceiver(P + "Channel.WEB")); + // A record component, an abstract interface method, an annotation element + // and a constructor all need an instance. + assertTrue(hasReceiver(P + "Money.cents")); + assertTrue(hasReceiver(P + "Priceable.price()")); + assertTrue(hasReceiver(P + "Audited.value()")); + assertTrue(hasReceiver(P + "Order.(java.lang.String)")); + // A lambda and a parameter never do. + for (JsonNode entity : entities.values()) { + String kind = entity.path("kind").asText(); + if (Set.of("lambda", "parameter", "localVariable", "class", "package").contains(kind)) { + assertFalse(hasReceiver(entity.path("id").asText()), entity.path("id").asText()); + } + } + } + + // ----------------------------------------------------------------- receiver + + @Test + void anAccessSaysWhichReceiverItWentThrough() { + // Order(String, Channel): `this.channel = channel` — written `this`. + assertEquals("self", receiverOf(P + "Order.(java.lang.String,com.acme.order.Channel)", P + "Order.channel")); + // Order.discount: `total.times(…)` — implied `this`, a field inherited from AbstractOrder. + assertEquals("self", receiverOf(P + "Order.discount(int)", P + "AbstractOrder.total")); + // Basket.Cursor.next: `lines.get(index++)` — `index` is the cursor's own, + // `lines` the OUTER basket's: another object. + assertEquals("self", receiverOf(P + "Basket.Cursor.next()", P + "Basket.Cursor.index")); + assertEquals("other", receiverOf(P + "Basket.Cursor.next()", P + "Basket.lines")); + // Order(String): `Channel.WEB` is static, `System.out` a stub: neither names one. + assertEquals("-", receiverOf(P + "Order.(java.lang.String)", P + "Channel.WEB")); + assertEquals("-", receiverOf(P + "Notifications.log(java.lang.String)", "java:java.lang/System")); + } + + @Test + void receiversCountedByHand() { + // 33 accesses: 29 through the accessor's own `this` (written, implied or + // inherited), 1 through the outer basket, 3 with none (Channel.WEB is + // static; System.out and LedgerClient.AUDIT_TAG are stubs). + Map counts = new TreeMap<>(); + for (JsonNode access : accesses) { + counts.merge(access.path("receiver").asText("-"), 1, Integer::sum); + } + assertEquals(Map.of("self", 29, "other", 1, "-", 3), counts); + } + + // ----------------------------------------------------------------- helpers + + private static JsonNode typeExpr(String id) { + JsonNode entity = entities.get(id); + assertNotNull(entity, "no entity " + id); + assertTrue(entity.has("typeExpr"), id + " carries no typeExpr"); + return entity.path("typeExpr"); + } + + private static String render(String id) { + return render(typeExpr(id)); + } + + /** A compact rendering: `«…»` an unevaluated text, `$T` a variable. */ + private static String render(JsonNode node) { + if (node.has("typeExpr")) { + return render(node.path("typeExpr")); + } + switch (node.path("k").asText()) { + case "named": + if (!node.has("args")) { + return node.path("type").asText(); + } + return node.path("type").asText() + + "<" + + ExtractorHarness.elements(node.path("args")).stream() + .map(TypeExprAndReceiverTest::render) + .collect(Collectors.joining(",")) + + ">"; + case "primitive": + return node.path("name").asText(); + case "array": + return "array(" + render(node.path("of")) + ")"; + case "variable": + return "$" + node.path("name").asText(); + case "unevaluated": + return "«" + node.path("source").asText() + "»"; + default: + return ""; + } + } + + private static boolean hasReceiver(String id) { + JsonNode entity = entities.get(id); + assertNotNull(entity, "no entity " + id); + return ExtractorHarness.traitsOf(entity).contains("TWithReceiver"); + } + + private static String receiverOf(String from, String to) { + List found = + accesses.stream() + .filter(e -> e.path("from").asText().equals(from) && e.path("to").asText().equals(to)) + .toList(); + assertEquals(1, found.size(), "accesses " + from + " -> " + to); + return found.get(0).path("receiver").asText("-"); + } +} diff --git a/fixtures/java/expected/model.dataop b/fixtures/java/expected/model.dataop new file mode 100644 index 00000000..9aeedec4 --- /dev/null +++ b/fixtures/java/expected/model.dataop @@ -0,0 +1,439 @@ +// A Data & Operation model lowered by codegraph from a code graph (observed): what the graph holds and +// nothing else. Not lowered: states, contracts, flows, descriptions, lineage, domain links. +// receivers (java, contract 1.2.0): TWithReceiver is read as a fact on attribute, constructor, method, and its absence as no receiver; every other kind takes the fallback: every field of a type is a schema field and every method is attached; an access to a field of the operation's own struct or of a flattened supertype reads as `_`. +// types (java): scalars, sequences and optionals from the type table; types from typeExpr. +model src observed { + + external module com.megacorp.ledger + external module java.io + external module java.lang + external module java.time + external module java.util + external module java.util.function + external struct AuditTrail + external struct Invoice + external struct com.megacorp.ledger.LedgerClient + external struct java.io.PrintStream + external struct java.lang.Comparable + external struct java.lang.Object + external struct java.lang.Runnable + external struct java.lang.RuntimeException + external struct java.lang.StringBuilder + external struct java.time.LocalDate + external struct java.util.ArrayList + external struct java.util.Arrays + external struct java.util.List + external struct java.util.function.Consumer + + module com.acme.order { + struct AbstractOrder { + // source: com/acme/order/AbstractOrder.java:4-23 + schema { + reference: string + // source: com/acme/order/AbstractOrder.java:8-8 + total: Money + // source: com/acme/order/AbstractOrder.java:6-6 + } + + operation new(reference: string): AbstractOrder on module + // source: com/acme/order/AbstractOrder.java:10-13 + depends on { Money.zero } + + operation price(): Money + // source: com/acme/order/AbstractOrder.java:20-22 + reads { _.total } + + operation reference(): string + // source: com/acme/order/AbstractOrder.java:15-17 + reads { _.reference } + } + + struct Audited { + // source: com/acme/order/Audited.java:8-11 + schema { + } + + operation value(): string + // source: com/acme/order/Audited.java:10-10 + } + + struct Basket { + // source: com/acme/order/Basket.java:7-57 + schema { + lines: array<@"Basket.Line"> + // source: com/acme/order/Basket.java:11-11 + total: number + // source: com/acme/order/Basket.java:9-9 + } + + operation add(line: @"Basket.Line") + // source: com/acme/order/Basket.java:13-16 + depends on { @"Basket.Line".amount } + uses { java.util.List } + reads { _.lines, _.total } + writes { _.total } + + operation cursor(): @"Basket.Cursor" + // source: com/acme/order/Basket.java:22-24 + depends on { @"Basket.Cursor".new } + + operation new(): Basket on module + // source: com/acme/order/Basket.java:7-57 + + operation total(): number + // source: com/acme/order/Basket.java:18-20 + reads { _.total } + } + + struct @"Basket.Cursor" { + // source: com/acme/order/Basket.java:49-56 + schema { + index: number + // source: com/acme/order/Basket.java:51-51 + } + + operation new(): @"Basket.Cursor" on module + // source: com/acme/order/Basket.java:49-56 + + operation next(): @"Basket.Line" + // source: com/acme/order/Basket.java:53-55 + uses { java.util.List } + reads { _.index } + writes { _.index } + } + + struct @"Basket.Line" { + // source: com/acme/order/Basket.java:27-46 + schema { + amount: number + // source: com/acme/order/Basket.java:29-29 + } + + operation amount(): number + // source: com/acme/order/Basket.java:35-37 + reads { _.amount } + + operation new(amount: number): @"Basket.Line" on module + // source: com/acme/order/Basket.java:31-33 + } + + struct @"Basket.Line.Discount" { + // source: com/acme/order/Basket.java:40-45 + schema { + } + + operation applyTo(amount: number): number + // source: com/acme/order/Basket.java:42-44 + + operation new(): @"Basket.Line.Discount" on module + // source: com/acme/order/Basket.java:40-45 + } + + struct Batch { + // source: com/acme/order/Batch.java:20-62 + schema { + counts: array + // source: com/acme/order/Batch.java:22-22 + prices: array + // source: com/acme/order/Batch.java:24-24 + } + + operation allocator(): opaque "java.util.function.IntFunction" + // source: com/acme/order/Batch.java:42-44 + + operation new(counts: array, prices: array): Batch on module + // source: com/acme/order/Batch.java:26-29 + + operation priced(): number + // source: com/acme/order/Batch.java:37-39 + reads { _.prices } + + operation running(): Priceable + // source: com/acme/order/Batch.java:47-61 + depends on { Money.zero } + + operation @"running.price"(): Money on module + // source: com/acme/order/Batch.java:53-55 + depends on { Batch.@"running.scaled" } + + operation @"running.scaled"(base: Money): Money on module + // source: com/acme/order/Batch.java:57-59 + + operation size(): number + // source: com/acme/order/Batch.java:32-34 + reads { _.counts } + } + + struct Channel { + // source: com/acme/order/Channel.java:4-13 + schema { + } + + global PHONE: Channel = opaque + // source: com/acme/order/Channel.java:6-6 + + global STORE: Channel = opaque + // source: com/acme/order/Channel.java:7-7 + + global WEB: Channel = opaque + // source: com/acme/order/Channel.java:5-5 + + operation new(): Channel on module + // source: com/acme/order/Channel.java:4-13 + + operation price(): Money + // source: com/acme/order/Channel.java:10-12 + depends on { Money.zero } + } + + struct Discountable { + // source: com/acme/order/Discountable.java:4-7 + // NOTE: the schema flattens the fields of Priceable: Specy has no inheritance + schema { + } + + operation discount(percent: number): Money + // source: com/acme/order/Discountable.java:6-6 + } + + struct EmptyBasketException { + // source: com/acme/order/EmptyBasketException.java:4-9 + // NOTE: supertypes outside the model, their fields unknown: java.lang.RuntimeException + schema { + } + + operation new(message: string): EmptyBasketException on module + // source: com/acme/order/EmptyBasketException.java:6-8 + uses { java.lang.RuntimeException } + } + + struct Money { + // source: com/acme/order/Money.java:4-18 + schema { + cents: number + // source: com/acme/order/Money.java:4-18 + } + + operation cents(): number + // source: com/acme/order/Money.java:4-18 + + operation new(cents: number): Money on module + // source: com/acme/order/Money.java:4-18 + + operation price(): Money + // source: com/acme/order/Money.java:15-17 + + operation times(factor: number): Money + // source: com/acme/order/Money.java:10-12 + depends on { Money.new } + reads { _.cents } + + operation zero(): Money on module + // source: com/acme/order/Money.java:6-8 + depends on { Money.new } + } + + struct Notifications { + // source: com/acme/order/Notifications.java:6-39 + schema { + onShipped: opaque "java.util.function.Consumer" + // source: com/acme/order/Notifications.java:8-8 + } + + operation both(order: Order): java.lang.Runnable + // source: com/acme/order/Notifications.java:10-12 + depends on { AbstractOrder.reference, Notifications.chain, Notifications.log } + + operation chain(first: java.lang.Runnable, second: java.lang.Runnable): java.lang.Runnable + // source: com/acme/order/Notifications.java:14-19 + uses { java.lang.Runnable } + + operation freeOf(order: Order): Priceable + // source: com/acme/order/Notifications.java:21-30 + + operation @"freeOf.price"(): Money on module + // source: com/acme/order/Notifications.java:25-28 + depends on { AbstractOrder.reference, Money.zero, Notifications.log } + + operation log(message: string) + // source: com/acme/order/Notifications.java:36-38 + uses { java.io.PrintStream } + + operation new(): Notifications on module + // source: com/acme/order/Notifications.java:6-39 + + operation notifyShipped(order: Order) + // source: com/acme/order/Notifications.java:32-34 + uses { java.util.function.Consumer } + reads { _.onShipped } + } + + struct Order { + // source: com/acme/order/Order.java:6-35 + // NOTE: the schema flattens the fields of AbstractOrder: Specy has no inheritance + schema { + channel: Channel + // source: com/acme/order/Order.java:14-14 + trail: java.lang.StringBuilder + // source: com/acme/order/Order.java:12-12 + reference: string + // source: com/acme/order/AbstractOrder.java:8-8 + total: Money + // source: com/acme/order/AbstractOrder.java:6-6 + } + + global MAX_LINES: number = 100 + // source: com/acme/order/Order.java:9-9 + + operation channel(): Channel + // source: com/acme/order/Order.java:25-27 + reads { _.channel } + + operation discount(percent: number): Money + // source: com/acme/order/Order.java:31-34 + depends on { Money.times } + reads { _.total } + + operation new(reference: string): Order on module + // source: com/acme/order/Order.java:16-18 + depends on { Order.new(string, Channel) } + reads { Channel.WEB } + + operation new(reference: string, channel: Channel): Order on module + // source: com/acme/order/Order.java:20-23 + depends on { AbstractOrder.new } + } + + struct OrderService { + // source: com/acme/order/OrderService.java:9-32 + schema { + ledger: com.megacorp.ledger.LedgerClient + // source: com/acme/order/OrderService.java:11-11 + } + + operation archive(orders: array) + // source: com/acme/order/OrderService.java:23-27 + // FINDING: branching: cyclomatic 2 + depends on { AbstractOrder.reference } + uses { com.megacorp.ledger.LedgerClient } + reads { _.ledger } + + operation archive(orders: com.acme.order.legacy.List) + // source: com/acme/order/OrderService.java:29-31 + depends on { com.acme.order.legacy.List.head } + uses { com.megacorp.ledger.LedgerClient } + reads { _.ledger } + + operation bill(order: Order): Invoice + // source: com/acme/order/OrderService.java:17-21 + depends on { AbstractOrder.reference } + uses { Invoice, com.megacorp.ledger.LedgerClient } + reads { _.ledger } + + operation new(ledger: com.megacorp.ledger.LedgerClient): OrderService on module + // source: com/acme/order/OrderService.java:13-15 + } + + struct Priceable { + // source: com/acme/order/Priceable.java:4-7 + schema { + } + + operation price(): Money + // source: com/acme/order/Priceable.java:6-6 + } + + struct Reporting { + // source: com/acme/order/Reporting.java:9-41 + schema { + } + + operation first(values: array): opaque "T" + // source: com/acme/order/Reporting.java:34-36 + // FINDING: branching: cyclomatic 2 + uses { java.util.List } + + operation join(parts: array): string + // source: com/acme/order/Reporting.java:15-21 + // FINDING: branching: cyclomatic 2 + uses { java.lang.StringBuilder } + + operation lines(rows: array): opaque "java.util.ArrayList" + // source: com/acme/order/Reporting.java:11-13 + uses { java.util.ArrayList, java.util.Arrays } + + operation max(values: array): opaque "T" + // source: com/acme/order/Reporting.java:24-32 + // FINDING: branching: cyclomatic 4 + uses { java.lang.Comparable } + + operation new(): Reporting on module + // source: com/acme/order/Reporting.java:9-41 + + operation today(): java.time.LocalDate + // source: com/acme/order/Reporting.java:38-40 + uses { java.time.LocalDate } + } + + struct StockGuard { + // source: com/acme/order/StockGuard.java:9-24 + schema { + } + + operation check(quantity: number) + // source: com/acme/order/StockGuard.java:22-23 + + operation ensure(quantity: number) + // source: com/acme/order/StockGuard.java:11-20 + // FINDING: branching: cyclomatic 3 + errors { EmptyBasketException of EmptyBasketException } + depends on { EmptyBasketException.new, StockGuard.check } + + operation new(): StockGuard on module + // source: com/acme/order/StockGuard.java:9-24 + } + } + + module com.acme.order.adapter { + struct LedgerAdapter { + // source: com/acme/order/adapter/LedgerAdapter.java:6-15 + // NOTE: supertypes outside the model, their fields unknown: com.megacorp.ledger.LedgerClient + schema { + trail: AuditTrail + // source: com/acme/order/adapter/LedgerAdapter.java:8-8 + } + + operation new(): LedgerAdapter on module + // source: com/acme/order/adapter/LedgerAdapter.java:6-15 + + operation post(document: java.lang.Object) + // source: com/acme/order/adapter/LedgerAdapter.java:11-14 + uses { AuditTrail, com.megacorp.ledger.LedgerClient } + reads { _.trail } + } + } + + module com.acme.order.legacy { + struct List { + // source: com/acme/order/legacy/List.java:4-22 + schema { + head: string + // source: com/acme/order/legacy/List.java:6-6 + tail: List + // source: com/acme/order/legacy/List.java:8-8 + } + + operation head(): string + // source: com/acme/order/legacy/List.java:15-17 + reads { _.head } + + operation length(): number + // source: com/acme/order/legacy/List.java:19-21 + // FINDING: branching: cyclomatic 2 + reads { _.tail } + + operation new(head: string, tail: List): List on module + // source: com/acme/order/legacy/List.java:10-13 + } + } +} diff --git a/fixtures/java/expected/model.jsonl b/fixtures/java/expected/model.jsonl index c6ef6b6a..98041c63 100644 --- a/fixtures/java/expected/model.jsonl +++ b/fixtures/java/expected/model.jsonl @@ -1,4 +1,4 @@ -{"t":"header","schemaVersion":"1.1.0","lang":"java","extractor":{"name":"codegraph-spoon","version":"0.4.0","noClasspath":true},"root":"fixtures/java/src","dict":{"kinds":["annotation","attribute","class","constructor","enum","interface","lambda","localVariable","method","package","parameter","record"],"traits":["TChildOf","TComment","TInvocable","TMetrics","TModule","TNamed","TSourceAnchor","TStructural","TType","TTypedEntity","TWithAccesses","TWithChildren","TWithImplements","TWithInheritances","TWithInvocations","TWithLocalVariables","TWithParameters","TWithValue"],"edges":["access","annotationUse","import","inheritance","interfaceImplementation","invocation","reference","throws"],"provenance":["declared","derived"]}} +{"t":"header","schemaVersion":"1.2.0","lang":"java","extractor":{"name":"codegraph-spoon","version":"0.4.0","noClasspath":true},"root":"fixtures/java/src","dict":{"kinds":["annotation","attribute","class","constructor","enum","interface","lambda","localVariable","method","package","parameter","record"],"traits":["TChildOf","TComment","TInvocable","TMetrics","TModule","TNamed","TSourceAnchor","TStructural","TType","TTypedEntity","TWithAccesses","TWithChildren","TWithImplements","TWithInheritances","TWithInvocations","TWithLocalVariables","TWithParameters","TWithReceiver","TWithValue"],"edges":["access","annotationUse","import","inheritance","interfaceImplementation","invocation","reference","throws"],"provenance":["declared","derived"]}} {"t":"f","i":0,"path":"com/acme/order/AbstractOrder.java"} {"t":"f","i":1,"path":"com/acme/order/Audited.java"} {"t":"f","i":2,"path":"com/acme/order/Basket.java"} @@ -17,158 +17,158 @@ {"t":"f","i":15,"path":"com/acme/order/legacy/List.java"} {"t":"e","i":0,"k":9,"tr":[5,11,4],"m":0,"s":"com.acme.order","name":"com.acme.order","isStub":false,"definedIn":[0,1,2,3,4,5,6,7,8,9,10,11,12,13]} {"t":"e","i":1,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"AbstractOrder","name":"AbstractOrder","isStub":false,"parent":0,"comments":["Shared state for every kind of order."],"metrics":{"sloc":15},"anchor":[0,4,23]} -{"t":"e","i":2,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"AbstractOrder.(java.lang.String)","signature":"(java.lang.String)","parent":1,"parameters":[3],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[0,10,13]} -{"t":"e","i":3,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"AbstractOrder.(java.lang.String)","d":"param:reference","name":"reference","declaredType":164,"parent":2,"anchor":[0,10,10]} -{"t":"e","i":4,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"AbstractOrder.price()","name":"price","signature":"price()","declaredType":60,"parent":1,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[0,20,22]} -{"t":"e","i":5,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"AbstractOrder.reference","name":"reference","declaredType":164,"parent":1,"anchor":[0,8,8]} -{"t":"e","i":6,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"AbstractOrder.reference()","name":"reference","signature":"reference()","declaredType":164,"parent":1,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[0,15,17]} -{"t":"e","i":7,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"AbstractOrder.total","name":"total","declaredType":60,"parent":1,"anchor":[0,6,6]} +{"t":"e","i":2,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"AbstractOrder.(java.lang.String)","signature":"(java.lang.String)","parent":1,"parameters":[3],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[0,10,13]} +{"t":"e","i":3,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"AbstractOrder.(java.lang.String)","d":"param:reference","name":"reference","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":2,"anchor":[0,10,10]} +{"t":"e","i":4,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"AbstractOrder.price()","name":"price","signature":"price()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":1,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[0,20,22]} +{"t":"e","i":5,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"AbstractOrder.reference","name":"reference","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":1,"anchor":[0,8,8]} +{"t":"e","i":6,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"AbstractOrder.reference()","name":"reference","signature":"reference()","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":1,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[0,15,17]} +{"t":"e","i":7,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"AbstractOrder.total","name":"total","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":1,"anchor":[0,6,6]} {"t":"e","i":8,"k":0,"tr":[5,6,1,11,0,8,3],"m":0,"s":"Audited","name":"Audited","isStub":false,"parent":0,"comments":["Marks a method whose calls must reach the audit log."],"metrics":{"sloc":3},"anchor":[1,8,11]} -{"t":"e","i":9,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3,17],"m":0,"s":"Audited.value()","name":"value","signature":"value()","declaredType":164,"parent":8,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"value":{"k":"string","v":""},"anchor":[1,10,10]} +{"t":"e","i":9,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3,18],"m":0,"s":"Audited.value()","name":"value","signature":"value()","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":8,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"value":{"k":"string","v":""},"anchor":[1,10,10]} {"t":"e","i":10,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Basket","name":"Basket","isStub":false,"parent":0,"comments":["A basket being filled. Declares no constructor of its own."],"metrics":{"sloc":34},"anchor":[2,7,57]} -{"t":"e","i":11,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Basket.()","signature":"()","parent":10,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[2,7,57]} +{"t":"e","i":11,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Basket.()","signature":"()","parent":10,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[2,7,57]} {"t":"e","i":12,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Basket.Cursor","name":"Cursor","isStub":false,"parent":10,"comments":["Non-static inner: reads the enclosing Basket's fields."],"metrics":{"sloc":6},"anchor":[2,49,56]} -{"t":"e","i":13,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Basket.Cursor.()","signature":"()","parent":12,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[2,49,56]} -{"t":"e","i":14,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Basket.Cursor.index","name":"index","parent":12,"anchor":[2,51,51]} -{"t":"e","i":15,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Basket.Cursor.next()","name":"next","signature":"next()","declaredType":16,"parent":12,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[2,53,55]} +{"t":"e","i":13,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Basket.Cursor.()","signature":"()","parent":12,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[2,49,56]} +{"t":"e","i":14,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Basket.Cursor.index","name":"index","typeExpr":{"k":"primitive","name":"int"},"parent":12,"anchor":[2,51,51]} +{"t":"e","i":15,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Basket.Cursor.next()","name":"next","signature":"next()","declaredType":16,"typeExpr":{"k":"named","type":16},"parent":12,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[2,53,55]} {"t":"e","i":16,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Basket.Line","name":"Line","isStub":false,"parent":10,"comments":["Static nested: no enclosing Basket instance."],"metrics":{"sloc":14},"anchor":[2,27,46]} -{"t":"e","i":17,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Basket.Line.(long)","signature":"(long)","parent":16,"parameters":[18],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[2,31,33]} -{"t":"e","i":18,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Basket.Line.(long)","d":"param:amount","name":"amount","parent":17,"anchor":[2,31,31]} +{"t":"e","i":17,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Basket.Line.(long)","signature":"(long)","parent":16,"parameters":[18],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[2,31,33]} +{"t":"e","i":18,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Basket.Line.(long)","d":"param:amount","name":"amount","typeExpr":{"k":"primitive","name":"long"},"parent":17,"anchor":[2,31,31]} {"t":"e","i":19,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Basket.Line.Discount","name":"Discount","isStub":false,"parent":16,"comments":["Nested inside a nested type."],"metrics":{"sloc":5},"anchor":[2,40,45]} -{"t":"e","i":20,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Basket.Line.Discount.()","signature":"()","parent":19,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[2,40,45]} -{"t":"e","i":21,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Basket.Line.Discount.applyTo(long)","name":"applyTo","signature":"applyTo(long)","parent":19,"parameters":[22],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[2,42,44]} -{"t":"e","i":22,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Basket.Line.Discount.applyTo(long)","d":"param:amount","name":"amount","parent":21,"anchor":[2,42,42]} -{"t":"e","i":23,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Basket.Line.amount","name":"amount","parent":16,"anchor":[2,29,29]} -{"t":"e","i":24,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Basket.Line.amount()","name":"amount","signature":"amount()","parent":16,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[2,35,37]} -{"t":"e","i":25,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Basket.add(com.acme.order.Basket.Line)","name":"add","signature":"add(com.acme.order.Basket.Line)","parent":10,"parameters":[26],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[2,13,16]} -{"t":"e","i":26,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Basket.add(com.acme.order.Basket.Line)","d":"param:line","name":"line","declaredType":16,"parent":25,"anchor":[2,13,13]} -{"t":"e","i":27,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Basket.cursor()","name":"cursor","signature":"cursor()","declaredType":12,"parent":10,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[2,22,24]} -{"t":"e","i":28,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Basket.lines","name":"lines","declaredType":175,"parent":10,"anchor":[2,11,11]} -{"t":"e","i":29,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Basket.total","name":"total","parent":10,"anchor":[2,9,9]} -{"t":"e","i":30,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Basket.total()","name":"total","signature":"total()","parent":10,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[2,18,20]} +{"t":"e","i":20,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Basket.Line.Discount.()","signature":"()","parent":19,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[2,40,45]} +{"t":"e","i":21,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Basket.Line.Discount.applyTo(long)","name":"applyTo","signature":"applyTo(long)","typeExpr":{"k":"primitive","name":"long"},"parent":19,"parameters":[22],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[2,42,44]} +{"t":"e","i":22,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Basket.Line.Discount.applyTo(long)","d":"param:amount","name":"amount","typeExpr":{"k":"primitive","name":"long"},"parent":21,"anchor":[2,42,42]} +{"t":"e","i":23,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Basket.Line.amount","name":"amount","typeExpr":{"k":"primitive","name":"long"},"parent":16,"anchor":[2,29,29]} +{"t":"e","i":24,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Basket.Line.amount()","name":"amount","signature":"amount()","typeExpr":{"k":"primitive","name":"long"},"parent":16,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[2,35,37]} +{"t":"e","i":25,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Basket.add(com.acme.order.Basket.Line)","name":"add","signature":"add(com.acme.order.Basket.Line)","parent":10,"parameters":[26],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[2,13,16]} +{"t":"e","i":26,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Basket.add(com.acme.order.Basket.Line)","d":"param:line","name":"line","declaredType":16,"typeExpr":{"k":"named","type":16},"parent":25,"anchor":[2,13,13]} +{"t":"e","i":27,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Basket.cursor()","name":"cursor","signature":"cursor()","declaredType":12,"typeExpr":{"k":"named","type":12},"parent":10,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[2,22,24]} +{"t":"e","i":28,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Basket.lines","name":"lines","declaredType":175,"typeExpr":{"k":"named","type":175,"args":[{"k":"named","type":16}]},"parent":10,"anchor":[2,11,11]} +{"t":"e","i":29,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Basket.total","name":"total","typeExpr":{"k":"primitive","name":"long"},"parent":10,"anchor":[2,9,9]} +{"t":"e","i":30,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Basket.total()","name":"total","signature":"total()","typeExpr":{"k":"primitive","name":"long"},"parent":10,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[2,18,20]} {"t":"e","i":31,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Batch","name":"Batch","isStub":false,"parent":0,"comments":["Array members and an anonymous class that uses its own members.\n\n

Both were blind spots found by auditing a real corpus (commons-lang), not by\nthis corpus: arrays were present but nothing ever read `array.length`, and an\nanonymous class was present but nothing inside it touched its own fields.\n\n

`counts.length` and `int[]::new` declare their member on the ARRAY type. An\narray is not an entity, and its component type does not own those members —\nattributing them to the component invented a stub class named `int` and an\naccess on `com.acme.order.Money` that the source never writes.\n\n

The anonymous `Priceable` is identified by `#file:line`; Spoon names it\n`Batch$1`, so any edge that names it from a type REFERENCE must be translated\nback, or one declared class ends up with two ids and the second is laundered\ninto a stub carrying the corpus's own package."],"metrics":{"sloc":29},"anchor":[3,20,62]} {"t":"e","i":32,"k":6,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32","signature":"com.acme.order.Priceable()","parent":45,"parameters":[],"localVariables":[],"metrics":{"sloc":10},"anchor":[3,48,60]} -{"t":"e","i":33,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.()","signature":"()","parent":32,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[3,48,60]} -{"t":"e","i":34,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.price()","name":"price","signature":"price()","declaredType":60,"parent":32,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[3,53,55]} -{"t":"e","i":35,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.running","name":"running","declaredType":60,"parent":32,"anchor":[3,50,50]} -{"t":"e","i":36,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.scaled(com.acme.order.Money)","name":"scaled","signature":"scaled(com.acme.order.Money)","declaredType":60,"parent":32,"parameters":[37],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[3,57,59]} -{"t":"e","i":37,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.scaled(com.acme.order.Money)#param:base","name":"base","declaredType":60,"parent":36,"anchor":[3,57,57]} -{"t":"e","i":38,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Batch.(int[],com.acme.order.Money[])","signature":"(int[],com.acme.order.Money[])","parent":31,"parameters":[39,40],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[3,26,29]} -{"t":"e","i":39,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Batch.(int[],com.acme.order.Money[])","d":"param:counts","name":"counts","parent":38,"anchor":[3,26,26]} -{"t":"e","i":40,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Batch.(int[],com.acme.order.Money[])","d":"param:prices","name":"prices","declaredType":60,"parent":38,"anchor":[3,26,26]} -{"t":"e","i":41,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,3],"m":0,"s":"Batch.allocator()","name":"allocator","signature":"allocator()","declaredType":178,"parent":31,"parameters":[],"localVariables":[],"comments":["`int[]::new` — a constructor declared on the array type."],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[3,42,44]} -{"t":"e","i":42,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Batch.counts","name":"counts","parent":31,"anchor":[3,22,22]} -{"t":"e","i":43,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,3],"m":0,"s":"Batch.priced()","name":"priced","signature":"priced()","parent":31,"parameters":[],"localVariables":[],"comments":["`prices.length` — a field of `Money[]`, not of `Money`."],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[3,37,39]} -{"t":"e","i":44,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Batch.prices","name":"prices","declaredType":60,"parent":31,"anchor":[3,24,24]} -{"t":"e","i":45,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,3],"m":0,"s":"Batch.running()","name":"running","signature":"running()","declaredType":115,"parent":31,"parameters":[],"localVariables":[],"comments":["An anonymous class that reads its own field and calls its own method."],"metrics":{"cyclomatic":1,"sloc":12},"anchor":[3,47,61]} -{"t":"e","i":46,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,3],"m":0,"s":"Batch.size()","name":"size","signature":"size()","parent":31,"parameters":[],"localVariables":[],"comments":["`counts.length` — a field of `int[]`, not of `int`."],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[3,32,34]} +{"t":"e","i":33,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.()","signature":"()","parent":32,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[3,48,60]} +{"t":"e","i":34,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.price()","name":"price","signature":"price()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":32,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[3,53,55]} +{"t":"e","i":35,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.running","name":"running","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":32,"anchor":[3,50,50]} +{"t":"e","i":36,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.scaled(com.acme.order.Money)","name":"scaled","signature":"scaled(com.acme.order.Money)","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":32,"parameters":[37],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[3,57,59]} +{"t":"e","i":37,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.scaled(com.acme.order.Money)#param:base","name":"base","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":36,"anchor":[3,57,57]} +{"t":"e","i":38,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Batch.(int[],com.acme.order.Money[])","signature":"(int[],com.acme.order.Money[])","parent":31,"parameters":[39,40],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[3,26,29]} +{"t":"e","i":39,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Batch.(int[],com.acme.order.Money[])","d":"param:counts","name":"counts","typeExpr":{"k":"array","of":{"k":"primitive","name":"int"}},"parent":38,"anchor":[3,26,26]} +{"t":"e","i":40,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Batch.(int[],com.acme.order.Money[])","d":"param:prices","name":"prices","declaredType":60,"typeExpr":{"k":"array","of":{"k":"named","type":60}},"parent":38,"anchor":[3,26,26]} +{"t":"e","i":41,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Batch.allocator()","name":"allocator","signature":"allocator()","declaredType":178,"typeExpr":{"k":"named","type":178,"args":[{"k":"array","of":{"k":"primitive","name":"int"}}]},"parent":31,"parameters":[],"localVariables":[],"comments":["`int[]::new` — a constructor declared on the array type."],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[3,42,44]} +{"t":"e","i":42,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Batch.counts","name":"counts","typeExpr":{"k":"array","of":{"k":"primitive","name":"int"}},"parent":31,"anchor":[3,22,22]} +{"t":"e","i":43,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Batch.priced()","name":"priced","signature":"priced()","typeExpr":{"k":"primitive","name":"int"},"parent":31,"parameters":[],"localVariables":[],"comments":["`prices.length` — a field of `Money[]`, not of `Money`."],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[3,37,39]} +{"t":"e","i":44,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Batch.prices","name":"prices","declaredType":60,"typeExpr":{"k":"array","of":{"k":"named","type":60}},"parent":31,"anchor":[3,24,24]} +{"t":"e","i":45,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Batch.running()","name":"running","signature":"running()","declaredType":115,"typeExpr":{"k":"named","type":115},"parent":31,"parameters":[],"localVariables":[],"comments":["An anonymous class that reads its own field and calls its own method."],"metrics":{"cyclomatic":1,"sloc":12},"anchor":[3,47,61]} +{"t":"e","i":46,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Batch.size()","name":"size","signature":"size()","typeExpr":{"k":"primitive","name":"int"},"parent":31,"parameters":[],"localVariables":[],"comments":["`counts.length` — a field of `int[]`, not of `int`."],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[3,32,34]} {"t":"e","i":47,"k":4,"tr":[5,6,1,11,0,8,12,3],"m":0,"s":"Channel","name":"Channel","isStub":false,"parent":0,"comments":["Where an order came from."],"metrics":{"sloc":9},"anchor":[4,4,13]} -{"t":"e","i":48,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Channel.()","signature":"()","parent":47,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[4,4,13]} -{"t":"e","i":49,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Channel.PHONE","name":"PHONE","declaredType":47,"parent":47,"anchor":[4,6,6]} -{"t":"e","i":50,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Channel.STORE","name":"STORE","declaredType":47,"parent":47,"anchor":[4,7,7]} -{"t":"e","i":51,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Channel.WEB","name":"WEB","declaredType":47,"parent":47,"anchor":[4,5,5]} -{"t":"e","i":52,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Channel.price()","name":"price","signature":"price()","declaredType":60,"parent":47,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[4,10,12]} +{"t":"e","i":48,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Channel.()","signature":"()","parent":47,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[4,4,13]} +{"t":"e","i":49,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Channel.PHONE","name":"PHONE","declaredType":47,"typeExpr":{"k":"named","type":47},"parent":47,"anchor":[4,6,6]} +{"t":"e","i":50,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Channel.STORE","name":"STORE","declaredType":47,"typeExpr":{"k":"named","type":47},"parent":47,"anchor":[4,7,7]} +{"t":"e","i":51,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Channel.WEB","name":"WEB","declaredType":47,"typeExpr":{"k":"named","type":47},"parent":47,"anchor":[4,5,5]} +{"t":"e","i":52,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Channel.price()","name":"price","signature":"price()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":47,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[4,10,12]} {"t":"e","i":53,"k":5,"tr":[5,6,1,11,0,8,13,3],"m":0,"s":"Discountable","name":"Discountable","isStub":false,"parent":0,"comments":["An order that can be marked down. Extends another corpus interface."],"metrics":{"sloc":3},"anchor":[5,4,7]} -{"t":"e","i":54,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Discountable.discount(int)","name":"discount","signature":"discount(int)","declaredType":60,"parent":53,"parameters":[55],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"anchor":[5,6,6]} -{"t":"e","i":55,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Discountable.discount(int)","d":"param:percent","name":"percent","parent":54,"anchor":[5,6,6]} +{"t":"e","i":54,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Discountable.discount(int)","name":"discount","signature":"discount(int)","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":53,"parameters":[55],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"anchor":[5,6,6]} +{"t":"e","i":55,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Discountable.discount(int)","d":"param:percent","name":"percent","typeExpr":{"k":"primitive","name":"int"},"parent":54,"anchor":[5,6,6]} {"t":"e","i":56,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"EmptyBasketException","name":"EmptyBasketException","isStub":false,"parent":0,"comments":["The corpus-declared exception the throw-site regression case targets."],"metrics":{"sloc":5},"anchor":[6,4,9]} -{"t":"e","i":57,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"EmptyBasketException.(java.lang.String)","signature":"(java.lang.String)","parent":56,"parameters":[58],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[6,6,8]} -{"t":"e","i":58,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"EmptyBasketException.(java.lang.String)","d":"param:message","name":"message","declaredType":164,"parent":57,"anchor":[6,6,6]} +{"t":"e","i":57,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"EmptyBasketException.(java.lang.String)","signature":"(java.lang.String)","parent":56,"parameters":[58],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[6,6,8]} +{"t":"e","i":58,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"EmptyBasketException.(java.lang.String)","d":"param:message","name":"message","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":57,"anchor":[6,6,6]} {"t":"e","i":59,"k":2,"tr":[5,8],"m":0,"s":"Invoice","name":"Invoice","isStub":true} {"t":"e","i":60,"k":11,"tr":[5,6,1,11,0,8,12,3],"m":0,"s":"Money","name":"Money","isStub":false,"parent":0,"comments":["Minor units only; this fixture has no currencies."],"metrics":{"sloc":12},"anchor":[7,4,18]} -{"t":"e","i":61,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Money.(long)","signature":"(long)","parent":60,"parameters":[62],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[7,4,18]} -{"t":"e","i":62,"k":10,"tr":[5,0,9,7],"m":0,"s":"Money.(long)","d":"param:cents","name":"cents","parent":61} -{"t":"e","i":63,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Money.cents","name":"cents","parent":60,"anchor":[7,4,18]} -{"t":"e","i":64,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Money.cents()","name":"cents","signature":"cents()","parent":60,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[7,4,18]} -{"t":"e","i":65,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Money.price()","name":"price","signature":"price()","declaredType":60,"parent":60,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[7,15,17]} -{"t":"e","i":66,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Money.times(int)","name":"times","signature":"times(int)","declaredType":60,"parent":60,"parameters":[67],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[7,10,12]} -{"t":"e","i":67,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Money.times(int)","d":"param:factor","name":"factor","parent":66,"anchor":[7,10,10]} -{"t":"e","i":68,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Money.zero()","name":"zero","signature":"zero()","declaredType":60,"parent":60,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[7,6,8]} +{"t":"e","i":61,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Money.(long)","signature":"(long)","parent":60,"parameters":[62],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[7,4,18]} +{"t":"e","i":62,"k":10,"tr":[5,0,9,7],"m":0,"s":"Money.(long)","d":"param:cents","name":"cents","typeExpr":{"k":"primitive","name":"long"},"parent":61} +{"t":"e","i":63,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Money.cents","name":"cents","typeExpr":{"k":"primitive","name":"long"},"parent":60,"anchor":[7,4,18]} +{"t":"e","i":64,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Money.cents()","name":"cents","signature":"cents()","typeExpr":{"k":"primitive","name":"long"},"parent":60,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[7,4,18]} +{"t":"e","i":65,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Money.price()","name":"price","signature":"price()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":60,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[7,15,17]} +{"t":"e","i":66,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Money.times(int)","name":"times","signature":"times(int)","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":60,"parameters":[67],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[7,10,12]} +{"t":"e","i":67,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Money.times(int)","d":"param:factor","name":"factor","typeExpr":{"k":"primitive","name":"int"},"parent":66,"anchor":[7,10,10]} +{"t":"e","i":68,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Money.zero()","name":"zero","signature":"zero()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":60,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[7,6,8]} {"t":"e","i":69,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Notifications","name":"Notifications","isStub":false,"parent":0,"comments":["Delivery hooks. Nothing invocable in here has a name of its own."],"metrics":{"sloc":27},"anchor":[8,6,39]} {"t":"e","i":70,"k":6,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:11:22","signature":"()","parent":79,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"anchor":[8,11,11]} {"t":"e","i":71,"k":6,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:11:65","signature":"()","parent":79,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"anchor":[8,11,11]} {"t":"e","i":72,"k":6,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:15:16","signature":"()","parent":81,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[8,15,18]} {"t":"e","i":73,"k":6,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:22:32","signature":"com.acme.order.Priceable()","parent":84,"parameters":[],"localVariables":[],"metrics":{"sloc":7},"anchor":[8,22,29]} -{"t":"e","i":74,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:22:32.()","signature":"()","parent":73,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[8,22,29]} -{"t":"e","i":75,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:22:32.price()","name":"price","signature":"price()","declaredType":60,"parent":73,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[8,25,28]} +{"t":"e","i":74,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:22:32.()","signature":"()","parent":73,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[8,22,29]} +{"t":"e","i":75,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:22:32.price()","name":"price","signature":"price()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":73,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[8,25,28]} {"t":"e","i":76,"k":6,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:8:47","signature":"(com.acme.order.Order)","parent":69,"parameters":[77],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"anchor":[8,8,8]} {"t":"e","i":77,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:8:47#param:order","name":"order","declaredType":91,"parent":76,"anchor":[8,8,8]} -{"t":"e","i":78,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications.()","signature":"()","parent":69,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[8,6,39]} -{"t":"e","i":79,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Notifications.both(com.acme.order.Order)","name":"both","signature":"both(com.acme.order.Order)","declaredType":162,"parent":69,"parameters":[80],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[8,10,12]} -{"t":"e","i":80,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.both(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"parent":79,"anchor":[8,10,10]} -{"t":"e","i":81,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Notifications.chain(java.lang.Runnable,java.lang.Runnable)","name":"chain","signature":"chain(java.lang.Runnable,java.lang.Runnable)","declaredType":162,"parent":69,"parameters":[82,83],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":6},"anchor":[8,14,19]} -{"t":"e","i":82,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.chain(java.lang.Runnable,java.lang.Runnable)","d":"param:first","name":"first","declaredType":162,"parent":81,"anchor":[8,14,14]} -{"t":"e","i":83,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.chain(java.lang.Runnable,java.lang.Runnable)","d":"param:second","name":"second","declaredType":162,"parent":81,"anchor":[8,14,14]} -{"t":"e","i":84,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Notifications.freeOf(com.acme.order.Order)","name":"freeOf","signature":"freeOf(com.acme.order.Order)","declaredType":115,"parent":69,"parameters":[85],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":9},"anchor":[8,21,30]} -{"t":"e","i":85,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.freeOf(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"parent":84,"anchor":[8,21,21]} -{"t":"e","i":86,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Notifications.log(java.lang.String)","name":"log","signature":"log(java.lang.String)","parent":69,"parameters":[87],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[8,36,38]} -{"t":"e","i":87,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.log(java.lang.String)","d":"param:message","name":"message","declaredType":164,"parent":86,"anchor":[8,36,36]} -{"t":"e","i":88,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Notifications.notifyShipped(com.acme.order.Order)","name":"notifyShipped","signature":"notifyShipped(com.acme.order.Order)","parent":69,"parameters":[89],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[8,32,34]} -{"t":"e","i":89,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.notifyShipped(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"parent":88,"anchor":[8,32,32]} -{"t":"e","i":90,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.onShipped","name":"onShipped","declaredType":177,"parent":69,"anchor":[8,8,8]} +{"t":"e","i":78,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Notifications.()","signature":"()","parent":69,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[8,6,39]} +{"t":"e","i":79,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Notifications.both(com.acme.order.Order)","name":"both","signature":"both(com.acme.order.Order)","declaredType":162,"typeExpr":{"k":"named","type":162},"parent":69,"parameters":[80],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[8,10,12]} +{"t":"e","i":80,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.both(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"typeExpr":{"k":"named","type":91},"parent":79,"anchor":[8,10,10]} +{"t":"e","i":81,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Notifications.chain(java.lang.Runnable,java.lang.Runnable)","name":"chain","signature":"chain(java.lang.Runnable,java.lang.Runnable)","declaredType":162,"typeExpr":{"k":"named","type":162},"parent":69,"parameters":[82,83],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":6},"anchor":[8,14,19]} +{"t":"e","i":82,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.chain(java.lang.Runnable,java.lang.Runnable)","d":"param:first","name":"first","declaredType":162,"typeExpr":{"k":"named","type":162},"parent":81,"anchor":[8,14,14]} +{"t":"e","i":83,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.chain(java.lang.Runnable,java.lang.Runnable)","d":"param:second","name":"second","declaredType":162,"typeExpr":{"k":"named","type":162},"parent":81,"anchor":[8,14,14]} +{"t":"e","i":84,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Notifications.freeOf(com.acme.order.Order)","name":"freeOf","signature":"freeOf(com.acme.order.Order)","declaredType":115,"typeExpr":{"k":"named","type":115},"parent":69,"parameters":[85],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":9},"anchor":[8,21,30]} +{"t":"e","i":85,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.freeOf(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"typeExpr":{"k":"named","type":91},"parent":84,"anchor":[8,21,21]} +{"t":"e","i":86,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Notifications.log(java.lang.String)","name":"log","signature":"log(java.lang.String)","parent":69,"parameters":[87],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[8,36,38]} +{"t":"e","i":87,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.log(java.lang.String)","d":"param:message","name":"message","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":86,"anchor":[8,36,36]} +{"t":"e","i":88,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Notifications.notifyShipped(com.acme.order.Order)","name":"notifyShipped","signature":"notifyShipped(com.acme.order.Order)","parent":69,"parameters":[89],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[8,32,34]} +{"t":"e","i":89,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.notifyShipped(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"typeExpr":{"k":"named","type":91},"parent":88,"anchor":[8,32,32]} +{"t":"e","i":90,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Notifications.onShipped","name":"onShipped","declaredType":177,"typeExpr":{"k":"named","type":177,"args":[{"k":"named","type":91}]},"parent":69,"anchor":[8,8,8]} {"t":"e","i":91,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Order","name":"Order","isStub":false,"parent":0,"comments":["A customer order. The one-argument constructor delegates to the other."],"metrics":{"sloc":20},"anchor":[9,6,35]} -{"t":"e","i":92,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Order.(java.lang.String)","signature":"(java.lang.String)","parent":91,"parameters":[93],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[9,16,18]} -{"t":"e","i":93,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.(java.lang.String)","d":"param:reference","name":"reference","declaredType":164,"parent":92,"anchor":[9,16,16]} -{"t":"e","i":94,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Order.(java.lang.String,com.acme.order.Channel)","signature":"(java.lang.String,com.acme.order.Channel)","parent":91,"parameters":[96,95],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[9,20,23]} -{"t":"e","i":95,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.(java.lang.String,com.acme.order.Channel)","d":"param:channel","name":"channel","declaredType":47,"parent":94,"anchor":[9,20,20]} -{"t":"e","i":96,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.(java.lang.String,com.acme.order.Channel)","d":"param:reference","name":"reference","declaredType":164,"parent":94,"anchor":[9,20,20]} -{"t":"e","i":97,"k":1,"tr":[5,6,1,0,9,7,17],"m":0,"s":"Order.MAX_LINES","name":"MAX_LINES","parent":91,"comments":["A compile-time constant: the initializer folds across the arithmetic."],"value":{"k":"number","v":"100"},"anchor":[9,9,9]} -{"t":"e","i":98,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Order.channel","name":"channel","declaredType":47,"parent":91,"anchor":[9,14,14]} -{"t":"e","i":99,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Order.channel()","name":"channel","signature":"channel()","declaredType":47,"parent":91,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[9,25,27]} -{"t":"e","i":100,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Order.discount(int)","name":"discount","signature":"discount(int)","declaredType":60,"parent":91,"parameters":[101],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[9,31,34]} -{"t":"e","i":101,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.discount(int)","d":"param:percent","name":"percent","parent":100,"anchor":[9,31,31]} -{"t":"e","i":102,"k":1,"tr":[5,6,1,0,9,7],"m":0,"s":"Order.trail","name":"trail","declaredType":165,"parent":91,"comments":["Final, but NOT a constant: an initializer that is code carries no value."],"anchor":[9,12,12]} +{"t":"e","i":92,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Order.(java.lang.String)","signature":"(java.lang.String)","parent":91,"parameters":[93],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[9,16,18]} +{"t":"e","i":93,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.(java.lang.String)","d":"param:reference","name":"reference","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":92,"anchor":[9,16,16]} +{"t":"e","i":94,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Order.(java.lang.String,com.acme.order.Channel)","signature":"(java.lang.String,com.acme.order.Channel)","parent":91,"parameters":[96,95],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[9,20,23]} +{"t":"e","i":95,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.(java.lang.String,com.acme.order.Channel)","d":"param:channel","name":"channel","declaredType":47,"typeExpr":{"k":"named","type":47},"parent":94,"anchor":[9,20,20]} +{"t":"e","i":96,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.(java.lang.String,com.acme.order.Channel)","d":"param:reference","name":"reference","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":94,"anchor":[9,20,20]} +{"t":"e","i":97,"k":1,"tr":[5,6,1,0,9,7,18],"m":0,"s":"Order.MAX_LINES","name":"MAX_LINES","typeExpr":{"k":"primitive","name":"int"},"parent":91,"comments":["A compile-time constant: the initializer folds across the arithmetic."],"value":{"k":"number","v":"100"},"anchor":[9,9,9]} +{"t":"e","i":98,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Order.channel","name":"channel","declaredType":47,"typeExpr":{"k":"named","type":47},"parent":91,"anchor":[9,14,14]} +{"t":"e","i":99,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Order.channel()","name":"channel","signature":"channel()","declaredType":47,"typeExpr":{"k":"named","type":47},"parent":91,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[9,25,27]} +{"t":"e","i":100,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Order.discount(int)","name":"discount","signature":"discount(int)","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":91,"parameters":[101],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[9,31,34]} +{"t":"e","i":101,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.discount(int)","d":"param:percent","name":"percent","typeExpr":{"k":"primitive","name":"int"},"parent":100,"anchor":[9,31,31]} +{"t":"e","i":102,"k":1,"tr":[5,6,1,0,9,7,17],"m":0,"s":"Order.trail","name":"trail","declaredType":165,"typeExpr":{"k":"named","type":165},"parent":91,"comments":["Final, but NOT a constant: an initializer that is code carries no value."],"anchor":[9,12,12]} {"t":"e","i":103,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"OrderService","name":"OrderService","isStub":false,"parent":0,"comments":["Billing and archival. Both {@code archive} overloads take a parameter whose\nsimple name is {@code List}; only their packages differ."],"metrics":{"sloc":19},"anchor":[10,9,32]} -{"t":"e","i":104,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"OrderService.(com.megacorp.ledger.LedgerClient)","signature":"(com.megacorp.ledger.LedgerClient)","parent":103,"parameters":[105],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[10,13,15]} -{"t":"e","i":105,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.(com.megacorp.ledger.LedgerClient)","d":"param:ledger","name":"ledger","declaredType":155,"parent":104,"anchor":[10,13,13]} -{"t":"e","i":106,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"OrderService.archive(com.acme.order.legacy.List)","name":"archive","signature":"archive(com.acme.order.legacy.List)","parent":103,"parameters":[107],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[10,29,31]} -{"t":"e","i":107,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.archive(com.acme.order.legacy.List)","d":"param:orders","name":"orders","declaredType":146,"parent":106,"anchor":[10,29,29]} -{"t":"e","i":108,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"OrderService.archive(java.util.List)","name":"archive","signature":"archive(java.util.List)","parent":103,"parameters":[110],"localVariables":[109],"metrics":{"cyclomatic":2,"sloc":5},"anchor":[10,23,27]} -{"t":"e","i":109,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.archive(java.util.List)","d":"local:order:24","name":"order","declaredType":91,"parent":108,"anchor":[10,24,24]} -{"t":"e","i":110,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.archive(java.util.List)","d":"param:orders","name":"orders","declaredType":175,"parent":108,"anchor":[10,23,23]} -{"t":"e","i":111,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"OrderService.bill(com.acme.order.Order)","name":"bill","signature":"bill(com.acme.order.Order)","declaredType":59,"parent":103,"parameters":[113],"localVariables":[112],"metrics":{"cyclomatic":1,"sloc":5},"anchor":[10,17,21]} -{"t":"e","i":112,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.bill(com.acme.order.Order)","d":"local:invoice:18","name":"invoice","declaredType":59,"parent":111,"anchor":[10,18,18]} -{"t":"e","i":113,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.bill(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"parent":111,"anchor":[10,17,17]} -{"t":"e","i":114,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.ledger","name":"ledger","declaredType":155,"parent":103,"anchor":[10,11,11]} +{"t":"e","i":104,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"OrderService.(com.megacorp.ledger.LedgerClient)","signature":"(com.megacorp.ledger.LedgerClient)","parent":103,"parameters":[105],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[10,13,15]} +{"t":"e","i":105,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.(com.megacorp.ledger.LedgerClient)","d":"param:ledger","name":"ledger","declaredType":155,"typeExpr":{"k":"named","type":155},"parent":104,"anchor":[10,13,13]} +{"t":"e","i":106,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"OrderService.archive(com.acme.order.legacy.List)","name":"archive","signature":"archive(com.acme.order.legacy.List)","parent":103,"parameters":[107],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[10,29,31]} +{"t":"e","i":107,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.archive(com.acme.order.legacy.List)","d":"param:orders","name":"orders","declaredType":146,"typeExpr":{"k":"named","type":146},"parent":106,"anchor":[10,29,29]} +{"t":"e","i":108,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"OrderService.archive(java.util.List)","name":"archive","signature":"archive(java.util.List)","parent":103,"parameters":[110],"localVariables":[109],"metrics":{"cyclomatic":2,"sloc":5},"anchor":[10,23,27]} +{"t":"e","i":109,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.archive(java.util.List)","d":"local:order:24","name":"order","declaredType":91,"typeExpr":{"k":"named","type":91},"parent":108,"anchor":[10,24,24]} +{"t":"e","i":110,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.archive(java.util.List)","d":"param:orders","name":"orders","declaredType":175,"typeExpr":{"k":"named","type":175,"args":[{"k":"unevaluated","source":"? extends Order"}]},"parent":108,"anchor":[10,23,23]} +{"t":"e","i":111,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"OrderService.bill(com.acme.order.Order)","name":"bill","signature":"bill(com.acme.order.Order)","declaredType":59,"typeExpr":{"k":"named","type":59},"parent":103,"parameters":[113],"localVariables":[112],"metrics":{"cyclomatic":1,"sloc":5},"anchor":[10,17,21]} +{"t":"e","i":112,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.bill(com.acme.order.Order)","d":"local:invoice:18","name":"invoice","declaredType":59,"typeExpr":{"k":"named","type":59},"parent":111,"anchor":[10,18,18]} +{"t":"e","i":113,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.bill(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"typeExpr":{"k":"named","type":91},"parent":111,"anchor":[10,17,17]} +{"t":"e","i":114,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"OrderService.ledger","name":"ledger","declaredType":155,"typeExpr":{"k":"named","type":155},"parent":103,"anchor":[10,11,11]} {"t":"e","i":115,"k":5,"tr":[5,6,1,11,0,8,13,3],"m":0,"s":"Priceable","name":"Priceable","isStub":false,"parent":0,"comments":["Anything the pricing engine can put a number on."],"metrics":{"sloc":3},"anchor":[11,4,7]} -{"t":"e","i":116,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Priceable.price()","name":"price","signature":"price()","declaredType":60,"parent":115,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"anchor":[11,6,6]} +{"t":"e","i":116,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Priceable.price()","name":"price","signature":"price()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":115,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"anchor":[11,6,6]} {"t":"e","i":117,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Reporting","name":"Reporting","isStub":false,"parent":0,"comments":["Monthly reporting helpers."],"metrics":{"sloc":28},"anchor":[12,9,41]} -{"t":"e","i":118,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Reporting.()","signature":"()","parent":117,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[12,9,41]} -{"t":"e","i":119,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Reporting.first(java.util.List)","name":"first","signature":"first(java.util.List)","declaredType":160,"parent":117,"parameters":[120],"localVariables":[],"metrics":{"cyclomatic":2,"sloc":3},"anchor":[12,34,36]} -{"t":"e","i":120,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.first(java.util.List)","d":"param:values","name":"values","declaredType":175,"parent":119,"anchor":[12,34,34]} -{"t":"e","i":121,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Reporting.join(java.lang.String[])","name":"join","signature":"join(java.lang.String[])","declaredType":164,"parent":117,"parameters":[124],"localVariables":[122,123],"metrics":{"cyclomatic":2,"sloc":7},"anchor":[12,15,21]} -{"t":"e","i":122,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.join(java.lang.String[])","d":"local:out:16","name":"out","declaredType":165,"parent":121,"anchor":[12,16,16]} -{"t":"e","i":123,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.join(java.lang.String[])","d":"local:part:17","name":"part","declaredType":164,"parent":121,"anchor":[12,17,17]} -{"t":"e","i":124,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.join(java.lang.String[])","d":"param:parts","name":"parts","declaredType":164,"parent":121,"anchor":[12,15,15]} -{"t":"e","i":125,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Reporting.lines(java.lang.String[])","name":"lines","signature":"lines(java.lang.String[])","declaredType":173,"parent":117,"parameters":[126],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[12,11,13]} -{"t":"e","i":126,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.lines(java.lang.String[])","d":"param:rows","name":"rows","declaredType":164,"parent":125,"anchor":[12,11,11]} -{"t":"e","i":127,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Reporting.max(java.util.List)","name":"max","signature":"max(java.util.List)","declaredType":159,"parent":117,"parameters":[130],"localVariables":[128,129],"metrics":{"cyclomatic":4,"sloc":9},"anchor":[12,24,32]} -{"t":"e","i":128,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.max(java.util.List)","d":"local:best:25","name":"best","declaredType":159,"parent":127,"anchor":[12,25,25]} -{"t":"e","i":129,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.max(java.util.List)","d":"local:value:26","name":"value","declaredType":159,"parent":127,"anchor":[12,26,26]} -{"t":"e","i":130,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.max(java.util.List)","d":"param:values","name":"values","declaredType":175,"parent":127,"anchor":[12,24,24]} -{"t":"e","i":131,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Reporting.today()","name":"today","signature":"today()","declaredType":171,"parent":117,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[12,38,40]} +{"t":"e","i":118,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Reporting.()","signature":"()","parent":117,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[12,9,41]} +{"t":"e","i":119,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Reporting.first(java.util.List)","name":"first","signature":"first(java.util.List)","declaredType":160,"typeExpr":{"k":"variable","name":"T"},"parent":117,"parameters":[120],"localVariables":[],"metrics":{"cyclomatic":2,"sloc":3},"anchor":[12,34,36]} +{"t":"e","i":120,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.first(java.util.List)","d":"param:values","name":"values","declaredType":175,"typeExpr":{"k":"named","type":175,"args":[{"k":"variable","name":"T"}]},"parent":119,"anchor":[12,34,34]} +{"t":"e","i":121,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Reporting.join(java.lang.String[])","name":"join","signature":"join(java.lang.String[])","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":117,"parameters":[124],"localVariables":[122,123],"metrics":{"cyclomatic":2,"sloc":7},"anchor":[12,15,21]} +{"t":"e","i":122,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.join(java.lang.String[])","d":"local:out:16","name":"out","declaredType":165,"typeExpr":{"k":"named","type":165},"parent":121,"anchor":[12,16,16]} +{"t":"e","i":123,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.join(java.lang.String[])","d":"local:part:17","name":"part","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":121,"anchor":[12,17,17]} +{"t":"e","i":124,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.join(java.lang.String[])","d":"param:parts","name":"parts","declaredType":164,"typeExpr":{"k":"array","of":{"k":"named","type":164}},"parent":121,"anchor":[12,15,15]} +{"t":"e","i":125,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Reporting.lines(java.lang.String[])","name":"lines","signature":"lines(java.lang.String[])","declaredType":173,"typeExpr":{"k":"named","type":173,"args":[{"k":"named","type":164}]},"parent":117,"parameters":[126],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[12,11,13]} +{"t":"e","i":126,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.lines(java.lang.String[])","d":"param:rows","name":"rows","declaredType":164,"typeExpr":{"k":"array","of":{"k":"named","type":164}},"parent":125,"anchor":[12,11,11]} +{"t":"e","i":127,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Reporting.max(java.util.List)","name":"max","signature":"max(java.util.List)","declaredType":159,"typeExpr":{"k":"variable","name":"T"},"parent":117,"parameters":[130],"localVariables":[128,129],"metrics":{"cyclomatic":4,"sloc":9},"anchor":[12,24,32]} +{"t":"e","i":128,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.max(java.util.List)","d":"local:best:25","name":"best","declaredType":159,"typeExpr":{"k":"variable","name":"T"},"parent":127,"anchor":[12,25,25]} +{"t":"e","i":129,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.max(java.util.List)","d":"local:value:26","name":"value","declaredType":159,"typeExpr":{"k":"variable","name":"T"},"parent":127,"anchor":[12,26,26]} +{"t":"e","i":130,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.max(java.util.List)","d":"param:values","name":"values","declaredType":175,"typeExpr":{"k":"named","type":175,"args":[{"k":"variable","name":"T"}]},"parent":127,"anchor":[12,24,24]} +{"t":"e","i":131,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Reporting.today()","name":"today","signature":"today()","declaredType":171,"typeExpr":{"k":"named","type":171},"parent":117,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[12,38,40]} {"t":"e","i":132,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"StockGuard","name":"StockGuard","isStub":false,"parent":0,"comments":["Throw-site regression case: a guard clause and a rethrow must each emit a\n{@code throws} edge anchored at its own statement, and the {@code throws}\nclause on {@code check} must stay a plain reference (propagation, not a\nfailure exit)."],"metrics":{"sloc":14},"anchor":[13,9,24]} -{"t":"e","i":133,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"StockGuard.()","signature":"()","parent":132,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[13,9,24]} -{"t":"e","i":134,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"StockGuard.check(int)","name":"check","signature":"check(int)","parent":132,"parameters":[135],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":2},"anchor":[13,22,23]} -{"t":"e","i":135,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"StockGuard.check(int)","d":"param:quantity","name":"quantity","parent":134,"anchor":[13,22,22]} -{"t":"e","i":136,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"StockGuard.ensure(int)","name":"ensure","signature":"ensure(int)","parent":132,"parameters":[137],"localVariables":[],"metrics":{"cyclomatic":3,"sloc":10},"anchor":[13,11,20]} -{"t":"e","i":137,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"StockGuard.ensure(int)","d":"param:quantity","name":"quantity","parent":136,"anchor":[13,11,11]} +{"t":"e","i":133,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"StockGuard.()","signature":"()","parent":132,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[13,9,24]} +{"t":"e","i":134,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"StockGuard.check(int)","name":"check","signature":"check(int)","parent":132,"parameters":[135],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":2},"anchor":[13,22,23]} +{"t":"e","i":135,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"StockGuard.check(int)","d":"param:quantity","name":"quantity","typeExpr":{"k":"primitive","name":"int"},"parent":134,"anchor":[13,22,22]} +{"t":"e","i":136,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"StockGuard.ensure(int)","name":"ensure","signature":"ensure(int)","parent":132,"parameters":[137],"localVariables":[],"metrics":{"cyclomatic":3,"sloc":10},"anchor":[13,11,20]} +{"t":"e","i":137,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"StockGuard.ensure(int)","d":"param:quantity","name":"quantity","typeExpr":{"k":"primitive","name":"int"},"parent":136,"anchor":[13,11,11]} {"t":"e","i":138,"k":9,"tr":[5,11,0,4],"m":138,"s":"com.acme.order.adapter","name":"com.acme.order.adapter","isStub":false,"parent":0,"definedIn":[14]} {"t":"e","i":139,"k":2,"tr":[5,8],"m":138,"s":"AuditTrail","name":"AuditTrail","isStub":true} {"t":"e","i":140,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":138,"s":"LedgerAdapter","name":"LedgerAdapter","isStub":false,"parent":138,"comments":["Posts to the ledger and keeps a local trail."],"metrics":{"sloc":8},"anchor":[14,6,15]} -{"t":"e","i":141,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":138,"s":"LedgerAdapter.()","signature":"()","parent":140,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[14,6,15]} -{"t":"e","i":142,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":138,"s":"LedgerAdapter.post(java.lang.Object)","name":"post","signature":"post(java.lang.Object)","parent":140,"parameters":[143],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[14,11,14]} -{"t":"e","i":143,"k":10,"tr":[5,6,0,9,7],"m":138,"s":"LedgerAdapter.post(java.lang.Object)","d":"param:document","name":"document","declaredType":160,"parent":142,"anchor":[14,11,11]} -{"t":"e","i":144,"k":1,"tr":[5,6,0,9,7],"m":138,"s":"LedgerAdapter.trail","name":"trail","declaredType":139,"parent":140,"anchor":[14,8,8]} +{"t":"e","i":141,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":138,"s":"LedgerAdapter.()","signature":"()","parent":140,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[14,6,15]} +{"t":"e","i":142,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":138,"s":"LedgerAdapter.post(java.lang.Object)","name":"post","signature":"post(java.lang.Object)","parent":140,"parameters":[143],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[14,11,14]} +{"t":"e","i":143,"k":10,"tr":[5,6,0,9,7],"m":138,"s":"LedgerAdapter.post(java.lang.Object)","d":"param:document","name":"document","declaredType":160,"typeExpr":{"k":"named","type":160},"parent":142,"anchor":[14,11,11]} +{"t":"e","i":144,"k":1,"tr":[5,6,0,9,7,17],"m":138,"s":"LedgerAdapter.trail","name":"trail","declaredType":139,"typeExpr":{"k":"named","type":139},"parent":140,"anchor":[14,8,8]} {"t":"e","i":145,"k":9,"tr":[5,11,0,4],"m":145,"s":"com.acme.order.legacy","name":"com.acme.order.legacy","isStub":false,"parent":0,"definedIn":[15]} {"t":"e","i":146,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":145,"s":"List","name":"List","isStub":false,"parent":145,"comments":["A hand-rolled cons list from before java.util was allowed here."],"metrics":{"sloc":14},"anchor":[15,4,22]} -{"t":"e","i":147,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":145,"s":"List.(java.lang.String,com.acme.order.legacy.List)","signature":"(java.lang.String,com.acme.order.legacy.List)","parent":146,"parameters":[148,149],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[15,10,13]} -{"t":"e","i":148,"k":10,"tr":[5,6,0,9,7],"m":145,"s":"List.(java.lang.String,com.acme.order.legacy.List)","d":"param:head","name":"head","declaredType":164,"parent":147,"anchor":[15,10,10]} -{"t":"e","i":149,"k":10,"tr":[5,6,0,9,7],"m":145,"s":"List.(java.lang.String,com.acme.order.legacy.List)","d":"param:tail","name":"tail","declaredType":146,"parent":147,"anchor":[15,10,10]} -{"t":"e","i":150,"k":1,"tr":[5,6,0,9,7],"m":145,"s":"List.head","name":"head","declaredType":164,"parent":146,"anchor":[15,6,6]} -{"t":"e","i":151,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":145,"s":"List.head()","name":"head","signature":"head()","declaredType":164,"parent":146,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[15,15,17]} -{"t":"e","i":152,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":145,"s":"List.length()","name":"length","signature":"length()","parent":146,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":2,"sloc":3},"anchor":[15,19,21]} -{"t":"e","i":153,"k":1,"tr":[5,6,0,9,7],"m":145,"s":"List.tail","name":"tail","declaredType":146,"parent":146,"anchor":[15,8,8]} +{"t":"e","i":147,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":145,"s":"List.(java.lang.String,com.acme.order.legacy.List)","signature":"(java.lang.String,com.acme.order.legacy.List)","parent":146,"parameters":[148,149],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[15,10,13]} +{"t":"e","i":148,"k":10,"tr":[5,6,0,9,7],"m":145,"s":"List.(java.lang.String,com.acme.order.legacy.List)","d":"param:head","name":"head","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":147,"anchor":[15,10,10]} +{"t":"e","i":149,"k":10,"tr":[5,6,0,9,7],"m":145,"s":"List.(java.lang.String,com.acme.order.legacy.List)","d":"param:tail","name":"tail","declaredType":146,"typeExpr":{"k":"named","type":146},"parent":147,"anchor":[15,10,10]} +{"t":"e","i":150,"k":1,"tr":[5,6,0,9,7,17],"m":145,"s":"List.head","name":"head","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":146,"anchor":[15,6,6]} +{"t":"e","i":151,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":145,"s":"List.head()","name":"head","signature":"head()","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":146,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":3},"anchor":[15,15,17]} +{"t":"e","i":152,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":145,"s":"List.length()","name":"length","signature":"length()","typeExpr":{"k":"primitive","name":"int"},"parent":146,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":2,"sloc":3},"anchor":[15,19,21]} +{"t":"e","i":153,"k":1,"tr":[5,6,0,9,7,17],"m":145,"s":"List.tail","name":"tail","declaredType":146,"typeExpr":{"k":"named","type":146},"parent":146,"anchor":[15,8,8]} {"t":"e","i":154,"k":9,"tr":[5,11,4],"m":154,"s":"com.megacorp.ledger","name":"com.megacorp.ledger","isStub":true,"definedIn":[]} {"t":"e","i":155,"k":2,"tr":[5,0,8],"m":154,"s":"LedgerClient","name":"LedgerClient","isStub":true,"parent":154} {"t":"e","i":156,"k":9,"tr":[5,11,4],"m":156,"s":"java.io","name":"java.io","isStub":true,"definedIn":[]} @@ -205,29 +205,29 @@ {"t":"x","k":2,"f":0,"o":172,"p":0,"anchor":[12,6,6]} {"t":"x","k":2,"f":0,"o":176,"p":0,"anchor":[8,3,3]} {"t":"x","k":4,"f":1,"o":53,"p":0,"anchor":[0,4,4]} -{"t":"x","k":0,"f":2,"o":5,"p":0,"isRead":false,"isWrite":true,"anchor":[0,11,11]} -{"t":"x","k":0,"f":2,"o":7,"p":0,"isRead":false,"isWrite":true,"anchor":[0,12,12]} +{"t":"x","k":0,"f":2,"o":5,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[0,11,11]} +{"t":"x","k":0,"f":2,"o":7,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[0,12,12]} {"t":"x","k":5,"f":2,"o":68,"p":0,"anchor":[0,12,12]} {"t":"x","k":6,"f":3,"o":164,"p":0,"anchor":[0,10,10]} -{"t":"x","k":0,"f":4,"o":7,"p":0,"isRead":true,"isWrite":false,"anchor":[0,21,21]} +{"t":"x","k":0,"f":4,"o":7,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[0,21,21]} {"t":"x","k":6,"f":4,"o":60,"p":0,"anchor":[0,20,20]} {"t":"x","k":1,"f":4,"o":161,"p":0,"anchor":[0,19,19]} {"t":"x","k":6,"f":5,"o":164,"p":0,"anchor":[0,8,8]} -{"t":"x","k":0,"f":6,"o":5,"p":0,"isRead":true,"isWrite":false,"anchor":[0,16,16]} +{"t":"x","k":0,"f":6,"o":5,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[0,16,16]} {"t":"x","k":6,"f":6,"o":164,"p":0,"anchor":[0,15,15]} {"t":"x","k":6,"f":7,"o":60,"p":0,"anchor":[0,6,6]} {"t":"x","k":1,"f":8,"o":168,"p":0,"arguments":[{"name":"value","value":{"k":"enum","type":169,"name":"RUNTIME"}}],"anchor":[1,7,7]} {"t":"x","k":6,"f":8,"o":169,"p":0,"member":"RUNTIME","anchor":[1,7,7]} {"t":"x","k":6,"f":9,"o":164,"p":0,"anchor":[1,10,10]} -{"t":"x","k":0,"f":15,"o":14,"p":0,"isRead":true,"isWrite":true,"anchor":[2,54,54]} +{"t":"x","k":0,"f":15,"o":14,"p":0,"isRead":true,"isWrite":true,"receiver":"self","anchor":[2,54,54]} {"t":"x","k":6,"f":15,"o":16,"p":0,"anchor":[2,53,53]} -{"t":"x","k":0,"f":15,"o":28,"p":0,"isRead":true,"isWrite":false,"anchor":[2,54,54]} +{"t":"x","k":0,"f":15,"o":28,"p":0,"isRead":true,"isWrite":false,"receiver":"other","anchor":[2,54,54]} {"t":"x","k":5,"f":15,"o":175,"p":0,"member":"get","anchor":[2,54,54]} -{"t":"x","k":0,"f":17,"o":23,"p":0,"isRead":false,"isWrite":true,"anchor":[2,32,32]} -{"t":"x","k":0,"f":24,"o":23,"p":0,"isRead":true,"isWrite":false,"anchor":[2,36,36]} +{"t":"x","k":0,"f":17,"o":23,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[2,32,32]} +{"t":"x","k":0,"f":24,"o":23,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[2,36,36]} {"t":"x","k":5,"f":25,"o":24,"p":0,"anchor":[2,15,15]} -{"t":"x","k":0,"f":25,"o":28,"p":0,"isRead":true,"isWrite":false,"anchor":[2,14,14]} -{"t":"x","k":0,"f":25,"o":29,"p":0,"isRead":true,"isWrite":true,"anchor":[2,15,15]} +{"t":"x","k":0,"f":25,"o":28,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[2,14,14]} +{"t":"x","k":0,"f":25,"o":29,"p":0,"isRead":true,"isWrite":true,"receiver":"self","anchor":[2,15,15]} {"t":"x","k":5,"f":25,"o":175,"p":0,"member":"add","anchor":[2,14,14]} {"t":"x","k":6,"f":26,"o":16,"p":0,"anchor":[2,13,13]} {"t":"x","k":6,"f":27,"o":12,"p":0,"anchor":[2,22,22]} @@ -235,25 +235,25 @@ {"t":"x","k":6,"f":28,"o":16,"p":0,"anchor":[2,11,11]} {"t":"x","k":6,"f":28,"o":173,"p":0,"anchor":[2,11,11]} {"t":"x","k":6,"f":28,"o":175,"p":0,"anchor":[2,11,11]} -{"t":"x","k":0,"f":30,"o":29,"p":0,"isRead":true,"isWrite":false,"anchor":[2,19,19]} +{"t":"x","k":0,"f":30,"o":29,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[2,19,19]} {"t":"x","k":6,"f":32,"o":115,"p":0,"anchor":[3,48,60]} -{"t":"x","k":0,"f":34,"o":35,"p":0,"isRead":true,"isWrite":false,"anchor":[3,54,54]} +{"t":"x","k":0,"f":34,"o":35,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[3,54,54]} {"t":"x","k":5,"f":34,"o":36,"p":0,"anchor":[3,54,54]} {"t":"x","k":6,"f":34,"o":60,"p":0,"anchor":[3,53,53]} {"t":"x","k":1,"f":34,"o":161,"p":0,"anchor":[3,52,52]} {"t":"x","k":6,"f":35,"o":60,"p":0,"anchor":[3,50,50]} {"t":"x","k":6,"f":36,"o":60,"p":0,"anchor":[3,57,57]} {"t":"x","k":6,"f":37,"o":60,"p":0,"anchor":[3,57,57]} -{"t":"x","k":0,"f":38,"o":42,"p":0,"isRead":false,"isWrite":true,"anchor":[3,27,27]} -{"t":"x","k":0,"f":38,"o":44,"p":0,"isRead":false,"isWrite":true,"anchor":[3,28,28]} +{"t":"x","k":0,"f":38,"o":42,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[3,27,27]} +{"t":"x","k":0,"f":38,"o":44,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[3,28,28]} {"t":"x","k":6,"f":40,"o":60,"p":0,"anchor":[3,26,26]} {"t":"x","k":6,"f":41,"o":178,"p":0,"anchor":[3,42,42]} -{"t":"x","k":0,"f":43,"o":44,"p":0,"isRead":true,"isWrite":false,"anchor":[3,38,38]} +{"t":"x","k":0,"f":43,"o":44,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[3,38,38]} {"t":"x","k":6,"f":44,"o":60,"p":0,"anchor":[3,24,24]} {"t":"x","k":5,"f":45,"o":32,"p":0,"anchor":[3,48,60]} {"t":"x","k":5,"f":45,"o":68,"p":0,"anchor":[3,50,50]} {"t":"x","k":6,"f":45,"o":115,"p":0,"anchor":[3,47,47]} -{"t":"x","k":0,"f":46,"o":42,"p":0,"isRead":true,"isWrite":false,"anchor":[3,33,33]} +{"t":"x","k":0,"f":46,"o":42,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[3,33,33]} {"t":"x","k":4,"f":47,"o":115,"p":0,"anchor":[4,4,4]} {"t":"x","k":6,"f":52,"o":60,"p":0,"anchor":[4,10,10]} {"t":"x","k":5,"f":52,"o":68,"p":0,"anchor":[4,11,11]} @@ -268,7 +268,7 @@ {"t":"x","k":1,"f":65,"o":161,"p":0,"anchor":[7,14,14]} {"t":"x","k":6,"f":66,"o":60,"p":0,"anchor":[7,10,10]} {"t":"x","k":5,"f":66,"o":61,"p":0,"anchor":[7,11,11]} -{"t":"x","k":0,"f":66,"o":63,"p":0,"isRead":true,"isWrite":false,"anchor":[7,11,11]} +{"t":"x","k":0,"f":66,"o":63,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[7,11,11]} {"t":"x","k":6,"f":68,"o":60,"p":0,"anchor":[7,6,6]} {"t":"x","k":5,"f":68,"o":61,"p":0,"anchor":[7,7,7]} {"t":"x","k":5,"f":70,"o":6,"p":0,"anchor":[8,11,11]} @@ -297,7 +297,7 @@ {"t":"x","k":5,"f":86,"o":157,"p":0,"member":"println","anchor":[8,37,37]} {"t":"x","k":0,"f":86,"o":166,"p":0,"member":"out","isRead":true,"isWrite":false,"anchor":[8,37,37]} {"t":"x","k":6,"f":87,"o":164,"p":0,"anchor":[8,36,36]} -{"t":"x","k":0,"f":88,"o":90,"p":0,"isRead":true,"isWrite":false,"anchor":[8,33,33]} +{"t":"x","k":0,"f":88,"o":90,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[8,33,33]} {"t":"x","k":5,"f":88,"o":177,"p":0,"member":"accept","anchor":[8,33,33]} {"t":"x","k":6,"f":89,"o":91,"p":0,"anchor":[8,32,32]} {"t":"x","k":6,"f":90,"o":91,"p":0,"anchor":[8,8,8]} @@ -307,27 +307,27 @@ {"t":"x","k":5,"f":92,"o":94,"p":0,"anchor":[9,17,17]} {"t":"x","k":6,"f":93,"o":164,"p":0,"anchor":[9,16,16]} {"t":"x","k":5,"f":94,"o":2,"p":0,"anchor":[9,21,21]} -{"t":"x","k":0,"f":94,"o":98,"p":0,"isRead":false,"isWrite":true,"anchor":[9,22,22]} +{"t":"x","k":0,"f":94,"o":98,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[9,22,22]} {"t":"x","k":6,"f":95,"o":47,"p":0,"anchor":[9,20,20]} {"t":"x","k":6,"f":96,"o":164,"p":0,"anchor":[9,20,20]} {"t":"x","k":6,"f":98,"o":47,"p":0,"anchor":[9,14,14]} {"t":"x","k":6,"f":99,"o":47,"p":0,"anchor":[9,25,25]} -{"t":"x","k":0,"f":99,"o":98,"p":0,"isRead":true,"isWrite":false,"anchor":[9,26,26]} -{"t":"x","k":0,"f":100,"o":7,"p":0,"isRead":true,"isWrite":false,"anchor":[9,33,33]} +{"t":"x","k":0,"f":99,"o":98,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[9,26,26]} +{"t":"x","k":0,"f":100,"o":7,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[9,33,33]} {"t":"x","k":1,"f":100,"o":8,"p":0,"arguments":[{"name":"value","value":{"k":"unevaluated","source":"LedgerClient.AUDIT_TAG"}}],"anchor":[9,29,29]} {"t":"x","k":6,"f":100,"o":60,"p":0,"anchor":[9,31,31]} {"t":"x","k":5,"f":100,"o":66,"p":0,"anchor":[9,33,33]} {"t":"x","k":0,"f":100,"o":155,"p":0,"member":"AUDIT_TAG","isRead":true,"isWrite":false,"anchor":[9,29,29]} {"t":"x","k":1,"f":100,"o":161,"p":0,"anchor":[9,30,30]} {"t":"x","k":6,"f":102,"o":165,"p":0,"anchor":[9,12,12]} -{"t":"x","k":0,"f":104,"o":114,"p":0,"isRead":false,"isWrite":true,"anchor":[10,14,14]} +{"t":"x","k":0,"f":104,"o":114,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[10,14,14]} {"t":"x","k":6,"f":105,"o":155,"p":0,"anchor":[10,13,13]} -{"t":"x","k":0,"f":106,"o":114,"p":0,"isRead":true,"isWrite":false,"anchor":[10,30,30]} +{"t":"x","k":0,"f":106,"o":114,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[10,30,30]} {"t":"x","k":5,"f":106,"o":151,"p":0,"anchor":[10,30,30]} {"t":"x","k":5,"f":106,"o":155,"p":0,"member":"archive","anchor":[10,30,30]} {"t":"x","k":6,"f":107,"o":146,"p":0,"anchor":[10,29,29]} {"t":"x","k":5,"f":108,"o":6,"p":0,"anchor":[10,25,25]} -{"t":"x","k":0,"f":108,"o":114,"p":0,"isRead":true,"isWrite":false,"anchor":[10,25,25]} +{"t":"x","k":0,"f":108,"o":114,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[10,25,25]} {"t":"x","k":5,"f":108,"o":155,"p":0,"member":"archive","anchor":[10,25,25]} {"t":"x","k":6,"f":109,"o":91,"p":0,"anchor":[10,24,24]} {"t":"x","k":6,"f":110,"o":91,"p":0,"anchor":[10,23,23]} @@ -335,7 +335,7 @@ {"t":"x","k":5,"f":111,"o":6,"p":0,"anchor":[10,18,18]} {"t":"x","k":5,"f":111,"o":59,"p":0,"anchor":[10,18,18]} {"t":"x","k":6,"f":111,"o":59,"p":0,"anchor":[10,17,17]} -{"t":"x","k":0,"f":111,"o":114,"p":0,"isRead":true,"isWrite":false,"anchor":[10,19,19]} +{"t":"x","k":0,"f":111,"o":114,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[10,19,19]} {"t":"x","k":5,"f":111,"o":155,"p":0,"member":"post","anchor":[10,19,19]} {"t":"x","k":6,"f":112,"o":59,"p":0,"anchor":[10,18,18]} {"t":"x","k":6,"f":113,"o":91,"p":0,"anchor":[10,17,17]} @@ -370,18 +370,18 @@ {"t":"x","k":2,"f":138,"o":154,"p":1,"anchor":[14,3,3]} {"t":"x","k":3,"f":140,"o":155,"p":0,"anchor":[14,6,6]} {"t":"x","k":5,"f":142,"o":139,"p":0,"member":"record","anchor":[14,12,12]} -{"t":"x","k":0,"f":142,"o":144,"p":0,"isRead":true,"isWrite":false,"anchor":[14,12,12]} +{"t":"x","k":0,"f":142,"o":144,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[14,12,12]} {"t":"x","k":5,"f":142,"o":155,"p":1,"member":"post","anchor":[14,13,13]} {"t":"x","k":1,"f":142,"o":161,"p":0,"anchor":[14,10,10]} {"t":"x","k":6,"f":143,"o":160,"p":0,"anchor":[14,11,11]} {"t":"x","k":6,"f":144,"o":139,"p":0,"anchor":[14,8,8]} -{"t":"x","k":0,"f":147,"o":150,"p":0,"isRead":false,"isWrite":true,"anchor":[15,11,11]} -{"t":"x","k":0,"f":147,"o":153,"p":0,"isRead":false,"isWrite":true,"anchor":[15,12,12]} +{"t":"x","k":0,"f":147,"o":150,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[15,11,11]} +{"t":"x","k":0,"f":147,"o":153,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[15,12,12]} {"t":"x","k":6,"f":148,"o":164,"p":0,"anchor":[15,10,10]} {"t":"x","k":6,"f":149,"o":146,"p":0,"anchor":[15,10,10]} {"t":"x","k":6,"f":150,"o":164,"p":0,"anchor":[15,6,6]} -{"t":"x","k":0,"f":151,"o":150,"p":0,"isRead":true,"isWrite":false,"anchor":[15,16,16]} +{"t":"x","k":0,"f":151,"o":150,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[15,16,16]} {"t":"x","k":6,"f":151,"o":164,"p":0,"anchor":[15,15,15]} -{"t":"x","k":0,"f":152,"o":153,"p":0,"isRead":true,"isWrite":false,"anchor":[15,20,20]} +{"t":"x","k":0,"f":152,"o":153,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[15,20,20]} {"t":"x","k":6,"f":153,"o":146,"p":0,"anchor":[15,8,8]} {"t":"eof","counts":{"files":16,"entities":179,"edges":190}} diff --git a/fixtures/java/expected/model.metrics.jsonl b/fixtures/java/expected/model.metrics.jsonl index ad3915cd..3d48f8b8 100644 --- a/fixtures/java/expected/model.metrics.jsonl +++ b/fixtures/java/expected/model.metrics.jsonl @@ -1,4 +1,4 @@ -{"t":"header","schemaVersion":"1.1.0","lang":"java","extractor":{"name":"codegraph-spoon","version":"0.4.0","noClasspath":true},"root":"fixtures/java/src","dict":{"kinds":["annotation","attribute","class","constructor","enum","interface","lambda","localVariable","method","package","parameter","record"],"traits":["TChildOf","TComment","TInvocable","TMetrics","TModule","TNamed","TSourceAnchor","TStructural","TType","TTypedEntity","TWithAccesses","TWithChildren","TWithImplements","TWithInheritances","TWithInvocations","TWithLocalVariables","TWithParameters","TWithValue"],"edges":["access","annotationUse","import","inheritance","interfaceImplementation","invocation","reference","throws"],"provenance":["declared","derived"]}} +{"t":"header","schemaVersion":"1.2.0","lang":"java","extractor":{"name":"codegraph-spoon","version":"0.4.0","noClasspath":true},"root":"fixtures/java/src","dict":{"kinds":["annotation","attribute","class","constructor","enum","interface","lambda","localVariable","method","package","parameter","record"],"traits":["TChildOf","TComment","TInvocable","TMetrics","TModule","TNamed","TSourceAnchor","TStructural","TType","TTypedEntity","TWithAccesses","TWithChildren","TWithImplements","TWithInheritances","TWithInvocations","TWithLocalVariables","TWithParameters","TWithReceiver","TWithValue"],"edges":["access","annotationUse","import","inheritance","interfaceImplementation","invocation","reference","throws"],"provenance":["declared","derived"]}} {"t":"f","i":0,"path":"com/acme/order/AbstractOrder.java"} {"t":"f","i":1,"path":"com/acme/order/Audited.java"} {"t":"f","i":2,"path":"com/acme/order/Basket.java"} @@ -17,158 +17,158 @@ {"t":"f","i":15,"path":"com/acme/order/legacy/List.java"} {"t":"e","i":0,"k":9,"tr":[5,11,4],"m":0,"s":"com.acme.order","name":"com.acme.order","isStub":false,"definedIn":[0,1,2,3,4,5,6,7,8,9,10,11,12,13]} {"t":"e","i":1,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"AbstractOrder","name":"AbstractOrder","isStub":false,"parent":0,"comments":["Shared state for every kind of order."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":10.7143,"halstead.effort":1795.564,"halstead.volume":167.586,"lloc":4,"mi":55.5072,"nexits":0,"npa":0,"npm":2,"sloc":15},"anchor":[0,4,23]} -{"t":"e","i":2,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"AbstractOrder.(java.lang.String)","signature":"(java.lang.String)","parent":1,"parameters":[3],"localVariables":[],"metrics":{"abc.assignments":2,"abc.branches":1,"abc.conditions":0,"abc.magnitude":2.2361,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4.2,"halstead.effort":276.0626,"halstead.volume":65.7292,"lloc":2,"mi":74.0042,"nexits":0,"sloc":4},"anchor":[0,10,13]} -{"t":"e","i":3,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"AbstractOrder.(java.lang.String)","d":"param:reference","name":"reference","declaredType":164,"parent":2,"anchor":[0,10,10]} -{"t":"e","i":4,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"AbstractOrder.price()","name":"price","signature":"price()","declaredType":60,"parent":1,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2,"halstead.effort":39.303,"halstead.volume":19.6515,"lloc":1,"mi":77.6758,"nexits":1,"sloc":3},"anchor":[0,20,22]} -{"t":"e","i":5,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"AbstractOrder.reference","name":"reference","declaredType":164,"parent":1,"anchor":[0,8,8]} -{"t":"e","i":6,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"AbstractOrder.reference()","name":"reference","signature":"reference()","declaredType":164,"parent":1,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4,"halstead.effort":55.7263,"halstead.volume":13.9316,"lloc":1,"mi":81.4473,"nexits":1,"sloc":3},"anchor":[0,15,17]} -{"t":"e","i":7,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"AbstractOrder.total","name":"total","declaredType":60,"parent":1,"anchor":[0,6,6]} +{"t":"e","i":2,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"AbstractOrder.(java.lang.String)","signature":"(java.lang.String)","parent":1,"parameters":[3],"localVariables":[],"metrics":{"abc.assignments":2,"abc.branches":1,"abc.conditions":0,"abc.magnitude":2.2361,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4.2,"halstead.effort":276.0626,"halstead.volume":65.7292,"lloc":2,"mi":74.0042,"nexits":0,"sloc":4},"anchor":[0,10,13]} +{"t":"e","i":3,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"AbstractOrder.(java.lang.String)","d":"param:reference","name":"reference","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":2,"anchor":[0,10,10]} +{"t":"e","i":4,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"AbstractOrder.price()","name":"price","signature":"price()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":1,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2,"halstead.effort":39.303,"halstead.volume":19.6515,"lloc":1,"mi":77.6758,"nexits":1,"sloc":3},"anchor":[0,20,22]} +{"t":"e","i":5,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"AbstractOrder.reference","name":"reference","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":1,"anchor":[0,8,8]} +{"t":"e","i":6,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"AbstractOrder.reference()","name":"reference","signature":"reference()","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":1,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4,"halstead.effort":55.7263,"halstead.volume":13.9316,"lloc":1,"mi":81.4473,"nexits":1,"sloc":3},"anchor":[0,15,17]} +{"t":"e","i":7,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"AbstractOrder.total","name":"total","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":1,"anchor":[0,6,6]} {"t":"e","i":8,"k":0,"tr":[5,6,1,11,0,8,3],"m":0,"s":"Audited","name":"Audited","isStub":false,"parent":0,"comments":["Marks a method whose calls must reach the audit log."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":2.5,"halstead.effort":103.7829,"halstead.volume":41.5132,"lloc":0,"mi":73.2876,"nexits":0,"npa":0,"npm":1,"sloc":3},"anchor":[1,8,11]} -{"t":"e","i":9,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3,17],"m":0,"s":"Audited.value()","name":"value","signature":"value()","declaredType":164,"parent":8,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"value":{"k":"string","v":""},"anchor":[1,10,10]} +{"t":"e","i":9,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3,18],"m":0,"s":"Audited.value()","name":"value","signature":"value()","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":8,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"value":{"k":"string","v":""},"anchor":[1,10,10]} {"t":"e","i":10,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Basket","name":"Basket","isStub":false,"parent":0,"comments":["A basket being filled. Declares no constructor of its own."],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":3,"cognitive":0,"halstead.difficulty":18.7,"halstead.effort":9350,"halstead.volume":500,"lloc":8,"mi":42.3734,"nexits":0,"npa":0,"npm":3,"sloc":34},"anchor":[2,7,57]} -{"t":"e","i":11,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Basket.()","signature":"()","parent":10,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[2,7,57]} +{"t":"e","i":11,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Basket.()","signature":"()","parent":10,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[2,7,57]} {"t":"e","i":12,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Basket.Cursor","name":"Cursor","isStub":false,"parent":10,"comments":["Non-static inner: reads the enclosing Basket's fields."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":4.2,"halstead.effort":240.9095,"halstead.volume":57.3594,"lloc":1,"mi":67.7172,"nexits":0,"npa":0,"npm":1,"sloc":6},"anchor":[2,49,56]} -{"t":"e","i":13,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Basket.Cursor.()","signature":"()","parent":12,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[2,49,56]} -{"t":"e","i":14,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Basket.Cursor.index","name":"index","parent":12,"anchor":[2,51,51]} -{"t":"e","i":15,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Basket.Cursor.next()","name":"next","signature":"next()","declaredType":16,"parent":12,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":1,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1.4142,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":109.6236,"halstead.volume":36.5412,"lloc":1,"mi":78.515,"nexits":1,"sloc":3},"anchor":[2,53,55]} +{"t":"e","i":13,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Basket.Cursor.()","signature":"()","parent":12,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[2,49,56]} +{"t":"e","i":14,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Basket.Cursor.index","name":"index","typeExpr":{"k":"primitive","name":"int"},"parent":12,"anchor":[2,51,51]} +{"t":"e","i":15,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Basket.Cursor.next()","name":"next","signature":"next()","declaredType":16,"typeExpr":{"k":"named","type":16},"parent":12,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":1,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1.4142,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":109.6236,"halstead.volume":36.5412,"lloc":1,"mi":78.515,"nexits":1,"sloc":3},"anchor":[2,53,55]} {"t":"e","i":16,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Basket.Line","name":"Line","isStub":false,"parent":10,"comments":["Static nested: no enclosing Basket instance."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":1,"cognitive":0,"halstead.difficulty":13,"halstead.effort":1879.2144,"halstead.volume":144.555,"lloc":3,"mi":55.8223,"nexits":0,"npa":0,"npm":2,"sloc":14},"anchor":[2,27,46]} -{"t":"e","i":17,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Basket.Line.(long)","signature":"(long)","parent":16,"parameters":[18],"localVariables":[],"metrics":{"abc.assignments":1,"abc.branches":0,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":7,"halstead.effort":244.0842,"halstead.volume":34.8692,"lloc":1,"mi":78.6574,"nexits":0,"sloc":3},"anchor":[2,31,33]} -{"t":"e","i":18,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Basket.Line.(long)","d":"param:amount","name":"amount","parent":17,"anchor":[2,31,31]} +{"t":"e","i":17,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Basket.Line.(long)","signature":"(long)","parent":16,"parameters":[18],"localVariables":[],"metrics":{"abc.assignments":1,"abc.branches":0,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":7,"halstead.effort":244.0842,"halstead.volume":34.8692,"lloc":1,"mi":78.6574,"nexits":0,"sloc":3},"anchor":[2,31,33]} +{"t":"e","i":18,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Basket.Line.(long)","d":"param:amount","name":"amount","typeExpr":{"k":"primitive","name":"long"},"parent":17,"anchor":[2,31,31]} {"t":"e","i":19,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Basket.Line.Discount","name":"Discount","isStub":false,"parent":16,"comments":["Nested inside a nested type."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":3.75,"halstead.effort":161.944,"halstead.volume":43.1851,"lloc":1,"mi":71.3058,"nexits":0,"npa":0,"npm":1,"sloc":5},"anchor":[2,40,45]} -{"t":"e","i":20,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Basket.Line.Discount.()","signature":"()","parent":19,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[2,40,45]} -{"t":"e","i":21,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Basket.Line.Discount.applyTo(long)","name":"applyTo","signature":"applyTo(long)","parent":19,"parameters":[22],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4,"halstead.effort":139.4767,"halstead.volume":34.8692,"lloc":1,"mi":78.6574,"nexits":1,"sloc":3},"anchor":[2,42,44]} -{"t":"e","i":22,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Basket.Line.Discount.applyTo(long)","d":"param:amount","name":"amount","parent":21,"anchor":[2,42,42]} -{"t":"e","i":23,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Basket.Line.amount","name":"amount","parent":16,"anchor":[2,29,29]} -{"t":"e","i":24,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Basket.Line.amount()","name":"amount","signature":"amount()","parent":16,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":5,"halstead.effort":90.4737,"halstead.volume":18.0947,"lloc":1,"mi":80.6522,"nexits":1,"sloc":3},"anchor":[2,35,37]} -{"t":"e","i":25,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Basket.add(com.acme.order.Basket.Line)","name":"add","signature":"add(com.acme.order.Basket.Line)","parent":10,"parameters":[26],"localVariables":[],"metrics":{"abc.assignments":1,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2.2361,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4.8,"halstead.effort":298.8949,"halstead.volume":62.2698,"lloc":2,"mi":74.1686,"nexits":0,"sloc":4},"anchor":[2,13,16]} -{"t":"e","i":26,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Basket.add(com.acme.order.Basket.Line)","d":"param:line","name":"line","declaredType":16,"parent":25,"anchor":[2,13,13]} -{"t":"e","i":27,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Basket.cursor()","name":"cursor","signature":"cursor()","declaredType":12,"parent":10,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2.5,"halstead.effort":45.2368,"halstead.volume":18.0947,"lloc":1,"mi":80.6522,"nexits":1,"sloc":3},"anchor":[2,22,24]} -{"t":"e","i":28,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Basket.lines","name":"lines","declaredType":175,"parent":10,"anchor":[2,11,11]} -{"t":"e","i":29,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Basket.total","name":"total","parent":10,"anchor":[2,9,9]} -{"t":"e","i":30,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Basket.total()","name":"total","signature":"total()","parent":10,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":5,"halstead.effort":90.4737,"halstead.volume":18.0947,"lloc":1,"mi":80.6522,"nexits":1,"sloc":3},"anchor":[2,18,20]} +{"t":"e","i":20,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Basket.Line.Discount.()","signature":"()","parent":19,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[2,40,45]} +{"t":"e","i":21,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Basket.Line.Discount.applyTo(long)","name":"applyTo","signature":"applyTo(long)","typeExpr":{"k":"primitive","name":"long"},"parent":19,"parameters":[22],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4,"halstead.effort":139.4767,"halstead.volume":34.8692,"lloc":1,"mi":78.6574,"nexits":1,"sloc":3},"anchor":[2,42,44]} +{"t":"e","i":22,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Basket.Line.Discount.applyTo(long)","d":"param:amount","name":"amount","typeExpr":{"k":"primitive","name":"long"},"parent":21,"anchor":[2,42,42]} +{"t":"e","i":23,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Basket.Line.amount","name":"amount","typeExpr":{"k":"primitive","name":"long"},"parent":16,"anchor":[2,29,29]} +{"t":"e","i":24,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Basket.Line.amount()","name":"amount","signature":"amount()","typeExpr":{"k":"primitive","name":"long"},"parent":16,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":5,"halstead.effort":90.4737,"halstead.volume":18.0947,"lloc":1,"mi":80.6522,"nexits":1,"sloc":3},"anchor":[2,35,37]} +{"t":"e","i":25,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Basket.add(com.acme.order.Basket.Line)","name":"add","signature":"add(com.acme.order.Basket.Line)","parent":10,"parameters":[26],"localVariables":[],"metrics":{"abc.assignments":1,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2.2361,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4.8,"halstead.effort":298.8949,"halstead.volume":62.2698,"lloc":2,"mi":74.1686,"nexits":0,"sloc":4},"anchor":[2,13,16]} +{"t":"e","i":26,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Basket.add(com.acme.order.Basket.Line)","d":"param:line","name":"line","declaredType":16,"typeExpr":{"k":"named","type":16},"parent":25,"anchor":[2,13,13]} +{"t":"e","i":27,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Basket.cursor()","name":"cursor","signature":"cursor()","declaredType":12,"typeExpr":{"k":"named","type":12},"parent":10,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2.5,"halstead.effort":45.2368,"halstead.volume":18.0947,"lloc":1,"mi":80.6522,"nexits":1,"sloc":3},"anchor":[2,22,24]} +{"t":"e","i":28,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Basket.lines","name":"lines","declaredType":175,"typeExpr":{"k":"named","type":175,"args":[{"k":"named","type":16}]},"parent":10,"anchor":[2,11,11]} +{"t":"e","i":29,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Basket.total","name":"total","typeExpr":{"k":"primitive","name":"long"},"parent":10,"anchor":[2,9,9]} +{"t":"e","i":30,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Basket.total()","name":"total","signature":"total()","typeExpr":{"k":"primitive","name":"long"},"parent":10,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":5,"halstead.effort":90.4737,"halstead.volume":18.0947,"lloc":1,"mi":80.6522,"nexits":1,"sloc":3},"anchor":[2,18,20]} {"t":"e","i":31,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Batch","name":"Batch","isStub":false,"parent":0,"comments":["Array members and an anonymous class that uses its own members.\n\n

Both were blind spots found by auditing a real corpus (commons-lang), not by\nthis corpus: arrays were present but nothing ever read `array.length`, and an\nanonymous class was present but nothing inside it touched its own fields.\n\n

`counts.length` and `int[]::new` declare their member on the ARRAY type. An\narray is not an entity, and its component type does not own those members —\nattributing them to the component invented a stub class named `int` and an\naccess on `com.acme.order.Money` that the source never writes.\n\n

The anonymous `Priceable` is identified by `#file:line`; Spoon names it\n`Batch$1`, so any edge that names it from a type REFERENCE must be translated\nback, or one declared class ends up with two ids and the second is laundered\ninto a stub carrying the corpus's own package."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":4,"cognitive":0,"halstead.difficulty":15,"halstead.effort":7141.2321,"halstead.volume":476.0821,"lloc":8,"mi":44.4079,"nexits":0,"npa":0,"npm":5,"sloc":29},"anchor":[3,20,62]} {"t":"e","i":32,"k":6,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32","signature":"com.acme.order.Priceable()","parent":45,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"halstead.difficulty":5.7143,"halstead.effort":602.7774,"halstead.volume":105.486,"lloc":2,"mi":61.1305,"nexits":0,"sloc":10},"anchor":[3,48,60]} -{"t":"e","i":33,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.()","signature":"()","parent":32,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[3,48,60]} -{"t":"e","i":34,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.price()","name":"price","signature":"price()","declaredType":60,"parent":32,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2,"halstead.effort":54,"halstead.volume":27,"lloc":1,"mi":76.7098,"nexits":1,"sloc":3},"anchor":[3,53,55]} -{"t":"e","i":35,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.running","name":"running","declaredType":60,"parent":32,"anchor":[3,50,50]} -{"t":"e","i":36,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.scaled(com.acme.order.Money)","name":"scaled","signature":"scaled(com.acme.order.Money)","declaredType":60,"parent":32,"parameters":[37],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":54.2842,"halstead.volume":18.0947,"lloc":1,"mi":80.6522,"nexits":1,"sloc":3},"anchor":[3,57,59]} -{"t":"e","i":37,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.scaled(com.acme.order.Money)#param:base","name":"base","declaredType":60,"parent":36,"anchor":[3,57,57]} -{"t":"e","i":38,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Batch.(int[],com.acme.order.Money[])","signature":"(int[],com.acme.order.Money[])","parent":31,"parameters":[39,40],"localVariables":[],"metrics":{"abc.assignments":2,"abc.branches":0,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":10.5,"halstead.effort":790.4842,"halstead.volume":75.2842,"lloc":2,"mi":73.5915,"nexits":0,"sloc":4},"anchor":[3,26,29]} -{"t":"e","i":39,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Batch.(int[],com.acme.order.Money[])","d":"param:counts","name":"counts","parent":38,"anchor":[3,26,26]} -{"t":"e","i":40,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Batch.(int[],com.acme.order.Money[])","d":"param:prices","name":"prices","declaredType":60,"parent":38,"anchor":[3,26,26]} -{"t":"e","i":41,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,3],"m":0,"s":"Batch.allocator()","name":"allocator","signature":"allocator()","declaredType":178,"parent":31,"parameters":[],"localVariables":[],"comments":["`int[]::new` — a constructor declared on the array type."],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":5.5,"halstead.effort":315.4767,"halstead.volume":57.3594,"lloc":1,"mi":77.1438,"nexits":1,"sloc":3},"anchor":[3,42,44]} -{"t":"e","i":42,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Batch.counts","name":"counts","parent":31,"anchor":[3,22,22]} -{"t":"e","i":43,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,3],"m":0,"s":"Batch.priced()","name":"priced","signature":"priced()","parent":31,"parameters":[],"localVariables":[],"comments":["`prices.length` — a field of `Money[]`, not of `Money`."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":85.588,"halstead.volume":28.5293,"lloc":1,"mi":79.2676,"nexits":1,"sloc":3},"anchor":[3,37,39]} -{"t":"e","i":44,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Batch.prices","name":"prices","declaredType":60,"parent":31,"anchor":[3,24,24]} -{"t":"e","i":45,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,3],"m":0,"s":"Batch.running()","name":"running","signature":"running()","declaredType":115,"parent":31,"parameters":[],"localVariables":[],"comments":["An anonymous class that reads its own field and calls its own method."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":6.2857,"halstead.effort":785.8431,"halstead.volume":125.0205,"lloc":3,"mi":59.1237,"nexits":1,"sloc":12},"anchor":[3,47,61]} -{"t":"e","i":46,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,3],"m":0,"s":"Batch.size()","name":"size","signature":"size()","parent":31,"parameters":[],"localVariables":[],"comments":["`counts.length` — a field of `int[]`, not of `int`."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":85.588,"halstead.volume":28.5293,"lloc":1,"mi":79.2676,"nexits":1,"sloc":3},"anchor":[3,32,34]} +{"t":"e","i":33,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.()","signature":"()","parent":32,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[3,48,60]} +{"t":"e","i":34,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.price()","name":"price","signature":"price()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":32,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2,"halstead.effort":54,"halstead.volume":27,"lloc":1,"mi":76.7098,"nexits":1,"sloc":3},"anchor":[3,53,55]} +{"t":"e","i":35,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.running","name":"running","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":32,"anchor":[3,50,50]} +{"t":"e","i":36,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.scaled(com.acme.order.Money)","name":"scaled","signature":"scaled(com.acme.order.Money)","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":32,"parameters":[37],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":54.2842,"halstead.volume":18.0947,"lloc":1,"mi":80.6522,"nexits":1,"sloc":3},"anchor":[3,57,59]} +{"t":"e","i":37,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Batch","d":"com/acme/order/Batch.java:48:32.scaled(com.acme.order.Money)#param:base","name":"base","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":36,"anchor":[3,57,57]} +{"t":"e","i":38,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Batch.(int[],com.acme.order.Money[])","signature":"(int[],com.acme.order.Money[])","parent":31,"parameters":[39,40],"localVariables":[],"metrics":{"abc.assignments":2,"abc.branches":0,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":10.5,"halstead.effort":790.4842,"halstead.volume":75.2842,"lloc":2,"mi":73.5915,"nexits":0,"sloc":4},"anchor":[3,26,29]} +{"t":"e","i":39,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Batch.(int[],com.acme.order.Money[])","d":"param:counts","name":"counts","typeExpr":{"k":"array","of":{"k":"primitive","name":"int"}},"parent":38,"anchor":[3,26,26]} +{"t":"e","i":40,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Batch.(int[],com.acme.order.Money[])","d":"param:prices","name":"prices","declaredType":60,"typeExpr":{"k":"array","of":{"k":"named","type":60}},"parent":38,"anchor":[3,26,26]} +{"t":"e","i":41,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Batch.allocator()","name":"allocator","signature":"allocator()","declaredType":178,"typeExpr":{"k":"named","type":178,"args":[{"k":"array","of":{"k":"primitive","name":"int"}}]},"parent":31,"parameters":[],"localVariables":[],"comments":["`int[]::new` — a constructor declared on the array type."],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":5.5,"halstead.effort":315.4767,"halstead.volume":57.3594,"lloc":1,"mi":77.1438,"nexits":1,"sloc":3},"anchor":[3,42,44]} +{"t":"e","i":42,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Batch.counts","name":"counts","typeExpr":{"k":"array","of":{"k":"primitive","name":"int"}},"parent":31,"anchor":[3,22,22]} +{"t":"e","i":43,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Batch.priced()","name":"priced","signature":"priced()","typeExpr":{"k":"primitive","name":"int"},"parent":31,"parameters":[],"localVariables":[],"comments":["`prices.length` — a field of `Money[]`, not of `Money`."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":85.588,"halstead.volume":28.5293,"lloc":1,"mi":79.2676,"nexits":1,"sloc":3},"anchor":[3,37,39]} +{"t":"e","i":44,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Batch.prices","name":"prices","declaredType":60,"typeExpr":{"k":"array","of":{"k":"named","type":60}},"parent":31,"anchor":[3,24,24]} +{"t":"e","i":45,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Batch.running()","name":"running","signature":"running()","declaredType":115,"typeExpr":{"k":"named","type":115},"parent":31,"parameters":[],"localVariables":[],"comments":["An anonymous class that reads its own field and calls its own method."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":6.2857,"halstead.effort":785.8431,"halstead.volume":125.0205,"lloc":3,"mi":59.1237,"nexits":1,"sloc":12},"anchor":[3,47,61]} +{"t":"e","i":46,"k":8,"tr":[5,6,1,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Batch.size()","name":"size","signature":"size()","typeExpr":{"k":"primitive","name":"int"},"parent":31,"parameters":[],"localVariables":[],"comments":["`counts.length` — a field of `int[]`, not of `int`."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":85.588,"halstead.volume":28.5293,"lloc":1,"mi":79.2676,"nexits":1,"sloc":3},"anchor":[3,32,34]} {"t":"e","i":47,"k":4,"tr":[5,6,1,11,0,8,12,3],"m":0,"s":"Channel","name":"Channel","isStub":false,"parent":0,"comments":["Where an order came from."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":3.5,"halstead.effort":259.8082,"halstead.volume":74.2309,"lloc":1,"mi":64.8192,"nexits":0,"npa":0,"npm":1,"sloc":9},"anchor":[4,4,13]} -{"t":"e","i":48,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Channel.()","signature":"()","parent":47,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[4,4,13]} -{"t":"e","i":49,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Channel.PHONE","name":"PHONE","declaredType":47,"parent":47,"anchor":[4,6,6]} -{"t":"e","i":50,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Channel.STORE","name":"STORE","declaredType":47,"parent":47,"anchor":[4,7,7]} -{"t":"e","i":51,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Channel.WEB","name":"WEB","declaredType":47,"parent":47,"anchor":[4,5,5]} -{"t":"e","i":52,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Channel.price()","name":"price","signature":"price()","declaredType":60,"parent":47,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2.5,"halstead.effort":79.2481,"halstead.volume":31.6993,"lloc":1,"mi":76.2218,"nexits":1,"sloc":3},"anchor":[4,10,12]} +{"t":"e","i":48,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Channel.()","signature":"()","parent":47,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[4,4,13]} +{"t":"e","i":49,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Channel.PHONE","name":"PHONE","declaredType":47,"typeExpr":{"k":"named","type":47},"parent":47,"anchor":[4,6,6]} +{"t":"e","i":50,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Channel.STORE","name":"STORE","declaredType":47,"typeExpr":{"k":"named","type":47},"parent":47,"anchor":[4,7,7]} +{"t":"e","i":51,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Channel.WEB","name":"WEB","declaredType":47,"typeExpr":{"k":"named","type":47},"parent":47,"anchor":[4,5,5]} +{"t":"e","i":52,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Channel.price()","name":"price","signature":"price()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":47,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2.5,"halstead.effort":79.2481,"halstead.volume":31.6993,"lloc":1,"mi":76.2218,"nexits":1,"sloc":3},"anchor":[4,10,12]} {"t":"e","i":53,"k":5,"tr":[5,6,1,11,0,8,13,3],"m":0,"s":"Discountable","name":"Discountable","isStub":false,"parent":0,"comments":["An order that can be marked down. Extends another corpus interface."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":2.5,"halstead.effort":60,"halstead.volume":24,"lloc":0,"mi":76.9334,"nexits":0,"npa":0,"npm":1,"sloc":3},"anchor":[5,4,7]} -{"t":"e","i":54,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Discountable.discount(int)","name":"discount","signature":"discount(int)","declaredType":60,"parent":53,"parameters":[55],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":1.5,"halstead.effort":17.4145,"halstead.volume":11.6096,"lloc":0,"mi":92.4096,"nexits":0,"sloc":1},"anchor":[5,6,6]} -{"t":"e","i":55,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Discountable.discount(int)","d":"param:percent","name":"percent","parent":54,"anchor":[5,6,6]} +{"t":"e","i":54,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Discountable.discount(int)","name":"discount","signature":"discount(int)","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":53,"parameters":[55],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":1.5,"halstead.effort":17.4145,"halstead.volume":11.6096,"lloc":0,"mi":92.4096,"nexits":0,"sloc":1},"anchor":[5,6,6]} +{"t":"e","i":55,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Discountable.discount(int)","d":"param:percent","name":"percent","typeExpr":{"k":"primitive","name":"int"},"parent":54,"anchor":[5,6,6]} {"t":"e","i":56,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"EmptyBasketException","name":"EmptyBasketException","isStub":false,"parent":0,"comments":["The corpus-declared exception the throw-site regression case targets."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":5,"halstead.effort":154.4045,"halstead.volume":30.8809,"lloc":0,"mi":72.3256,"nexits":0,"npa":0,"npm":1,"sloc":5},"anchor":[6,4,9]} -{"t":"e","i":57,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"EmptyBasketException.(java.lang.String)","signature":"(java.lang.String)","parent":56,"parameters":[58],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":62.0391,"halstead.volume":20.6797,"lloc":0,"mi":80.2461,"nexits":0,"sloc":3},"anchor":[6,6,8]} -{"t":"e","i":58,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"EmptyBasketException.(java.lang.String)","d":"param:message","name":"message","declaredType":164,"parent":57,"anchor":[6,6,6]} +{"t":"e","i":57,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"EmptyBasketException.(java.lang.String)","signature":"(java.lang.String)","parent":56,"parameters":[58],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":62.0391,"halstead.volume":20.6797,"lloc":0,"mi":80.2461,"nexits":0,"sloc":3},"anchor":[6,6,8]} +{"t":"e","i":58,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"EmptyBasketException.(java.lang.String)","d":"param:message","name":"message","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":57,"anchor":[6,6,6]} {"t":"e","i":59,"k":2,"tr":[5,8],"m":0,"s":"Invoice","name":"Invoice","isStub":true} {"t":"e","i":60,"k":11,"tr":[5,6,1,11,0,8,12,3],"m":0,"s":"Money","name":"Money","isStub":false,"parent":0,"comments":["Minor units only; this fixture has no currencies."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":6.25,"halstead.effort":860.047,"halstead.volume":137.6075,"lloc":3,"mi":58.832,"nexits":0,"npa":0,"npm":3,"sloc":12},"anchor":[7,4,18]} -{"t":"e","i":61,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Money.(long)","signature":"(long)","parent":60,"parameters":[62],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[7,4,18]} -{"t":"e","i":62,"k":10,"tr":[5,0,9,7],"m":0,"s":"Money.(long)","d":"param:cents","name":"cents","parent":61} -{"t":"e","i":63,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Money.cents","name":"cents","parent":60,"anchor":[7,4,18]} -{"t":"e","i":64,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Money.cents()","name":"cents","signature":"cents()","parent":60,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[7,4,18]} -{"t":"e","i":65,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Money.price()","name":"price","signature":"price()","declaredType":60,"parent":60,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2.5,"halstead.effort":49.1287,"halstead.volume":19.6515,"lloc":1,"mi":77.6758,"nexits":1,"sloc":3},"anchor":[7,15,17]} -{"t":"e","i":66,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Money.times(int)","name":"times","signature":"times(int)","declaredType":60,"parent":60,"parameters":[67],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4.6667,"halstead.effort":186.028,"halstead.volume":39.8631,"lloc":1,"mi":78.2504,"nexits":1,"sloc":3},"anchor":[7,10,12]} -{"t":"e","i":67,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Money.times(int)","d":"param:factor","name":"factor","parent":66,"anchor":[7,10,10]} -{"t":"e","i":68,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Money.zero()","name":"zero","signature":"zero()","declaredType":60,"parent":60,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2.5,"halstead.effort":56.1471,"halstead.volume":22.4588,"lloc":1,"mi":79.9952,"nexits":1,"sloc":3},"anchor":[7,6,8]} +{"t":"e","i":61,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Money.(long)","signature":"(long)","parent":60,"parameters":[62],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[7,4,18]} +{"t":"e","i":62,"k":10,"tr":[5,0,9,7],"m":0,"s":"Money.(long)","d":"param:cents","name":"cents","typeExpr":{"k":"primitive","name":"long"},"parent":61} +{"t":"e","i":63,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Money.cents","name":"cents","typeExpr":{"k":"primitive","name":"long"},"parent":60,"anchor":[7,4,18]} +{"t":"e","i":64,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Money.cents()","name":"cents","signature":"cents()","typeExpr":{"k":"primitive","name":"long"},"parent":60,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[7,4,18]} +{"t":"e","i":65,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Money.price()","name":"price","signature":"price()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":60,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2.5,"halstead.effort":49.1287,"halstead.volume":19.6515,"lloc":1,"mi":77.6758,"nexits":1,"sloc":3},"anchor":[7,15,17]} +{"t":"e","i":66,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Money.times(int)","name":"times","signature":"times(int)","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":60,"parameters":[67],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4.6667,"halstead.effort":186.028,"halstead.volume":39.8631,"lloc":1,"mi":78.2504,"nexits":1,"sloc":3},"anchor":[7,10,12]} +{"t":"e","i":67,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Money.times(int)","d":"param:factor","name":"factor","typeExpr":{"k":"primitive","name":"int"},"parent":66,"anchor":[7,10,10]} +{"t":"e","i":68,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Money.zero()","name":"zero","signature":"zero()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":60,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2.5,"halstead.effort":56.1471,"halstead.volume":22.4588,"lloc":1,"mi":79.9952,"nexits":1,"sloc":3},"anchor":[7,6,8]} {"t":"e","i":69,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Notifications","name":"Notifications","isStub":false,"parent":0,"comments":["Delivery hooks. Nothing invocable in here has a name of its own."],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"halstead.difficulty":12.88,"halstead.effort":8169.1177,"halstead.volume":634.2483,"lloc":9,"mi":45.8949,"nexits":0,"npa":0,"npm":4,"sloc":27},"anchor":[8,6,39]} {"t":"e","i":70,"k":6,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:11:22","signature":"()","parent":79,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"anchor":[8,11,11]} {"t":"e","i":71,"k":6,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:11:65","signature":"()","parent":79,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"anchor":[8,11,11]} {"t":"e","i":72,"k":6,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:15:16","signature":"()","parent":81,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[8,15,18]} {"t":"e","i":73,"k":6,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:22:32","signature":"com.acme.order.Priceable()","parent":84,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"halstead.difficulty":3.5,"halstead.effort":300.8306,"halstead.volume":85.9516,"lloc":2,"mi":66.4874,"nexits":0,"sloc":7},"anchor":[8,22,29]} -{"t":"e","i":74,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:22:32.()","signature":"()","parent":73,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[8,22,29]} -{"t":"e","i":75,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:22:32.price()","name":"price","signature":"price()","declaredType":60,"parent":73,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":3,"abc.conditions":0,"abc.magnitude":3,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":217.0192,"halstead.volume":72.3397,"lloc":2,"mi":71.5988,"nexits":1,"sloc":4},"anchor":[8,25,28]} +{"t":"e","i":74,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:22:32.()","signature":"()","parent":73,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[8,22,29]} +{"t":"e","i":75,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:22:32.price()","name":"price","signature":"price()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":73,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":3,"abc.conditions":0,"abc.magnitude":3,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":217.0192,"halstead.volume":72.3397,"lloc":2,"mi":71.5988,"nexits":1,"sloc":4},"anchor":[8,25,28]} {"t":"e","i":76,"k":6,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:8:47","signature":"(com.acme.order.Order)","parent":69,"parameters":[77],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":1},"anchor":[8,8,8]} {"t":"e","i":77,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications","d":"com/acme/order/Notifications.java:8:47#param:order","name":"order","declaredType":91,"parent":76,"anchor":[8,8,8]} -{"t":"e","i":78,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Notifications.()","signature":"()","parent":69,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[8,6,39]} -{"t":"e","i":79,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Notifications.both(com.acme.order.Order)","name":"both","signature":"both(com.acme.order.Order)","declaredType":162,"parent":69,"parameters":[80],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":5,"abc.conditions":0,"abc.magnitude":5,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":6.2857,"halstead.effort":712.1703,"halstead.volume":113.2998,"lloc":1,"mi":75.0739,"nexits":1,"sloc":3},"anchor":[8,10,12]} -{"t":"e","i":80,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.both(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"parent":79,"anchor":[8,10,10]} -{"t":"e","i":81,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Notifications.chain(java.lang.Runnable,java.lang.Runnable)","name":"chain","signature":"chain(java.lang.Runnable,java.lang.Runnable)","declaredType":162,"parent":69,"parameters":[82,83],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":6.125,"halstead.effort":444.9694,"halstead.volume":72.6481,"lloc":3,"mi":69.8586,"nexits":1,"sloc":6},"anchor":[8,14,19]} -{"t":"e","i":82,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.chain(java.lang.Runnable,java.lang.Runnable)","d":"param:first","name":"first","declaredType":162,"parent":81,"anchor":[8,14,14]} -{"t":"e","i":83,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.chain(java.lang.Runnable,java.lang.Runnable)","d":"param:second","name":"second","declaredType":162,"parent":81,"anchor":[8,14,14]} -{"t":"e","i":84,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Notifications.freeOf(com.acme.order.Order)","name":"freeOf","signature":"freeOf(com.acme.order.Order)","declaredType":115,"parent":69,"parameters":[85],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3.8889,"halstead.effort":435.5556,"halstead.volume":112,"lloc":3,"mi":63.4339,"nexits":1,"sloc":9},"anchor":[8,21,30]} -{"t":"e","i":85,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.freeOf(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"parent":84,"anchor":[8,21,21]} -{"t":"e","i":86,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Notifications.log(java.lang.String)","name":"log","signature":"log(java.lang.String)","parent":69,"parameters":[87],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":129.5552,"halstead.volume":43.1851,"lloc":1,"mi":78.007,"nexits":0,"sloc":3},"anchor":[8,36,38]} -{"t":"e","i":87,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.log(java.lang.String)","d":"param:message","name":"message","declaredType":164,"parent":86,"anchor":[8,36,36]} -{"t":"e","i":88,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Notifications.notifyShipped(com.acme.order.Order)","name":"notifyShipped","signature":"notifyShipped(com.acme.order.Order)","parent":69,"parameters":[89],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3.125,"halstead.effort":108.9662,"halstead.volume":34.8692,"lloc":1,"mi":78.6574,"nexits":0,"sloc":3},"anchor":[8,32,34]} -{"t":"e","i":89,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.notifyShipped(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"parent":88,"anchor":[8,32,32]} -{"t":"e","i":90,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.onShipped","name":"onShipped","declaredType":177,"parent":69,"anchor":[8,8,8]} +{"t":"e","i":78,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Notifications.()","signature":"()","parent":69,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[8,6,39]} +{"t":"e","i":79,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Notifications.both(com.acme.order.Order)","name":"both","signature":"both(com.acme.order.Order)","declaredType":162,"typeExpr":{"k":"named","type":162},"parent":69,"parameters":[80],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":5,"abc.conditions":0,"abc.magnitude":5,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":6.2857,"halstead.effort":712.1703,"halstead.volume":113.2998,"lloc":1,"mi":75.0739,"nexits":1,"sloc":3},"anchor":[8,10,12]} +{"t":"e","i":80,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.both(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"typeExpr":{"k":"named","type":91},"parent":79,"anchor":[8,10,10]} +{"t":"e","i":81,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Notifications.chain(java.lang.Runnable,java.lang.Runnable)","name":"chain","signature":"chain(java.lang.Runnable,java.lang.Runnable)","declaredType":162,"typeExpr":{"k":"named","type":162},"parent":69,"parameters":[82,83],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":6.125,"halstead.effort":444.9694,"halstead.volume":72.6481,"lloc":3,"mi":69.8586,"nexits":1,"sloc":6},"anchor":[8,14,19]} +{"t":"e","i":82,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.chain(java.lang.Runnable,java.lang.Runnable)","d":"param:first","name":"first","declaredType":162,"typeExpr":{"k":"named","type":162},"parent":81,"anchor":[8,14,14]} +{"t":"e","i":83,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.chain(java.lang.Runnable,java.lang.Runnable)","d":"param:second","name":"second","declaredType":162,"typeExpr":{"k":"named","type":162},"parent":81,"anchor":[8,14,14]} +{"t":"e","i":84,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Notifications.freeOf(com.acme.order.Order)","name":"freeOf","signature":"freeOf(com.acme.order.Order)","declaredType":115,"typeExpr":{"k":"named","type":115},"parent":69,"parameters":[85],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3.8889,"halstead.effort":435.5556,"halstead.volume":112,"lloc":3,"mi":63.4339,"nexits":1,"sloc":9},"anchor":[8,21,30]} +{"t":"e","i":85,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.freeOf(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"typeExpr":{"k":"named","type":91},"parent":84,"anchor":[8,21,21]} +{"t":"e","i":86,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Notifications.log(java.lang.String)","name":"log","signature":"log(java.lang.String)","parent":69,"parameters":[87],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":129.5552,"halstead.volume":43.1851,"lloc":1,"mi":78.007,"nexits":0,"sloc":3},"anchor":[8,36,38]} +{"t":"e","i":87,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.log(java.lang.String)","d":"param:message","name":"message","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":86,"anchor":[8,36,36]} +{"t":"e","i":88,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Notifications.notifyShipped(com.acme.order.Order)","name":"notifyShipped","signature":"notifyShipped(com.acme.order.Order)","parent":69,"parameters":[89],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3.125,"halstead.effort":108.9662,"halstead.volume":34.8692,"lloc":1,"mi":78.6574,"nexits":0,"sloc":3},"anchor":[8,32,34]} +{"t":"e","i":89,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Notifications.notifyShipped(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"typeExpr":{"k":"named","type":91},"parent":88,"anchor":[8,32,32]} +{"t":"e","i":90,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Notifications.onShipped","name":"onShipped","declaredType":177,"typeExpr":{"k":"named","type":177,"args":[{"k":"named","type":91}]},"parent":69,"anchor":[8,8,8]} {"t":"e","i":91,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Order","name":"Order","isStub":false,"parent":0,"comments":["A customer order. The one-argument constructor delegates to the other."],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":3,"cognitive":0,"halstead.difficulty":12.0833,"halstead.effort":4510.5291,"halstead.volume":373.2852,"lloc":3,"mi":49.0962,"nexits":0,"npa":1,"npm":4,"sloc":20},"anchor":[9,6,35]} -{"t":"e","i":92,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Order.(java.lang.String)","signature":"(java.lang.String)","parent":91,"parameters":[93],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3.75,"halstead.effort":149.4868,"halstead.volume":39.8631,"lloc":0,"mi":78.2504,"nexits":0,"sloc":3},"anchor":[9,16,18]} -{"t":"e","i":93,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.(java.lang.String)","d":"param:reference","name":"reference","declaredType":164,"parent":92,"anchor":[9,16,16]} -{"t":"e","i":94,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Order.(java.lang.String,com.acme.order.Channel)","signature":"(java.lang.String,com.acme.order.Channel)","parent":91,"parameters":[96,95],"localVariables":[],"metrics":{"abc.assignments":1,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1.4142,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":8,"halstead.effort":442.8072,"halstead.volume":55.3509,"lloc":1,"mi":74.5268,"nexits":0,"sloc":4},"anchor":[9,20,23]} -{"t":"e","i":95,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.(java.lang.String,com.acme.order.Channel)","d":"param:channel","name":"channel","declaredType":47,"parent":94,"anchor":[9,20,20]} -{"t":"e","i":96,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.(java.lang.String,com.acme.order.Channel)","d":"param:reference","name":"reference","declaredType":164,"parent":94,"anchor":[9,20,20]} -{"t":"e","i":97,"k":1,"tr":[5,6,1,0,9,7,17],"m":0,"s":"Order.MAX_LINES","name":"MAX_LINES","parent":91,"comments":["A compile-time constant: the initializer folds across the arithmetic."],"value":{"k":"number","v":"100"},"anchor":[9,9,9]} -{"t":"e","i":98,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"Order.channel","name":"channel","declaredType":47,"parent":91,"anchor":[9,14,14]} -{"t":"e","i":99,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Order.channel()","name":"channel","signature":"channel()","declaredType":47,"parent":91,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4,"halstead.effort":55.7263,"halstead.volume":13.9316,"lloc":1,"mi":81.4473,"nexits":1,"sloc":3},"anchor":[9,25,27]} -{"t":"e","i":100,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Order.discount(int)","name":"discount","signature":"discount(int)","declaredType":60,"parent":91,"parameters":[101],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":1,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3.8889,"halstead.effort":311.1111,"halstead.volume":80,"lloc":1,"mi":69.5655,"nexits":1,"sloc":3},"anchor":[9,31,34]} -{"t":"e","i":101,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.discount(int)","d":"param:percent","name":"percent","parent":100,"anchor":[9,31,31]} -{"t":"e","i":102,"k":1,"tr":[5,6,1,0,9,7],"m":0,"s":"Order.trail","name":"trail","declaredType":165,"parent":91,"comments":["Final, but NOT a constant: an initializer that is code carries no value."],"anchor":[9,12,12]} -{"t":"e","i":103,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"OrderService","name":"OrderService","isStub":false,"parent":0,"comments":["Billing and archival. Both {@code archive} overloads take a parameter whose\nsimple name is {@code List}; only their packages differ."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":20.3,"halstead.effort":7352.9044,"halstead.volume":362.212,"lloc":7,"mi":51.1672,"nexits":0,"npa":0,"npm":4,"sloc":19},"anchor":[10,9,32]} -{"t":"e","i":104,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"OrderService.(com.megacorp.ledger.LedgerClient)","signature":"(com.megacorp.ledger.LedgerClient)","parent":103,"parameters":[105],"localVariables":[],"metrics":{"abc.assignments":1,"abc.branches":0,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":6,"halstead.effort":180,"halstead.volume":30,"lloc":1,"mi":79.1148,"nexits":0,"sloc":3},"anchor":[10,13,15]} -{"t":"e","i":105,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.(com.megacorp.ledger.LedgerClient)","d":"param:ledger","name":"ledger","declaredType":155,"parent":104,"anchor":[10,13,13]} -{"t":"e","i":106,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"OrderService.archive(com.acme.order.legacy.List)","name":"archive","signature":"archive(com.acme.order.legacy.List)","parent":103,"parameters":[107],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3.75,"halstead.effort":213.9699,"halstead.volume":57.0587,"lloc":1,"mi":77.1598,"nexits":0,"sloc":3},"anchor":[10,29,31]} -{"t":"e","i":107,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.archive(com.acme.order.legacy.List)","d":"param:orders","name":"orders","declaredType":146,"parent":106,"anchor":[10,29,29]} -{"t":"e","i":108,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"OrderService.archive(java.util.List)","name":"archive","signature":"archive(java.util.List)","parent":103,"parameters":[110],"localVariables":[109],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":1,"cyclomatic":2,"halstead.difficulty":7.2,"halstead.effort":657.9109,"halstead.volume":91.3765,"lloc":2,"mi":70.7539,"nexits":0,"sloc":5},"anchor":[10,23,27]} -{"t":"e","i":109,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.archive(java.util.List)","d":"local:order:24","name":"order","declaredType":91,"parent":108,"anchor":[10,24,24]} -{"t":"e","i":110,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.archive(java.util.List)","d":"param:orders","name":"orders","declaredType":175,"parent":108,"anchor":[10,23,23]} -{"t":"e","i":111,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"OrderService.bill(com.acme.order.Order)","name":"bill","signature":"bill(com.acme.order.Order)","declaredType":59,"parent":103,"parameters":[113],"localVariables":[112],"metrics":{"abc.assignments":1,"abc.branches":3,"abc.conditions":0,"abc.magnitude":3.1623,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":5.25,"halstead.effort":427.4008,"halstead.volume":81.4097,"lloc":3,"mi":71.2396,"nexits":1,"sloc":5},"anchor":[10,17,21]} -{"t":"e","i":112,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.bill(com.acme.order.Order)","d":"local:invoice:18","name":"invoice","declaredType":59,"parent":111,"anchor":[10,18,18]} -{"t":"e","i":113,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.bill(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"parent":111,"anchor":[10,17,17]} -{"t":"e","i":114,"k":1,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.ledger","name":"ledger","declaredType":155,"parent":103,"anchor":[10,11,11]} +{"t":"e","i":92,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Order.(java.lang.String)","signature":"(java.lang.String)","parent":91,"parameters":[93],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3.75,"halstead.effort":149.4868,"halstead.volume":39.8631,"lloc":0,"mi":78.2504,"nexits":0,"sloc":3},"anchor":[9,16,18]} +{"t":"e","i":93,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.(java.lang.String)","d":"param:reference","name":"reference","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":92,"anchor":[9,16,16]} +{"t":"e","i":94,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Order.(java.lang.String,com.acme.order.Channel)","signature":"(java.lang.String,com.acme.order.Channel)","parent":91,"parameters":[96,95],"localVariables":[],"metrics":{"abc.assignments":1,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1.4142,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":8,"halstead.effort":442.8072,"halstead.volume":55.3509,"lloc":1,"mi":74.5268,"nexits":0,"sloc":4},"anchor":[9,20,23]} +{"t":"e","i":95,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.(java.lang.String,com.acme.order.Channel)","d":"param:channel","name":"channel","declaredType":47,"typeExpr":{"k":"named","type":47},"parent":94,"anchor":[9,20,20]} +{"t":"e","i":96,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.(java.lang.String,com.acme.order.Channel)","d":"param:reference","name":"reference","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":94,"anchor":[9,20,20]} +{"t":"e","i":97,"k":1,"tr":[5,6,1,0,9,7,18],"m":0,"s":"Order.MAX_LINES","name":"MAX_LINES","typeExpr":{"k":"primitive","name":"int"},"parent":91,"comments":["A compile-time constant: the initializer folds across the arithmetic."],"value":{"k":"number","v":"100"},"anchor":[9,9,9]} +{"t":"e","i":98,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"Order.channel","name":"channel","declaredType":47,"typeExpr":{"k":"named","type":47},"parent":91,"anchor":[9,14,14]} +{"t":"e","i":99,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Order.channel()","name":"channel","signature":"channel()","declaredType":47,"typeExpr":{"k":"named","type":47},"parent":91,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4,"halstead.effort":55.7263,"halstead.volume":13.9316,"lloc":1,"mi":81.4473,"nexits":1,"sloc":3},"anchor":[9,25,27]} +{"t":"e","i":100,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Order.discount(int)","name":"discount","signature":"discount(int)","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":91,"parameters":[101],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":1,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3.8889,"halstead.effort":311.1111,"halstead.volume":80,"lloc":1,"mi":69.5655,"nexits":1,"sloc":3},"anchor":[9,31,34]} +{"t":"e","i":101,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Order.discount(int)","d":"param:percent","name":"percent","typeExpr":{"k":"primitive","name":"int"},"parent":100,"anchor":[9,31,31]} +{"t":"e","i":102,"k":1,"tr":[5,6,1,0,9,7,17],"m":0,"s":"Order.trail","name":"trail","declaredType":165,"typeExpr":{"k":"named","type":165},"parent":91,"comments":["Final, but NOT a constant: an initializer that is code carries no value."],"anchor":[9,12,12]} +{"t":"e","i":103,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"OrderService","name":"OrderService","isStub":false,"parent":0,"comments":["Billing and archival. Both {@code archive} overloads take a parameter whose\nsimple name is {@code List}; only their packages differ."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":23.2,"halstead.effort":8833.0663,"halstead.volume":380.7356,"lloc":7,"mi":51.0155,"nexits":0,"npa":0,"npm":4,"sloc":19},"anchor":[10,9,32]} +{"t":"e","i":104,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"OrderService.(com.megacorp.ledger.LedgerClient)","signature":"(com.megacorp.ledger.LedgerClient)","parent":103,"parameters":[105],"localVariables":[],"metrics":{"abc.assignments":1,"abc.branches":0,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":6,"halstead.effort":180,"halstead.volume":30,"lloc":1,"mi":79.1148,"nexits":0,"sloc":3},"anchor":[10,13,15]} +{"t":"e","i":105,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.(com.megacorp.ledger.LedgerClient)","d":"param:ledger","name":"ledger","declaredType":155,"typeExpr":{"k":"named","type":155},"parent":104,"anchor":[10,13,13]} +{"t":"e","i":106,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"OrderService.archive(com.acme.order.legacy.List)","name":"archive","signature":"archive(com.acme.order.legacy.List)","parent":103,"parameters":[107],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3.75,"halstead.effort":213.9699,"halstead.volume":57.0587,"lloc":1,"mi":77.1598,"nexits":0,"sloc":3},"anchor":[10,29,31]} +{"t":"e","i":107,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.archive(com.acme.order.legacy.List)","d":"param:orders","name":"orders","declaredType":146,"typeExpr":{"k":"named","type":146},"parent":106,"anchor":[10,29,29]} +{"t":"e","i":108,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"OrderService.archive(java.util.List)","name":"archive","signature":"archive(java.util.List)","parent":103,"parameters":[110],"localVariables":[109],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":1,"cyclomatic":2,"halstead.difficulty":8.8,"halstead.effort":915.2,"halstead.volume":104,"lloc":2,"mi":70.3604,"nexits":0,"sloc":5},"anchor":[10,23,27]} +{"t":"e","i":109,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.archive(java.util.List)","d":"local:order:24","name":"order","declaredType":91,"typeExpr":{"k":"named","type":91},"parent":108,"anchor":[10,24,24]} +{"t":"e","i":110,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.archive(java.util.List)","d":"param:orders","name":"orders","declaredType":175,"typeExpr":{"k":"named","type":175,"args":[{"k":"unevaluated","source":"? extends Order"}]},"parent":108,"anchor":[10,23,23]} +{"t":"e","i":111,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"OrderService.bill(com.acme.order.Order)","name":"bill","signature":"bill(com.acme.order.Order)","declaredType":59,"typeExpr":{"k":"named","type":59},"parent":103,"parameters":[113],"localVariables":[112],"metrics":{"abc.assignments":1,"abc.branches":3,"abc.conditions":0,"abc.magnitude":3.1623,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":5.25,"halstead.effort":427.4008,"halstead.volume":81.4097,"lloc":3,"mi":71.2396,"nexits":1,"sloc":5},"anchor":[10,17,21]} +{"t":"e","i":112,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.bill(com.acme.order.Order)","d":"local:invoice:18","name":"invoice","declaredType":59,"typeExpr":{"k":"named","type":59},"parent":111,"anchor":[10,18,18]} +{"t":"e","i":113,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"OrderService.bill(com.acme.order.Order)","d":"param:order","name":"order","declaredType":91,"typeExpr":{"k":"named","type":91},"parent":111,"anchor":[10,17,17]} +{"t":"e","i":114,"k":1,"tr":[5,6,0,9,7,17],"m":0,"s":"OrderService.ledger","name":"ledger","declaredType":155,"typeExpr":{"k":"named","type":155},"parent":103,"anchor":[10,11,11]} {"t":"e","i":115,"k":5,"tr":[5,6,1,11,0,8,13,3],"m":0,"s":"Priceable","name":"Priceable","isStub":false,"parent":0,"comments":["Anything the pricing engine can put a number on."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":1.5,"halstead.effort":17.4145,"halstead.volume":11.6096,"lloc":0,"mi":79.1418,"nexits":0,"npa":0,"npm":1,"sloc":3},"anchor":[11,4,7]} -{"t":"e","i":116,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Priceable.price()","name":"price","signature":"price()","declaredType":60,"parent":115,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":1,"halstead.effort":4.7549,"halstead.volume":4.7549,"lloc":0,"mi":95.1242,"nexits":0,"sloc":1},"anchor":[11,6,6]} +{"t":"e","i":116,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Priceable.price()","name":"price","signature":"price()","declaredType":60,"typeExpr":{"k":"named","type":60},"parent":115,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":1,"halstead.effort":4.7549,"halstead.volume":4.7549,"lloc":0,"mi":95.1242,"nexits":0,"sloc":1},"anchor":[11,6,6]} {"t":"e","i":117,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"Reporting","name":"Reporting","isStub":false,"parent":0,"comments":["Monthly reporting helpers."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":14.62,"halstead.effort":9854.4601,"halstead.volume":674.0397,"lloc":12,"mi":45.5892,"nexits":0,"npa":0,"npm":5,"sloc":28},"anchor":[12,9,41]} -{"t":"e","i":118,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"Reporting.()","signature":"()","parent":117,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[12,9,41]} -{"t":"e","i":119,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Reporting.first(java.util.List)","name":"first","signature":"first(java.util.List)","declaredType":160,"parent":117,"parameters":[120],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":2,"abc.magnitude":2.8284,"cloc":0,"cognitive":1,"cyclomatic":2,"halstead.difficulty":6,"halstead.effort":562.5922,"halstead.volume":93.7654,"lloc":1,"mi":75.5148,"nexits":1,"sloc":3},"anchor":[12,34,36]} -{"t":"e","i":120,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.first(java.util.List)","d":"param:values","name":"values","declaredType":175,"parent":119,"anchor":[12,34,34]} -{"t":"e","i":121,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Reporting.join(java.lang.String[])","name":"join","signature":"join(java.lang.String[])","declaredType":164,"parent":117,"parameters":[124],"localVariables":[122,123],"metrics":{"abc.assignments":1,"abc.branches":3,"abc.conditions":0,"abc.magnitude":3.1623,"cloc":0,"cognitive":1,"cyclomatic":2,"halstead.difficulty":8.3333,"halstead.effort":933.3333,"halstead.volume":112,"lloc":4,"mi":66.9474,"nexits":1,"sloc":7},"anchor":[12,15,21]} -{"t":"e","i":122,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.join(java.lang.String[])","d":"local:out:16","name":"out","declaredType":165,"parent":121,"anchor":[12,16,16]} -{"t":"e","i":123,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.join(java.lang.String[])","d":"local:part:17","name":"part","declaredType":164,"parent":121,"anchor":[12,17,17]} -{"t":"e","i":124,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.join(java.lang.String[])","d":"param:parts","name":"parts","declaredType":164,"parent":121,"anchor":[12,15,15]} -{"t":"e","i":125,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Reporting.lines(java.lang.String[])","name":"lines","signature":"lines(java.lang.String[])","declaredType":173,"parent":117,"parameters":[126],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4.6667,"halstead.effort":232.535,"halstead.volume":49.8289,"lloc":1,"mi":77.5718,"nexits":1,"sloc":3},"anchor":[12,11,13]} -{"t":"e","i":126,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.lines(java.lang.String[])","d":"param:rows","name":"rows","declaredType":164,"parent":125,"anchor":[12,11,11]} -{"t":"e","i":127,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Reporting.max(java.util.List)","name":"max","signature":"max(java.util.List)","declaredType":159,"parent":117,"parameters":[130],"localVariables":[128,129],"metrics":{"abc.assignments":2,"abc.branches":1,"abc.conditions":2,"abc.magnitude":3,"cloc":0,"cognitive":4,"cyclomatic":4,"halstead.difficulty":13.2222,"halstead.effort":2811.1424,"halstead.volume":212.6074,"lloc":5,"mi":61.3503,"nexits":1,"sloc":9},"anchor":[12,24,32]} -{"t":"e","i":128,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.max(java.util.List)","d":"local:best:25","name":"best","declaredType":159,"parent":127,"anchor":[12,25,25]} -{"t":"e","i":129,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.max(java.util.List)","d":"local:value:26","name":"value","declaredType":159,"parent":127,"anchor":[12,26,26]} -{"t":"e","i":130,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.max(java.util.List)","d":"param:values","name":"values","declaredType":175,"parent":127,"anchor":[12,24,24]} -{"t":"e","i":131,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"Reporting.today()","name":"today","signature":"today()","declaredType":171,"parent":117,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2.5,"halstead.effort":67.5,"halstead.volume":27,"lloc":1,"mi":79.4352,"nexits":1,"sloc":3},"anchor":[12,38,40]} +{"t":"e","i":118,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"Reporting.()","signature":"()","parent":117,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[12,9,41]} +{"t":"e","i":119,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Reporting.first(java.util.List)","name":"first","signature":"first(java.util.List)","declaredType":160,"typeExpr":{"k":"variable","name":"T"},"parent":117,"parameters":[120],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":2,"abc.magnitude":2.8284,"cloc":0,"cognitive":1,"cyclomatic":2,"halstead.difficulty":6,"halstead.effort":562.5922,"halstead.volume":93.7654,"lloc":1,"mi":75.5148,"nexits":1,"sloc":3},"anchor":[12,34,36]} +{"t":"e","i":120,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.first(java.util.List)","d":"param:values","name":"values","declaredType":175,"typeExpr":{"k":"named","type":175,"args":[{"k":"variable","name":"T"}]},"parent":119,"anchor":[12,34,34]} +{"t":"e","i":121,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Reporting.join(java.lang.String[])","name":"join","signature":"join(java.lang.String[])","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":117,"parameters":[124],"localVariables":[122,123],"metrics":{"abc.assignments":1,"abc.branches":3,"abc.conditions":0,"abc.magnitude":3.1623,"cloc":0,"cognitive":1,"cyclomatic":2,"halstead.difficulty":8.3333,"halstead.effort":933.3333,"halstead.volume":112,"lloc":4,"mi":66.9474,"nexits":1,"sloc":7},"anchor":[12,15,21]} +{"t":"e","i":122,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.join(java.lang.String[])","d":"local:out:16","name":"out","declaredType":165,"typeExpr":{"k":"named","type":165},"parent":121,"anchor":[12,16,16]} +{"t":"e","i":123,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.join(java.lang.String[])","d":"local:part:17","name":"part","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":121,"anchor":[12,17,17]} +{"t":"e","i":124,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.join(java.lang.String[])","d":"param:parts","name":"parts","declaredType":164,"typeExpr":{"k":"array","of":{"k":"named","type":164}},"parent":121,"anchor":[12,15,15]} +{"t":"e","i":125,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Reporting.lines(java.lang.String[])","name":"lines","signature":"lines(java.lang.String[])","declaredType":173,"typeExpr":{"k":"named","type":173,"args":[{"k":"named","type":164}]},"parent":117,"parameters":[126],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4.6667,"halstead.effort":232.535,"halstead.volume":49.8289,"lloc":1,"mi":77.5718,"nexits":1,"sloc":3},"anchor":[12,11,13]} +{"t":"e","i":126,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.lines(java.lang.String[])","d":"param:rows","name":"rows","declaredType":164,"typeExpr":{"k":"array","of":{"k":"named","type":164}},"parent":125,"anchor":[12,11,11]} +{"t":"e","i":127,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Reporting.max(java.util.List)","name":"max","signature":"max(java.util.List)","declaredType":159,"typeExpr":{"k":"variable","name":"T"},"parent":117,"parameters":[130],"localVariables":[128,129],"metrics":{"abc.assignments":2,"abc.branches":1,"abc.conditions":2,"abc.magnitude":3,"cloc":0,"cognitive":4,"cyclomatic":4,"halstead.difficulty":13.2222,"halstead.effort":2811.1424,"halstead.volume":212.6074,"lloc":5,"mi":61.3503,"nexits":1,"sloc":9},"anchor":[12,24,32]} +{"t":"e","i":128,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.max(java.util.List)","d":"local:best:25","name":"best","declaredType":159,"typeExpr":{"k":"variable","name":"T"},"parent":127,"anchor":[12,25,25]} +{"t":"e","i":129,"k":7,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.max(java.util.List)","d":"local:value:26","name":"value","declaredType":159,"typeExpr":{"k":"variable","name":"T"},"parent":127,"anchor":[12,26,26]} +{"t":"e","i":130,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"Reporting.max(java.util.List)","d":"param:values","name":"values","declaredType":175,"typeExpr":{"k":"named","type":175,"args":[{"k":"variable","name":"T"}]},"parent":127,"anchor":[12,24,24]} +{"t":"e","i":131,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"Reporting.today()","name":"today","signature":"today()","declaredType":171,"typeExpr":{"k":"named","type":171},"parent":117,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":2.5,"halstead.effort":67.5,"halstead.volume":27,"lloc":1,"mi":79.4352,"nexits":1,"sloc":3},"anchor":[12,38,40]} {"t":"e","i":132,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":0,"s":"StockGuard","name":"StockGuard","isStub":false,"parent":0,"comments":["Throw-site regression case: a guard clause and a rethrow must each emit a\n{@code throws} edge anchored at its own statement, and the {@code throws}\nclause on {@code check} must stay a plain reference (propagation, not a\nfailure exit)."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":11.1429,"halstead.effort":1926.3451,"halstead.volume":172.8771,"lloc":5,"mi":57.3922,"nexits":0,"npa":0,"npm":0,"sloc":14},"anchor":[13,9,24]} -{"t":"e","i":133,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"StockGuard.()","signature":"()","parent":132,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[13,9,24]} -{"t":"e","i":134,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"StockGuard.check(int)","name":"check","signature":"check(int)","parent":132,"parameters":[135],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":72,"halstead.volume":24,"lloc":0,"mi":83.6346,"nexits":0,"sloc":2},"anchor":[13,22,23]} -{"t":"e","i":135,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"StockGuard.check(int)","d":"param:quantity","name":"quantity","parent":134,"anchor":[13,22,22]} -{"t":"e","i":136,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":0,"s":"StockGuard.ensure(int)","name":"ensure","signature":"ensure(int)","parent":132,"parameters":[137],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":3,"abc.magnitude":3.6056,"cloc":0,"cognitive":2,"cyclomatic":3,"halstead.difficulty":8.25,"halstead.effort":1011.6471,"halstead.volume":122.6239,"lloc":5,"mi":63.1583,"nexits":2,"sloc":10},"anchor":[13,11,20]} -{"t":"e","i":137,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"StockGuard.ensure(int)","d":"param:quantity","name":"quantity","parent":136,"anchor":[13,11,11]} +{"t":"e","i":133,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":0,"s":"StockGuard.()","signature":"()","parent":132,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[13,9,24]} +{"t":"e","i":134,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"StockGuard.check(int)","name":"check","signature":"check(int)","parent":132,"parameters":[135],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":3,"halstead.effort":72,"halstead.volume":24,"lloc":0,"mi":83.6346,"nexits":0,"sloc":2},"anchor":[13,22,23]} +{"t":"e","i":135,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"StockGuard.check(int)","d":"param:quantity","name":"quantity","typeExpr":{"k":"primitive","name":"int"},"parent":134,"anchor":[13,22,22]} +{"t":"e","i":136,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":0,"s":"StockGuard.ensure(int)","name":"ensure","signature":"ensure(int)","parent":132,"parameters":[137],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":3,"abc.magnitude":3.6056,"cloc":0,"cognitive":2,"cyclomatic":3,"halstead.difficulty":8.25,"halstead.effort":1011.6471,"halstead.volume":122.6239,"lloc":5,"mi":63.1583,"nexits":2,"sloc":10},"anchor":[13,11,20]} +{"t":"e","i":137,"k":10,"tr":[5,6,0,9,7],"m":0,"s":"StockGuard.ensure(int)","d":"param:quantity","name":"quantity","typeExpr":{"k":"primitive","name":"int"},"parent":136,"anchor":[13,11,11]} {"t":"e","i":138,"k":9,"tr":[5,11,0,4],"m":138,"s":"com.acme.order.adapter","name":"com.acme.order.adapter","isStub":false,"parent":0,"definedIn":[14]} {"t":"e","i":139,"k":2,"tr":[5,8],"m":138,"s":"AuditTrail","name":"AuditTrail","isStub":true} {"t":"e","i":140,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":138,"s":"LedgerAdapter","name":"LedgerAdapter","isStub":false,"parent":138,"comments":["Posts to the ledger and keeps a local trail."],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":0,"abc.magnitude":1,"cloc":0,"cognitive":0,"halstead.difficulty":8.3333,"halstead.effort":900,"halstead.volume":108,"lloc":2,"mi":63.679,"nexits":0,"npa":0,"npm":1,"sloc":8},"anchor":[14,6,15]} -{"t":"e","i":141,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":138,"s":"LedgerAdapter.()","signature":"()","parent":140,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[14,6,15]} -{"t":"e","i":142,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":138,"s":"LedgerAdapter.post(java.lang.Object)","name":"post","signature":"post(java.lang.Object)","parent":140,"parameters":[143],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4.8,"halstead.effort":298.8949,"halstead.volume":62.2698,"lloc":2,"mi":72.0546,"nexits":0,"sloc":4},"anchor":[14,11,14]} -{"t":"e","i":143,"k":10,"tr":[5,6,0,9,7],"m":138,"s":"LedgerAdapter.post(java.lang.Object)","d":"param:document","name":"document","declaredType":160,"parent":142,"anchor":[14,11,11]} -{"t":"e","i":144,"k":1,"tr":[5,6,0,9,7],"m":138,"s":"LedgerAdapter.trail","name":"trail","declaredType":139,"parent":140,"anchor":[14,8,8]} +{"t":"e","i":141,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":138,"s":"LedgerAdapter.()","signature":"()","parent":140,"parameters":[],"localVariables":[],"metrics":{"cyclomatic":1},"anchor":[14,6,15]} +{"t":"e","i":142,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":138,"s":"LedgerAdapter.post(java.lang.Object)","name":"post","signature":"post(java.lang.Object)","parent":140,"parameters":[143],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":2,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4.8,"halstead.effort":298.8949,"halstead.volume":62.2698,"lloc":2,"mi":72.0546,"nexits":0,"sloc":4},"anchor":[14,11,14]} +{"t":"e","i":143,"k":10,"tr":[5,6,0,9,7],"m":138,"s":"LedgerAdapter.post(java.lang.Object)","d":"param:document","name":"document","declaredType":160,"typeExpr":{"k":"named","type":160},"parent":142,"anchor":[14,11,11]} +{"t":"e","i":144,"k":1,"tr":[5,6,0,9,7,17],"m":138,"s":"LedgerAdapter.trail","name":"trail","declaredType":139,"typeExpr":{"k":"named","type":139},"parent":140,"anchor":[14,8,8]} {"t":"e","i":145,"k":9,"tr":[5,11,0,4],"m":145,"s":"com.acme.order.legacy","name":"com.acme.order.legacy","isStub":false,"parent":0,"definedIn":[15]} {"t":"e","i":146,"k":2,"tr":[5,6,1,11,0,8,13,12,3],"m":145,"s":"List","name":"List","isStub":false,"parent":145,"comments":["A hand-rolled cons list from before java.util was allowed here."],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"halstead.difficulty":22.1667,"halstead.effort":4790.137,"halstead.volume":216.0964,"lloc":4,"mi":55.0856,"nexits":0,"npa":0,"npm":3,"sloc":14},"anchor":[15,4,22]} -{"t":"e","i":147,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":145,"s":"List.(java.lang.String,com.acme.order.legacy.List)","signature":"(java.lang.String,com.acme.order.legacy.List)","parent":146,"parameters":[148,149],"localVariables":[],"metrics":{"abc.assignments":2,"abc.branches":0,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":8.1667,"halstead.effort":488.3234,"halstead.volume":59.7947,"lloc":2,"mi":74.292,"nexits":0,"sloc":4},"anchor":[15,10,13]} -{"t":"e","i":148,"k":10,"tr":[5,6,0,9,7],"m":145,"s":"List.(java.lang.String,com.acme.order.legacy.List)","d":"param:head","name":"head","declaredType":164,"parent":147,"anchor":[15,10,10]} -{"t":"e","i":149,"k":10,"tr":[5,6,0,9,7],"m":145,"s":"List.(java.lang.String,com.acme.order.legacy.List)","d":"param:tail","name":"tail","declaredType":146,"parent":147,"anchor":[15,10,10]} -{"t":"e","i":150,"k":1,"tr":[5,6,0,9,7],"m":145,"s":"List.head","name":"head","declaredType":164,"parent":146,"anchor":[15,6,6]} -{"t":"e","i":151,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":145,"s":"List.head()","name":"head","signature":"head()","declaredType":164,"parent":146,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4,"halstead.effort":55.7263,"halstead.volume":13.9316,"lloc":1,"mi":81.4473,"nexits":1,"sloc":3},"anchor":[15,15,17]} -{"t":"e","i":152,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,3],"m":145,"s":"List.length()","name":"length","signature":"length()","parent":146,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":2,"abc.magnitude":2.2361,"cloc":0,"cognitive":1,"cyclomatic":2,"halstead.difficulty":8.75,"halstead.effort":599.6584,"halstead.volume":68.5324,"lloc":1,"mi":76.4681,"nexits":1,"sloc":3},"anchor":[15,19,21]} -{"t":"e","i":153,"k":1,"tr":[5,6,0,9,7],"m":145,"s":"List.tail","name":"tail","declaredType":146,"parent":146,"anchor":[15,8,8]} +{"t":"e","i":147,"k":3,"tr":[6,11,0,2,16,15,14,10,17,3],"m":145,"s":"List.(java.lang.String,com.acme.order.legacy.List)","signature":"(java.lang.String,com.acme.order.legacy.List)","parent":146,"parameters":[148,149],"localVariables":[],"metrics":{"abc.assignments":2,"abc.branches":0,"abc.conditions":0,"abc.magnitude":2,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":8.1667,"halstead.effort":488.3234,"halstead.volume":59.7947,"lloc":2,"mi":74.292,"nexits":0,"sloc":4},"anchor":[15,10,13]} +{"t":"e","i":148,"k":10,"tr":[5,6,0,9,7],"m":145,"s":"List.(java.lang.String,com.acme.order.legacy.List)","d":"param:head","name":"head","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":147,"anchor":[15,10,10]} +{"t":"e","i":149,"k":10,"tr":[5,6,0,9,7],"m":145,"s":"List.(java.lang.String,com.acme.order.legacy.List)","d":"param:tail","name":"tail","declaredType":146,"typeExpr":{"k":"named","type":146},"parent":147,"anchor":[15,10,10]} +{"t":"e","i":150,"k":1,"tr":[5,6,0,9,7,17],"m":145,"s":"List.head","name":"head","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":146,"anchor":[15,6,6]} +{"t":"e","i":151,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":145,"s":"List.head()","name":"head","signature":"head()","declaredType":164,"typeExpr":{"k":"named","type":164},"parent":146,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":0,"abc.conditions":0,"abc.magnitude":0,"cloc":0,"cognitive":0,"cyclomatic":1,"halstead.difficulty":4,"halstead.effort":55.7263,"halstead.volume":13.9316,"lloc":1,"mi":81.4473,"nexits":1,"sloc":3},"anchor":[15,15,17]} +{"t":"e","i":152,"k":8,"tr":[5,6,11,0,9,2,16,15,14,10,17,3],"m":145,"s":"List.length()","name":"length","signature":"length()","typeExpr":{"k":"primitive","name":"int"},"parent":146,"parameters":[],"localVariables":[],"metrics":{"abc.assignments":0,"abc.branches":1,"abc.conditions":2,"abc.magnitude":2.2361,"cloc":0,"cognitive":1,"cyclomatic":2,"halstead.difficulty":8.75,"halstead.effort":599.6584,"halstead.volume":68.5324,"lloc":1,"mi":76.4681,"nexits":1,"sloc":3},"anchor":[15,19,21]} +{"t":"e","i":153,"k":1,"tr":[5,6,0,9,7,17],"m":145,"s":"List.tail","name":"tail","declaredType":146,"typeExpr":{"k":"named","type":146},"parent":146,"anchor":[15,8,8]} {"t":"e","i":154,"k":9,"tr":[5,11,4],"m":154,"s":"com.megacorp.ledger","name":"com.megacorp.ledger","isStub":true,"definedIn":[]} {"t":"e","i":155,"k":2,"tr":[5,0,8],"m":154,"s":"LedgerClient","name":"LedgerClient","isStub":true,"parent":154} {"t":"e","i":156,"k":9,"tr":[5,11,4],"m":156,"s":"java.io","name":"java.io","isStub":true,"definedIn":[]} @@ -205,29 +205,29 @@ {"t":"x","k":2,"f":0,"o":172,"p":0,"anchor":[12,6,6]} {"t":"x","k":2,"f":0,"o":176,"p":0,"anchor":[8,3,3]} {"t":"x","k":4,"f":1,"o":53,"p":0,"anchor":[0,4,4]} -{"t":"x","k":0,"f":2,"o":5,"p":0,"isRead":false,"isWrite":true,"anchor":[0,11,11]} -{"t":"x","k":0,"f":2,"o":7,"p":0,"isRead":false,"isWrite":true,"anchor":[0,12,12]} +{"t":"x","k":0,"f":2,"o":5,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[0,11,11]} +{"t":"x","k":0,"f":2,"o":7,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[0,12,12]} {"t":"x","k":5,"f":2,"o":68,"p":0,"anchor":[0,12,12]} {"t":"x","k":6,"f":3,"o":164,"p":0,"anchor":[0,10,10]} -{"t":"x","k":0,"f":4,"o":7,"p":0,"isRead":true,"isWrite":false,"anchor":[0,21,21]} +{"t":"x","k":0,"f":4,"o":7,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[0,21,21]} {"t":"x","k":6,"f":4,"o":60,"p":0,"anchor":[0,20,20]} {"t":"x","k":1,"f":4,"o":161,"p":0,"anchor":[0,19,19]} {"t":"x","k":6,"f":5,"o":164,"p":0,"anchor":[0,8,8]} -{"t":"x","k":0,"f":6,"o":5,"p":0,"isRead":true,"isWrite":false,"anchor":[0,16,16]} +{"t":"x","k":0,"f":6,"o":5,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[0,16,16]} {"t":"x","k":6,"f":6,"o":164,"p":0,"anchor":[0,15,15]} {"t":"x","k":6,"f":7,"o":60,"p":0,"anchor":[0,6,6]} {"t":"x","k":1,"f":8,"o":168,"p":0,"arguments":[{"name":"value","value":{"k":"enum","type":169,"name":"RUNTIME"}}],"anchor":[1,7,7]} {"t":"x","k":6,"f":8,"o":169,"p":0,"member":"RUNTIME","anchor":[1,7,7]} {"t":"x","k":6,"f":9,"o":164,"p":0,"anchor":[1,10,10]} -{"t":"x","k":0,"f":15,"o":14,"p":0,"isRead":true,"isWrite":true,"anchor":[2,54,54]} +{"t":"x","k":0,"f":15,"o":14,"p":0,"isRead":true,"isWrite":true,"receiver":"self","anchor":[2,54,54]} {"t":"x","k":6,"f":15,"o":16,"p":0,"anchor":[2,53,53]} -{"t":"x","k":0,"f":15,"o":28,"p":0,"isRead":true,"isWrite":false,"anchor":[2,54,54]} +{"t":"x","k":0,"f":15,"o":28,"p":0,"isRead":true,"isWrite":false,"receiver":"other","anchor":[2,54,54]} {"t":"x","k":5,"f":15,"o":175,"p":0,"member":"get","anchor":[2,54,54]} -{"t":"x","k":0,"f":17,"o":23,"p":0,"isRead":false,"isWrite":true,"anchor":[2,32,32]} -{"t":"x","k":0,"f":24,"o":23,"p":0,"isRead":true,"isWrite":false,"anchor":[2,36,36]} +{"t":"x","k":0,"f":17,"o":23,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[2,32,32]} +{"t":"x","k":0,"f":24,"o":23,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[2,36,36]} {"t":"x","k":5,"f":25,"o":24,"p":0,"anchor":[2,15,15]} -{"t":"x","k":0,"f":25,"o":28,"p":0,"isRead":true,"isWrite":false,"anchor":[2,14,14]} -{"t":"x","k":0,"f":25,"o":29,"p":0,"isRead":true,"isWrite":true,"anchor":[2,15,15]} +{"t":"x","k":0,"f":25,"o":28,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[2,14,14]} +{"t":"x","k":0,"f":25,"o":29,"p":0,"isRead":true,"isWrite":true,"receiver":"self","anchor":[2,15,15]} {"t":"x","k":5,"f":25,"o":175,"p":0,"member":"add","anchor":[2,14,14]} {"t":"x","k":6,"f":26,"o":16,"p":0,"anchor":[2,13,13]} {"t":"x","k":6,"f":27,"o":12,"p":0,"anchor":[2,22,22]} @@ -235,25 +235,25 @@ {"t":"x","k":6,"f":28,"o":16,"p":0,"anchor":[2,11,11]} {"t":"x","k":6,"f":28,"o":173,"p":0,"anchor":[2,11,11]} {"t":"x","k":6,"f":28,"o":175,"p":0,"anchor":[2,11,11]} -{"t":"x","k":0,"f":30,"o":29,"p":0,"isRead":true,"isWrite":false,"anchor":[2,19,19]} +{"t":"x","k":0,"f":30,"o":29,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[2,19,19]} {"t":"x","k":6,"f":32,"o":115,"p":0,"anchor":[3,48,60]} -{"t":"x","k":0,"f":34,"o":35,"p":0,"isRead":true,"isWrite":false,"anchor":[3,54,54]} +{"t":"x","k":0,"f":34,"o":35,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[3,54,54]} {"t":"x","k":5,"f":34,"o":36,"p":0,"anchor":[3,54,54]} {"t":"x","k":6,"f":34,"o":60,"p":0,"anchor":[3,53,53]} {"t":"x","k":1,"f":34,"o":161,"p":0,"anchor":[3,52,52]} {"t":"x","k":6,"f":35,"o":60,"p":0,"anchor":[3,50,50]} {"t":"x","k":6,"f":36,"o":60,"p":0,"anchor":[3,57,57]} {"t":"x","k":6,"f":37,"o":60,"p":0,"anchor":[3,57,57]} -{"t":"x","k":0,"f":38,"o":42,"p":0,"isRead":false,"isWrite":true,"anchor":[3,27,27]} -{"t":"x","k":0,"f":38,"o":44,"p":0,"isRead":false,"isWrite":true,"anchor":[3,28,28]} +{"t":"x","k":0,"f":38,"o":42,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[3,27,27]} +{"t":"x","k":0,"f":38,"o":44,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[3,28,28]} {"t":"x","k":6,"f":40,"o":60,"p":0,"anchor":[3,26,26]} {"t":"x","k":6,"f":41,"o":178,"p":0,"anchor":[3,42,42]} -{"t":"x","k":0,"f":43,"o":44,"p":0,"isRead":true,"isWrite":false,"anchor":[3,38,38]} +{"t":"x","k":0,"f":43,"o":44,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[3,38,38]} {"t":"x","k":6,"f":44,"o":60,"p":0,"anchor":[3,24,24]} {"t":"x","k":5,"f":45,"o":32,"p":0,"anchor":[3,48,60]} {"t":"x","k":5,"f":45,"o":68,"p":0,"anchor":[3,50,50]} {"t":"x","k":6,"f":45,"o":115,"p":0,"anchor":[3,47,47]} -{"t":"x","k":0,"f":46,"o":42,"p":0,"isRead":true,"isWrite":false,"anchor":[3,33,33]} +{"t":"x","k":0,"f":46,"o":42,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[3,33,33]} {"t":"x","k":4,"f":47,"o":115,"p":0,"anchor":[4,4,4]} {"t":"x","k":6,"f":52,"o":60,"p":0,"anchor":[4,10,10]} {"t":"x","k":5,"f":52,"o":68,"p":0,"anchor":[4,11,11]} @@ -268,7 +268,7 @@ {"t":"x","k":1,"f":65,"o":161,"p":0,"anchor":[7,14,14]} {"t":"x","k":6,"f":66,"o":60,"p":0,"anchor":[7,10,10]} {"t":"x","k":5,"f":66,"o":61,"p":0,"anchor":[7,11,11]} -{"t":"x","k":0,"f":66,"o":63,"p":0,"isRead":true,"isWrite":false,"anchor":[7,11,11]} +{"t":"x","k":0,"f":66,"o":63,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[7,11,11]} {"t":"x","k":6,"f":68,"o":60,"p":0,"anchor":[7,6,6]} {"t":"x","k":5,"f":68,"o":61,"p":0,"anchor":[7,7,7]} {"t":"x","k":5,"f":70,"o":6,"p":0,"anchor":[8,11,11]} @@ -297,7 +297,7 @@ {"t":"x","k":5,"f":86,"o":157,"p":0,"member":"println","anchor":[8,37,37]} {"t":"x","k":0,"f":86,"o":166,"p":0,"member":"out","isRead":true,"isWrite":false,"anchor":[8,37,37]} {"t":"x","k":6,"f":87,"o":164,"p":0,"anchor":[8,36,36]} -{"t":"x","k":0,"f":88,"o":90,"p":0,"isRead":true,"isWrite":false,"anchor":[8,33,33]} +{"t":"x","k":0,"f":88,"o":90,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[8,33,33]} {"t":"x","k":5,"f":88,"o":177,"p":0,"member":"accept","anchor":[8,33,33]} {"t":"x","k":6,"f":89,"o":91,"p":0,"anchor":[8,32,32]} {"t":"x","k":6,"f":90,"o":91,"p":0,"anchor":[8,8,8]} @@ -307,27 +307,27 @@ {"t":"x","k":5,"f":92,"o":94,"p":0,"anchor":[9,17,17]} {"t":"x","k":6,"f":93,"o":164,"p":0,"anchor":[9,16,16]} {"t":"x","k":5,"f":94,"o":2,"p":0,"anchor":[9,21,21]} -{"t":"x","k":0,"f":94,"o":98,"p":0,"isRead":false,"isWrite":true,"anchor":[9,22,22]} +{"t":"x","k":0,"f":94,"o":98,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[9,22,22]} {"t":"x","k":6,"f":95,"o":47,"p":0,"anchor":[9,20,20]} {"t":"x","k":6,"f":96,"o":164,"p":0,"anchor":[9,20,20]} {"t":"x","k":6,"f":98,"o":47,"p":0,"anchor":[9,14,14]} {"t":"x","k":6,"f":99,"o":47,"p":0,"anchor":[9,25,25]} -{"t":"x","k":0,"f":99,"o":98,"p":0,"isRead":true,"isWrite":false,"anchor":[9,26,26]} -{"t":"x","k":0,"f":100,"o":7,"p":0,"isRead":true,"isWrite":false,"anchor":[9,33,33]} +{"t":"x","k":0,"f":99,"o":98,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[9,26,26]} +{"t":"x","k":0,"f":100,"o":7,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[9,33,33]} {"t":"x","k":1,"f":100,"o":8,"p":0,"arguments":[{"name":"value","value":{"k":"unevaluated","source":"LedgerClient.AUDIT_TAG"}}],"anchor":[9,29,29]} {"t":"x","k":6,"f":100,"o":60,"p":0,"anchor":[9,31,31]} {"t":"x","k":5,"f":100,"o":66,"p":0,"anchor":[9,33,33]} {"t":"x","k":0,"f":100,"o":155,"p":0,"member":"AUDIT_TAG","isRead":true,"isWrite":false,"anchor":[9,29,29]} {"t":"x","k":1,"f":100,"o":161,"p":0,"anchor":[9,30,30]} {"t":"x","k":6,"f":102,"o":165,"p":0,"anchor":[9,12,12]} -{"t":"x","k":0,"f":104,"o":114,"p":0,"isRead":false,"isWrite":true,"anchor":[10,14,14]} +{"t":"x","k":0,"f":104,"o":114,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[10,14,14]} {"t":"x","k":6,"f":105,"o":155,"p":0,"anchor":[10,13,13]} -{"t":"x","k":0,"f":106,"o":114,"p":0,"isRead":true,"isWrite":false,"anchor":[10,30,30]} +{"t":"x","k":0,"f":106,"o":114,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[10,30,30]} {"t":"x","k":5,"f":106,"o":151,"p":0,"anchor":[10,30,30]} {"t":"x","k":5,"f":106,"o":155,"p":0,"member":"archive","anchor":[10,30,30]} {"t":"x","k":6,"f":107,"o":146,"p":0,"anchor":[10,29,29]} {"t":"x","k":5,"f":108,"o":6,"p":0,"anchor":[10,25,25]} -{"t":"x","k":0,"f":108,"o":114,"p":0,"isRead":true,"isWrite":false,"anchor":[10,25,25]} +{"t":"x","k":0,"f":108,"o":114,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[10,25,25]} {"t":"x","k":5,"f":108,"o":155,"p":0,"member":"archive","anchor":[10,25,25]} {"t":"x","k":6,"f":109,"o":91,"p":0,"anchor":[10,24,24]} {"t":"x","k":6,"f":110,"o":91,"p":0,"anchor":[10,23,23]} @@ -335,7 +335,7 @@ {"t":"x","k":5,"f":111,"o":6,"p":0,"anchor":[10,18,18]} {"t":"x","k":5,"f":111,"o":59,"p":0,"anchor":[10,18,18]} {"t":"x","k":6,"f":111,"o":59,"p":0,"anchor":[10,17,17]} -{"t":"x","k":0,"f":111,"o":114,"p":0,"isRead":true,"isWrite":false,"anchor":[10,19,19]} +{"t":"x","k":0,"f":111,"o":114,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[10,19,19]} {"t":"x","k":5,"f":111,"o":155,"p":0,"member":"post","anchor":[10,19,19]} {"t":"x","k":6,"f":112,"o":59,"p":0,"anchor":[10,18,18]} {"t":"x","k":6,"f":113,"o":91,"p":0,"anchor":[10,17,17]} @@ -370,18 +370,18 @@ {"t":"x","k":2,"f":138,"o":154,"p":1,"anchor":[14,3,3]} {"t":"x","k":3,"f":140,"o":155,"p":0,"anchor":[14,6,6]} {"t":"x","k":5,"f":142,"o":139,"p":0,"member":"record","anchor":[14,12,12]} -{"t":"x","k":0,"f":142,"o":144,"p":0,"isRead":true,"isWrite":false,"anchor":[14,12,12]} +{"t":"x","k":0,"f":142,"o":144,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[14,12,12]} {"t":"x","k":5,"f":142,"o":155,"p":1,"member":"post","anchor":[14,13,13]} {"t":"x","k":1,"f":142,"o":161,"p":0,"anchor":[14,10,10]} {"t":"x","k":6,"f":143,"o":160,"p":0,"anchor":[14,11,11]} {"t":"x","k":6,"f":144,"o":139,"p":0,"anchor":[14,8,8]} -{"t":"x","k":0,"f":147,"o":150,"p":0,"isRead":false,"isWrite":true,"anchor":[15,11,11]} -{"t":"x","k":0,"f":147,"o":153,"p":0,"isRead":false,"isWrite":true,"anchor":[15,12,12]} +{"t":"x","k":0,"f":147,"o":150,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[15,11,11]} +{"t":"x","k":0,"f":147,"o":153,"p":0,"isRead":false,"isWrite":true,"receiver":"self","anchor":[15,12,12]} {"t":"x","k":6,"f":148,"o":164,"p":0,"anchor":[15,10,10]} {"t":"x","k":6,"f":149,"o":146,"p":0,"anchor":[15,10,10]} {"t":"x","k":6,"f":150,"o":164,"p":0,"anchor":[15,6,6]} -{"t":"x","k":0,"f":151,"o":150,"p":0,"isRead":true,"isWrite":false,"anchor":[15,16,16]} +{"t":"x","k":0,"f":151,"o":150,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[15,16,16]} {"t":"x","k":6,"f":151,"o":164,"p":0,"anchor":[15,15,15]} -{"t":"x","k":0,"f":152,"o":153,"p":0,"isRead":true,"isWrite":false,"anchor":[15,20,20]} +{"t":"x","k":0,"f":152,"o":153,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[15,20,20]} {"t":"x","k":6,"f":153,"o":146,"p":0,"anchor":[15,8,8]} {"t":"eof","counts":{"files":16,"entities":179,"edges":190}} diff --git a/fixtures/java/src/com/acme/order/OrderService.java b/fixtures/java/src/com/acme/order/OrderService.java index a07a8f95..8f173474 100644 --- a/fixtures/java/src/com/acme/order/OrderService.java +++ b/fixtures/java/src/com/acme/order/OrderService.java @@ -20,7 +20,7 @@ public Invoice bill(Order order) { return invoice; } - public void archive(java.util.List orders) { + public void archive(java.util.List orders) { for (Order order : orders) { ledger.archive(order.reference()); } diff --git a/packages/analyzer/src/conformance.ts b/packages/analyzer/src/conformance.ts index 2fdd57e7..cb3cb52d 100644 --- a/packages/analyzer/src/conformance.ts +++ b/packages/analyzer/src/conformance.ts @@ -4,6 +4,7 @@ import { getProfile, isStubEntity, memberViolations, + receiverViolations, selfReferences, unknownReferences, validateModel, @@ -58,6 +59,7 @@ export const CONFORMANCE_RULES = [ "anchor", "duplicate-id", "member", + "receiver", ] as const; export type ConformanceRule = (typeof CONFORMANCE_RULES)[number]; @@ -77,6 +79,8 @@ export const CONFORMANCE_CODES = [ "unknown-profile", "member-kind", "member-target-not-stub", + "receiver-kind", + "receiver-target-stub", ] as const; export type ConformanceCode = (typeof CONFORMANCE_CODES)[number] | ValidationCode; @@ -292,6 +296,22 @@ export function checkConformance(union: ModelUnion, options: ConformanceOptions ); } + // ---- RECEIVER (MM-8): an access, to a member that is not a stub's --------- + for (const violation of receiverViolations(model)) { + const { edge, path } = violation; + const kind = violation.reason === "kind"; + at( + "error", + "receiver", + kind ? "receiver-kind" : "receiver-target-stub", + `${path}.receiver`, + edge.from, + kind + ? `${path}: a ${edge.edge} edge states receiver "${String(edge.receiver)}"; only access edges may` + : `${path}: states receiver "${String(edge.receiver)}" on an access to "${edge.to}", which is a stub — a stub has no members, so nothing says the field needs an instance`, + ); + } + // ---- PROVENANCE, CANDIDATES, ANCHORS ------------------------------------ model.edges.forEach((edge, index) => { const path = `edges[${index}]`; diff --git a/packages/analyzer/src/store/helper-views.ts b/packages/analyzer/src/store/helper-views.ts index 01ca44bf..b9ac33c9 100644 --- a/packages/analyzer/src/store/helper-views.ts +++ b/packages/analyzer/src/store/helper-views.ts @@ -45,7 +45,8 @@ SELECT e.id AS ref, /** * One row per edge: its two ends by surrogate, its kind and provenance by name, - * its anchor, and the member of a stub it names (MM-6; NULL when none). + * its anchor, the member of a stub it names (MM-6; NULL when none), and how an + * access reached its target (MM-8: 'self' or 'other'; NULL when not said). */ export const DEP_VIEW_SQL = `CREATE TEMP VIEW dep AS SELECT x.id AS ref, @@ -55,7 +56,8 @@ SELECT x.id AS ref, p.name AS provenance, f.path AS file, x.anchor_start AS line, - x.member AS member + x.member AS member, + x.receiver AS receiver FROM edge x JOIN edge_kind ek ON ek.id = x.kind_id JOIN provenance p ON p.id = x.provenance_id diff --git a/packages/analyzer/src/store/import.ts b/packages/analyzer/src/store/import.ts index 0758cca8..0be285fd 100644 --- a/packages/analyzer/src/store/import.ts +++ b/packages/analyzer/src/store/import.ts @@ -162,8 +162,8 @@ export function writeModelRows(db: SqliteDatabase, jsonlPath: string): ImportRes entity: db.prepare( `INSERT INTO entity(id, kind_id, trait_set_id, module_id, symbol, disambiguator, name, signature, parent_id, attached_to_id, declared_type_id, - is_stub, anchor_file_id, anchor_start, anchor_end, space, value, extra) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + is_stub, anchor_file_id, anchor_start, anchor_end, space, value, type_expr, extra) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ), comment: db.prepare("INSERT INTO entity_comment(entity_id, ord, text) VALUES (?, ?, ?)"), definedIn: db.prepare("INSERT INTO entity_defined_in(entity_id, ord, file_id) VALUES (?, ?, ?)"), @@ -177,8 +177,8 @@ export function writeModelRows(db: SqliteDatabase, jsonlPath: string): ImportRes edge: db.prepare( `INSERT INTO edge(id, kind_id, from_id, to_id, provenance_id, anchor_file_id, anchor_start, anchor_end, arguments, - is_read, is_write, source_file_id, member, candidate_count, extra) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + is_read, is_write, source_file_id, member, receiver, candidate_count, extra) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ), candidate: db.prepare( "INSERT INTO edge_candidate(edge_id, ord, candidate_id) VALUES (?, ?, ?)", @@ -238,6 +238,7 @@ export function writeModelRows(db: SqliteDatabase, jsonlPath: string): ImportRes anchor[2], json(record.space), json(record.value), + json(record.typeExpr), extraOf(record, TYPED_ENTITY_KEYS), ); record.comments?.forEach((text, ord) => insert.comment.run(record.i, ord, text)); @@ -272,6 +273,7 @@ export function writeModelRows(db: SqliteDatabase, jsonlPath: string): ImportRes bool(record.isWrite), record.sourceFile ?? null, record.member ?? null, + record.receiver ?? null, record.candidates === undefined ? null : record.candidates.length, extraOf(record, TYPED_EDGE_KEYS), ); @@ -499,11 +501,11 @@ const EMPTY_TRAIT_SET: TraitSetInfo = { ids: [], names: new Set() }; const ENTITY_COLUMNS = "id, kind_id, trait_set_id, module_id, symbol, disambiguator, name, signature, " + "parent_id, attached_to_id, declared_type_id, is_stub, " + - "anchor_file_id, anchor_start, anchor_end, space, value, extra"; + "anchor_file_id, anchor_start, anchor_end, space, value, type_expr, extra"; const EDGE_COLUMNS = "id, kind_id, from_id, to_id, provenance_id, anchor_file_id, anchor_start, anchor_end, " + - "arguments, is_read, is_write, source_file_id, member, candidate_count, extra"; + "arguments, is_read, is_write, source_file_id, member, receiver, candidate_count, extra"; /** NULL means the key was absent; anything else is a value the wire carried. */ function put(record: Record, key: string, value: unknown): void { @@ -521,10 +523,10 @@ function entityRecordOf( ): EntityRec { const [id, kindId, , moduleId, symbol, disambiguator, name, signature, parentId, attachedToId, declaredTypeId, isStub, - anchorFile, anchorStart, anchorEnd, space, value, extra] = row as [ + anchorFile, anchorStart, anchorEnd, space, value, typeExpr, extra] = row as [ number, number, number, number, string, string | null, string | null, string | null, number | null, number | null, number | null, number | null, - number | null, number | null, number | null, string | null, string | null, string | null, + number | null, number | null, number | null, string | null, string | null, string | null, string | null, ]; const record: Record = { @@ -554,15 +556,16 @@ function entityRecordOf( if (space !== null) record["space"] = JSON.parse(space) as unknown; if (value !== null) record["value"] = JSON.parse(value) as unknown; + if (typeExpr !== null) record["typeExpr"] = JSON.parse(typeExpr) as unknown; if (extra !== null) Object.assign(record, JSON.parse(extra) as object); return record as unknown as EntityRec; } function edgeRecordOf(row: SqliteValue[], candidates: Map): EdgeRec { const [id, kindId, fromId, toId, provenanceId, anchorFile, anchorStart, anchorEnd, - args, isRead, isWrite, sourceFileId, member, candidateCount, extra] = row as [ + args, isRead, isWrite, sourceFileId, member, receiver, candidateCount, extra] = row as [ number, number, number, number, number, number, number, number, - string | null, number | null, number | null, number | null, string | null, number | null, string | null, + string | null, number | null, number | null, number | null, string | null, string | null, number | null, string | null, ]; const record: Record = { @@ -580,6 +583,7 @@ function edgeRecordOf(row: SqliteValue[], candidates: Map): E if (args !== null) record["arguments"] = JSON.parse(args) as unknown; if (isRead !== null) record["isRead"] = isRead === 1; if (isWrite !== null) record["isWrite"] = isWrite === 1; + put(record, "receiver", receiver); put(record, "sourceFile", sourceFileId); if (extra !== null) Object.assign(record, JSON.parse(extra) as object); return record as unknown as EdgeRec; diff --git a/packages/analyzer/src/store/schema.ts b/packages/analyzer/src/store/schema.ts index 8b343b19..c441bc40 100644 --- a/packages/analyzer/src/store/schema.ts +++ b/packages/analyzer/src/store/schema.ts @@ -98,7 +98,7 @@ export const STORE_OPEN_OPTIONS: SqliteOpenOptions = { enableForeignKeyConstrain * (A store that holds revisions is the one exception: the cache refuses to * touch it, because K snapshots cost K extractions — see `cache.ts`.) */ -export const DB_VERSION = 5; +export const DB_VERSION = 6; /** * `meta` keys the importer writes. Values are TEXT; anything structured is @@ -167,6 +167,8 @@ export const ENTITY_KEY_STORAGE = { // shredded into rows: nothing queries INSIDE a value, and the ids it holds // are the wire's own surrogates, so the blob round-trips exactly. value: { table: "entity", columns: ["value"] }, + // MM-7: a TypeExpr is a tree too, kept whole for the same reasons. + typeExpr: { table: "entity", columns: ["type_expr"] }, } as const satisfies KeyStorage; /** The same, for edge records. */ @@ -182,6 +184,8 @@ export const EDGE_KEY_STORAGE = { sourceFile: { table: "edge", columns: ["source_file_id"] }, // MM-6: the member a stub target is reached by, as written. NULL = none named. member: { table: "edge", columns: ["member"] }, + // MM-8: how an access reached its target, `self` or `other`. NULL = not said. + receiver: { table: "edge", columns: ["receiver"] }, // The same, for an annotation use's arguments: absent column = absent key, // which on the wire means the empty list the edge kind implies. arguments: { table: "edge", columns: ["arguments"] }, @@ -249,6 +253,7 @@ CREATE TABLE entity ( anchor_end INTEGER, space TEXT, value TEXT, -- JSON Literal (§1.6), surrogates inside + type_expr TEXT, -- JSON TypeExpr (MM-7), surrogates inside extra TEXT ); @@ -306,6 +311,7 @@ CREATE TABLE edge ( is_write INTEGER, source_file_id INTEGER REFERENCES file, member TEXT, -- MM-6: the stub's member, as written + receiver TEXT, -- MM-8: 'self' | 'other', access only -- NULL = the key was absent; N = present with N rows in edge_candidate. -- Unlike the entity lists, candidates is contributed by no trait, so nothing -- else could tell an EMPTY array from an absent one. diff --git a/packages/analyzer/test/conformance-properties.test.ts b/packages/analyzer/test/conformance-properties.test.ts index 9ead9dcc..1759d415 100644 --- a/packages/analyzer/test/conformance-properties.test.ts +++ b/packages/analyzer/test/conformance-properties.test.ts @@ -135,8 +135,9 @@ function traitKeys(trait: TraitName, ctx: TraitContext): Record return { definedIn: ctx.isStub ? [] : [`E${ctx.index}.src`], isStub: ctx.isStub }; case "TType": return { isStub: ctx.isStub }; + // The written type is a tree with an id inside (MM-7): closure reaches it too. case "TTypedEntity": - return { declaredType: ctx.rootId }; + return { declaredType: ctx.rootId, typeExpr: { k: "array", of: { k: "named", type: ctx.rootId } } }; case "TInvocable": return { signature: `E${ctx.index}()` }; case "TWithParameters": @@ -157,6 +158,7 @@ function traitKeys(trait: TraitName, ctx: TraitContext): Record case "TWithInvocations": case "TStructural": case "TWithAccesses": + case "TWithReceiver": return {}; } } diff --git a/packages/analyzer/test/member.test.ts b/packages/analyzer/test/member.test.ts index 39c301cf..03eebb4e 100644 --- a/packages/analyzer/test/member.test.ts +++ b/packages/analyzer/test/member.test.ts @@ -62,8 +62,9 @@ describe("loading", () => { describe("model.db", () => { const dbPath = importModel(namedPath, join(scratch, "named.db")).path; - it("bumps the store version, so an older cache is regenerated", () => { - expect(DB_VERSION).toBe(5); + // 5 added `edge.member`; any later version keeps it (6: MM-7, MM-8). + it("bumps the store version past the one without it, so an older cache is regenerated", () => { + expect(DB_VERSION).toBeGreaterThanOrEqual(5); }); it("holds the member in `edge.member`, not in `extra`", () => { diff --git a/packages/analyzer/test/store-schema.test.ts b/packages/analyzer/test/store-schema.test.ts index 1ae79450..383899a8 100644 --- a/packages/analyzer/test/store-schema.test.ts +++ b/packages/analyzer/test/store-schema.test.ts @@ -81,7 +81,7 @@ function digest(db: SqliteDatabase): string { * diff — which is the entire point. Bump `DB_VERSION` alongside any change: * migration is regeneration, so an old cache must be recognised as old. */ -const EXPECTED = `edge(id INTEGER PK1, kind_id INTEGER NOT NULL, from_id INTEGER NOT NULL, to_id INTEGER NOT NULL, provenance_id INTEGER NOT NULL, anchor_file_id INTEGER NOT NULL, anchor_start INTEGER NOT NULL, anchor_end INTEGER NOT NULL, arguments TEXT, is_read INTEGER, is_write INTEGER, source_file_id INTEGER, member TEXT, candidate_count INTEGER, extra TEXT) +const EXPECTED = `edge(id INTEGER PK1, kind_id INTEGER NOT NULL, from_id INTEGER NOT NULL, to_id INTEGER NOT NULL, provenance_id INTEGER NOT NULL, anchor_file_id INTEGER NOT NULL, anchor_start INTEGER NOT NULL, anchor_end INTEGER NOT NULL, arguments TEXT, is_read INTEGER, is_write INTEGER, source_file_id INTEGER, member TEXT, receiver TEXT, candidate_count INTEGER, extra TEXT) index edge_from (from_id, kind_id) index edge_provenance (provenance_id) index edge_to (to_id, kind_id) @@ -93,7 +93,7 @@ edge_kind(id INTEGER PK1, name TEXT NOT NULL) edge_version(revision_id INTEGER NOT NULL PK1, from_key INTEGER NOT NULL PK2, to_key INTEGER NOT NULL PK3, kind TEXT NOT NULL PK4, provenance TEXT NOT NULL PK5, count INTEGER NOT NULL) WITHOUT ROWID index edge_version_keys (from_key, to_key) unique index (revision_id, from_key, to_key, kind, provenance) -entity(id INTEGER PK1, kind_id INTEGER NOT NULL, trait_set_id INTEGER NOT NULL, module_id INTEGER NOT NULL, symbol TEXT NOT NULL, disambiguator TEXT, name TEXT, signature TEXT, parent_id INTEGER, attached_to_id INTEGER, declared_type_id INTEGER, is_stub INTEGER, anchor_file_id INTEGER, anchor_start INTEGER, anchor_end INTEGER, space TEXT, value TEXT, extra TEXT) +entity(id INTEGER PK1, kind_id INTEGER NOT NULL, trait_set_id INTEGER NOT NULL, module_id INTEGER NOT NULL, symbol TEXT NOT NULL, disambiguator TEXT, name TEXT, signature TEXT, parent_id INTEGER, attached_to_id INTEGER, declared_type_id INTEGER, is_stub INTEGER, anchor_file_id INTEGER, anchor_start INTEGER, anchor_end INTEGER, space TEXT, value TEXT, type_expr TEXT, extra TEXT) index entity_anchor_file (anchor_file_id) index entity_kind (kind_id) index entity_natural_key (module_id, symbol, disambiguator) diff --git a/packages/analyzer/test/type-expr-receiver.test.ts b/packages/analyzer/test/type-expr-receiver.test.ts new file mode 100644 index 00000000..bb776ab7 --- /dev/null +++ b/packages/analyzer/test/type-expr-receiver.test.ts @@ -0,0 +1,208 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterAll, describe, expect, it } from "vitest"; +import { + encodeModelToString, + readModelFileSync, + readModelRecordsSync, + type Edge, + type Entity, + type Model, + type TypeExpr, +} from "@codegraph/core"; + +import { checkConformance } from "../src/conformance.js"; +import { loadDecodedModels, loadModels } from "../src/load.js"; +import { createHelperViews } from "../src/store/helper-views.js"; +import { hydrateModel, importModel, openStore, readStoreRecords } from "../src/store/import.js"; +import { DB_VERSION } from "../src/store/schema.js"; + +/** + * MM-7 and MM-8 through the analyzer: a typed entity's `typeExpr`, the marker + * `TWithReceiver` and an access's `receiver` survive the loaded union, the + * `model.db` cache and its `dep` view, and the conformance gate checks them. + */ + +const fixture = fileURLToPath(new URL("../../../fixtures/java/expected/model.jsonl", import.meta.url)); +const scratch = mkdtempSync(join(tmpdir(), "codegraph-mm78-")); +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +const committed = readModelFileSync(fixture); +const bag = (entity: Entity): Record => entity as unknown as Record; + +/** + * The committed fixture with MM-7/MM-8 taken out: the Java extractor writes + * them since M25b, and the tests below add ONE of each by hand so that every + * count they state is the one they planted. + */ +const original: Model = { + ...committed, + entities: committed.entities.map((entity) => { + const { typeExpr: _written, ...rest } = bag(entity); + return { ...rest, traits: entity.traits.filter((t) => t !== "TWithReceiver") } as unknown as Entity; + }), + edges: committed.edges.map((edge) => { + const { receiver: _through, ...rest } = edge as Edge & { receiver?: string }; + return rest as Edge; + }), +}; +const isStub = new Set(original.entities.filter((e) => bag(e)["isStub"] === true).map((e) => e.id)); + +/** The first attribute whose declared type is a stub: it gets `List<…>`-shaped written type. */ +const typedAt = original.entities.findIndex((e) => e.kind === "attribute" && typeof bag(e)["declaredType"] === "string"); +const typed = original.entities[typedAt]!; +const head = bag(typed)["declaredType"] as string; +const WRITTEN: TypeExpr = { k: "named", type: head, args: [{ k: "array", of: { k: "primitive", name: "int" } }, { k: "variable", name: "T" }] }; + +/** The first access to a corpus field: stated through `self`, and once more through `other`. */ +const site = original.edges.findIndex((e) => e.edge === "access" && !isStub.has(e.to)); + +const extended: Model = { + ...original, + schemaVersion: "1.2.0", + entities: original.entities.map((entity, index) => + index === typedAt ? ({ ...entity, traits: [...entity.traits, "TWithReceiver"], typeExpr: WRITTEN } as Entity) : entity, + ), + edges: original.edges.flatMap((edge, index) => + index === site ? [{ ...edge, receiver: "self" } as Edge, { ...edge, receiver: "other" } as Edge] : [edge], + ), +}; +const extendedPath = join(scratch, "extended.jsonl"); +writeFileSync(extendedPath, encodeModelToString(extended), "utf8"); + +describe("loading", () => { + it("keeps the type expression, the marker and the receiver on both entry points", () => { + for (const union of [loadModels(extended).union, loadDecodedModels([readModelFileSync(extendedPath)]).union]) { + const entity = bag(union.entities.find((e) => e.id === typed.id)!); + expect(entity["typeExpr"]).toEqual(WRITTEN); + expect(entity["traits"]).toContain("TWithReceiver"); + expect(union.edges.filter((e) => e.receiver !== undefined).map((e) => e.receiver).sort()).toEqual(["other", "self"]); + } + }); +}); + +describe("the committed Java fixture (M25b)", () => { + const written = committed.entities.filter((e) => bag(e)["typeExpr"] !== undefined).length; + const stated = committed.edges.filter((e) => e.receiver !== undefined).length; + + it("carries the extractor's facts, and the load keeps every one", () => { + expect(written).toBeGreaterThan(0); + expect(stated).toBeGreaterThan(0); + const union = loadDecodedModels([committed]).union; + expect(union.entities.filter((e) => bag(e)["typeExpr"] !== undefined)).toHaveLength(written); + expect(union.edges.filter((e) => e.receiver !== undefined)).toHaveLength(stated); + expect(checkConformance(union).ok).toBe(true); + }); + + it("lands in model.db, one type_expr per carrier and one receiver per stating access", () => { + const db = openStore(importModel(fixture, join(scratch, "committed.db")).path); + try { + createHelperViews(db); + expect(db.prepare("SELECT count(*) AS n FROM entity WHERE type_expr IS NOT NULL").get()).toEqual({ n: written }); + expect(db.prepare("SELECT count(receiver) AS n FROM dep").get()).toEqual({ n: stated }); + } finally { + db.close(); + } + }); +}); + +describe("model.db", () => { + const dbPath = importModel(extendedPath, join(scratch, "extended.db")).path; + + it("bumps the store version, so an older cache is regenerated", () => { + expect(DB_VERSION).toBe(6); + }); + + it("holds the type expression in `entity.type_expr`, as JSON with surrogates inside", () => { + const db = openStore(dbPath); + try { + const rows = db.prepare("SELECT type_expr, extra FROM entity WHERE type_expr IS NOT NULL").all() as { type_expr: string; extra: string | null }[]; + expect(rows).toHaveLength(1); + const stored = JSON.parse(rows[0]!.type_expr) as { k: string; type: unknown; args: unknown[] }; + expect(stored.k).toBe("named"); + expect(typeof stored.type).toBe("number"); + expect(stored.args).toEqual([{ k: "array", of: { k: "primitive", name: "int" } }, { k: "variable", name: "T" }]); + expect(rows[0]!.extra).toBeNull(); + } finally { + db.close(); + } + }); + + it("holds the receiver in `edge.receiver`, not in `extra`", () => { + const db = openStore(dbPath); + try { + expect(db.prepare("SELECT receiver, extra FROM edge WHERE receiver IS NOT NULL ORDER BY id").all()).toEqual([ + { receiver: "other", extra: null }, + { receiver: "self", extra: null }, + ]); + } finally { + db.close(); + } + }); + + it("hands back the identical record stream and model", () => { + const db = openStore(dbPath); + try { + expect([...readStoreRecords(db)]).toEqual([...readModelRecordsSync(extendedPath)]); + expect(hydrateModel(db)).toEqual(readModelFileSync(extendedPath)); + } finally { + db.close(); + } + }); + + it("exposes the receiver on the `dep` view, NULL where none is stated", () => { + const db = openStore(dbPath); + try { + createHelperViews(db); + const counts = db.prepare("SELECT count(*) AS edges, count(receiver) AS stated FROM dep").get() as { edges: number; stated: number }; + expect(counts).toEqual({ edges: extended.edges.length, stated: 2 }); + expect(db.prepare("SELECT kind, receiver FROM dep WHERE receiver = 'self'").all()).toEqual([{ kind: "access", receiver: "self" }]); + } finally { + db.close(); + } + }); +}); + +describe("conformance", () => { + it("accepts the three on a profile-valid model", () => { + const report = checkConformance(loadModels(extended).union); + expect(report.findings).toEqual([]); + expect(report.ok).toBe(true); + }); + + it("reports a dangling id inside a type expression as closure, at its path", () => { + const dangling = "java:com.acme.order/Nowhere"; + const bad: Model = { + ...extended, + entities: extended.entities.map((e) => (e.id === typed.id ? ({ ...e, typeExpr: { k: "array", of: { k: "named", type: dangling } } } as Entity) : e)), + }; + const at = bad.entities.findIndex((e) => e.id === typed.id); + const report = checkConformance(loadModels(bad).union); + expect(report.findings.map((f) => [f.rule, f.code, f.path, f.id])).toEqual([ + ["closure", "dangling-reference", `entities[${at}].typeExpr.of.type`, dangling], + ]); + }); + + it("is an error to state a receiver on an access to a stub", () => { + const toStub = original.edges.findIndex((e) => e.edge === "access" && isStub.has(e.to)); + expect(toStub).toBeGreaterThanOrEqual(0); + const bad: Model = { ...original, edges: original.edges.map((e, i) => (i === toStub ? ({ ...e, receiver: "other" } as Edge) : e)) }; + const report = checkConformance(loadModels(bad).union); + expect(report.ok).toBe(false); + expect(report.findings.map((f) => [f.rule, f.code, f.path])).toEqual([["receiver", "receiver-target-stub", `edges[${toStub}].receiver`]]); + }); + + it("is an error to state one on a kind that cannot carry it, read off the wire", () => { + const at = original.edges.findIndex((e) => e.edge === "import"); + const lines = encodeModelToString(original).split("\n"); + const edgeLines = lines.map((line, i) => [line, i] as const).filter(([line]) => line.startsWith('{"t":"x"')); + const [line, i] = edgeLines[at]!; + lines[i] = line.replace(/,"anchor":/, ',"receiver":"self","anchor":'); + const path = join(scratch, "bad-kind.jsonl"); + writeFileSync(path, lines.join("\n"), "utf8"); + const report = checkConformance(loadDecodedModels([readModelFileSync(path)]).union); + expect(report.findings.map((f) => [f.rule, f.code])).toEqual([["receiver", "receiver-kind"]]); + }); +}); diff --git a/packages/cli/package.json b/packages/cli/package.json index 19347b8c..55908ab7 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -19,6 +19,7 @@ "@codegraph/analyzer": "workspace:*", "@codegraph/city": "workspace:*", "@codegraph/core": "workspace:*", + "@codegraph/dataop": "workspace:*", "@codegraph/insights": "workspace:*", "@codegraph/llm": "workspace:*", "@codegraph/navigator": "workspace:*", diff --git a/packages/cli/src/args.ts b/packages/cli/src/args.ts index aec1c3f2..2e1f0017 100644 --- a/packages/cli/src/args.ts +++ b/packages/cli/src/args.ts @@ -16,6 +16,7 @@ import { import { CLOSURES, DIRECTIONS, EXPLAIN_WALK_NAME, LAYERINGS, ROOTS_KEYWORDS, WALK_NAME_PATTERN, type Closure, type Direction, type Layering, type RootsSpec } from "@codegraph/insights"; import { METRIC_PREFIXES, SCALES, metricNames } from "@codegraph/city"; import { SCOPE_LEVELS, TERM_CLASSES, WEIGHT_KEYS, type ScopeLevel, type TermClass, type WeightKey } from "@codegraph/vocabulary"; +import { isModelName } from "@codegraph/dataop"; import { defaultDataDir } from "./app/store.js"; import { UsageError } from "./exit.js"; @@ -43,6 +44,7 @@ export const COMMAND_NAMES = [ "vocabulary", "serve", "domain-facts", + "dataop", "explain", "walk", "insights", @@ -638,6 +640,53 @@ export const DOMAIN_FACTS_SPEC: CommandSpec = { ], }; +/** + * `codegraph dataop`: the model lowered into a Specy Data & Operation model + * (`.dataop`, `observed` level — PLAN.md §26.5). The transform lives in + * `@codegraph/dataop`; this command resolves the boundaries file and the + * scope, and moves bytes. The summary of what was not lowered goes to stderr. + */ +export const DATAOP_SPEC: CommandSpec = { + name: "dataop", + summary: "Write the model as a Specy Data & Operation model (.dataop, observed): structs, globals, operations and their clauses.", + positional: MODELS_POSITIONAL_DEFAULTED, + options: [ + { + name: "out", + type: "string", + describe: "Write the .dataop text to this file instead of stdout.", + placeholder: "FILE", + }, + { + name: "name", + type: "string", + describe: + "The model's name: kebab-case words, each starting with a lowercase letter. " + + "Default: the last segment of the first model's root, made kebab-case (`model` when that gives none).", + placeholder: "NAME", + }, + { + name: "boundaries", + type: "string", + describe: + "A codegraph.boundaries/1 file (or an M23 stack table such as plugin/references/stacks/spring.json): " + + "an operation a rule finds at its declaration is written `entry`, one the inventory inferred `entry?`; an uncalled operation no rule names is not marked. Without it, no operation is.", + placeholder: "FILE", + }, + { + name: "scope", + type: "string", + multiple: true, + describe: + "Lower only the modules this selector term matches, or that hold an entity it matches: " + + "id:ID, kind:K, trait:T, lang:L, name:GLOB, module:GLOB, file:GLOB, edge:KIND[>TERM], edge-in:KIND[ termOf("scope", text)), + }, + }; + } case "explain": { checkSrc(values, models); if (flagOf(values, "retry-failed") && stringOf(values, "scope") !== undefined) { diff --git a/packages/cli/src/commands/dataop.ts b/packages/cli/src/commands/dataop.ts new file mode 100644 index 00000000..c96d5bc1 --- /dev/null +++ b/packages/cli/src/commands/dataop.ts @@ -0,0 +1,96 @@ +import { Buffer } from "node:buffer"; +import { applyBoundaries, buildGraph, compileSelector, type EntryLayer, type EntryRow, type Selector } from "@codegraph/analyzer"; +import { DataOpError, formatSummary, lower, print } from "@codegraph/dataop"; +import type { DataOpOptions } from "../args.js"; +import { EXIT, UsageError, type ExitCode } from "../exit.js"; +import { errLine, errLines, type IoSink } from "../io.js"; +import { loadModelFiles } from "../load.js"; +import { readBoundaries } from "./boundaries-reports.js"; +import { asUsageError } from "./walk-input.js"; + +/** Entry-inventory layers that INFER an entry rather than read a rule at the declaration: written `entry?`. */ +const INFERRED_LAYERS: ReadonlySet = new Set(["no caller", "concept"]); + +/** + * The inventory's residue: uncalled, and named by no rule. "No operation of the model calls it" is a position + * in the dependency graph, which Specy says the mark does NOT mean (Entry point) — so it is not marked at all. + * A `no caller` row an `operations` rule names (`main`, `perform`) keeps its `entry?`. + */ +function isResidue(row: EntryRow): boolean { + return row.layer === "no caller" && row.stimulus === null; +} + +/** + * `codegraph dataop [--out FILE] [--name NAME] + * [--boundaries FILE] [--scope SEL]...` (PLAN.md §26.5). + * + * Writes the model lowered into a Specy Data & Operation model (`.dataop`, at + * the `observed` level) on stdout, or to `--out FILE`. The lowering lives in + * `@codegraph/dataop`; this command reads the boundaries file and the scope, + * and moves bytes (decision 7). + * + * It reads the `.jsonl` itself, never a store: the lowering reads each model's + * contract version from its header, which says whether `TWithReceiver` is a fact. + * + * STREAM PURITY (decision 3): stdout carries the `.dataop` text and nothing + * else; the summary of what was and was not lowered goes to stderr. + */ +export function dataopCommand(options: DataOpOptions, io: IoSink): ExitCode { + // A faulty boundaries file is refused before any model is read. + const boundaries = options.boundaries === undefined ? undefined : readBoundaries(options.boundaries); + const loaded = loadModelFiles(options.models); + const graph = buildGraph(loaded.union); + const result = boundaries === undefined ? undefined : applyBoundaries(graph, boundaries); + + let scope: { matches(id: string): boolean } | undefined; + if (options.scope.length > 0) { + const selector: Selector = options.scope.length === 1 ? (options.scope[0] as Selector) : { type: "any", of: options.scope }; + try { + scope = compileSelector(selector, graph, undefined, result === undefined ? {} : { boundaries: result }); + } catch (error) { + throw asUsageError(error, "--scope"); + } + } + + const marked = result?.entries.filter((row) => !isResidue(row)); + const residue = result === undefined ? 0 : result.entries.length - (marked?.length ?? 0); + + let text: string; + let summary: readonly string[]; + try { + const model = lower(graph, { + name: options.name, + // A rule at the declaration is a fact; a `no caller` row a rule names and a `concept` (a model's label) are inferences. + entries: marked?.filter((row) => !INFERRED_LAYERS.has(row.layer)).map((row) => row.entry), + candidateEntries: marked?.filter((row) => INFERRED_LAYERS.has(row.layer)).map((row) => row.entry), + scope, + }); + text = print(model); + summary = formatSummary(model.summary); + } catch (error) { + if (error instanceof DataOpError) { + throw new UsageError(error.message, "codegraph dataop --help names the flags; --scope selects the modules lowered.", { cause: error }); + } + throw error; + } + + if (!loaded.clean) { + errLines(io, [ + "warning: the models are not clean; the Data & Operation model was lowered anyway.", + `Run 'codegraph validate ${loaded.paths.join(" ")}' for the detail.`, + ]); + } + if (boundaries !== undefined && result !== undefined) { + const rows = `${result.entries.length} entry row${result.entries.length === 1 ? "" : "s"}`; + errLine(io, `boundaries: ${options.boundaries ?? ""} — ${rows}${residue === 0 ? "" : `, ${residue} uncalled and named by no rule (not marked)`}.`); + } + errLines(io, summary); + + if (options.out !== undefined) { + io.writeFile(options.out, text); + errLine(io, `wrote ${Buffer.byteLength(text, "utf8")} bytes to ${options.out}.`); + } else { + io.out(text); + } + return loaded.clean ? EXIT.OK : EXIT.FINDINGS; +} diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index 8f792177..ae86e46e 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -6,6 +6,7 @@ import { historyCommand } from "./commands/history.js"; import { importCommand } from "./commands/import.js"; import { insightsCommand } from "./commands/insights.js"; import { domainFactsCommand } from "./commands/domain-facts.js"; +import { dataopCommand } from "./commands/dataop.js"; import { navigatorCommand } from "./commands/navigator.js"; import { scmCommand } from "./commands/scm.js"; import { serveCommand } from "./commands/serve.js"; @@ -112,6 +113,8 @@ function dispatch(invocation: Invocation, io: IoSink): ExitCode | Promise rmSync(scratch, { recursive: true, force: true })); + +function dataop(args: readonly string[]): { code: number; stdout: string; stderr: string; files: ReadonlyMap } { + const io = captureIo(); + const code = runSync(["dataop", ...args], io); + return { code, stdout: io.stdout(), stderr: io.stderr(), files: io.files() }; +} + +describe("dataop: the artifact", () => { + it("writes the .dataop text on stdout and the summary on stderr", () => { + const { code, stdout, stderr } = dataop([JAVA]); + expect(code).toBe(EXIT.OK); + expect(stdout).toMatch(/^\/\/ A Data & Operation model lowered by codegraph/u); + expect(stdout).toContain("\nmodel src observed {\n"); + expect(stdout).toContain(" module com.acme.order {\n"); + expect(stdout.endsWith("}\n")).toBe(true); + expect(stdout).not.toMatch(/^lowered: /mu); + expect(stderr).toMatch(/^lowered: \d+ modules?, \d+ structs?/mu); + expect(stderr).toMatch(/^edges \(invocation, access, throws\): \d+ declared, \d+ not declared\.$/mu); + expect(stderr).not.toContain("model src observed"); + }); + + it("is byte-identical across runs", () => { + expect(dataop([JAVA]).stdout).toBe(dataop([JAVA]).stdout); + }); + + it("lowers another language, stating its fallback in the header", () => { + const { code, stdout } = dataop([PYTHON]); + expect(code).toBe(EXIT.OK); + expect(stdout).toContain("// receivers (python, contract"); + expect(stdout).toContain("the profile licenses TWithReceiver on no kind"); + }); +}); + +describe("dataop: flags", () => { + it("--out writes the file and confirms on stderr, leaving stdout empty", () => { + const path = join(scratch, "model.dataop"); + const { code, stdout, stderr, files } = dataop([JAVA, "--out", path]); + expect(code).toBe(EXIT.OK); + expect(stdout).toBe(""); + expect(stderr).toContain(`bytes to ${path}`); + expect(files.get(path)).toBe(dataop([JAVA]).stdout); + }); + + it("--name names the model; a name the grammar refuses is a usage error", () => { + expect(dataop([JAVA, "--name", "order-service"]).stdout).toContain("\nmodel order-service observed {\n"); + const bad = dataop([JAVA, "--name", "Order Service"]); + expect(bad.code).toBe(EXIT.USAGE); + expect(bad.stdout).toBe(""); + expect(bad.stderr).toContain("not a model name"); + }); + + it("--scope lowers the modules it selects; what falls outside is external", () => { + const { code, stdout } = dataop([JAVA, "--scope", "module:com.acme.order.adapter"]); + expect(code).toBe(EXIT.OK); + expect(stdout).toContain(" module com.acme.order.adapter {\n"); + expect(stdout).not.toContain(" module com.acme.order {\n"); + }); + + it("--scope that selects nothing, or a term that does not parse, is a usage error", () => { + expect(dataop([JAVA, "--scope", "module:no.such.module"]).code).toBe(EXIT.USAGE); + const bad = dataop([JAVA, "--scope", "colour:blue"]); + expect(bad.code).toBe(EXIT.USAGE); + expect(bad.stderr).toContain("--scope"); + }); + + it("--boundaries marks the entry inventory's operations `entry`, and none are marked without it", () => { + const table = join(scratch, "stack.json"); + writeFileSync(table, JSON.stringify({ annotations: { Audited: "inbound command" } }), "utf8"); + const { code, stdout, stderr } = dataop([JAVA, "--boundaries", table]); + expect(code).toBe(EXIT.OK); + expect(stdout).toMatch(/entry operation discount\(/u); + expect(stderr).toMatch(/^boundaries: .* — \d+ entry rows?(, \d+ uncalled and named by no rule \(not marked\))?\.$/mu); + expect(dataop([JAVA]).stdout).not.toContain("entry operation"); + }); + + it("--boundaries writes an uncalled operation a rule NAMES `entry?`, a rule read at the declaration `entry`", () => { + const table = join(scratch, "inferred.json"); + // An `operations` rule names an uncalled operation: found by its name and its position in the graph, not by a rule at the declaration. + writeFileSync(table, JSON.stringify({ annotations: { Audited: "inbound command" }, operations: { bill: "inbound command" } }), "utf8"); + const { code, stdout } = dataop([JAVA, "--boundaries", table]); + expect(code).toBe(EXIT.OK); + expect(stdout).toMatch(/\n {6}entry operation discount\(/u); + expect(stdout).toMatch(/\n {6}entry\? operation bill\(/u); + // The one named row and no other: the rest of the uncalled operations stay unmarked. + expect(stdout.match(/entry\? operation /gu)).toHaveLength(1); + }); + + it("--boundaries leaves an uncalled operation no rule names unmarked: a position in the graph is not an entry", () => { + const table = join(scratch, "residue.json"); + // No `operations` rule: every `no caller` row is the unclassified residue (stimulus null). + writeFileSync(table, JSON.stringify({ annotations: { Audited: "inbound command" } }), "utf8"); + const { code, stdout, stderr } = dataop([JAVA, "--boundaries", table]); + expect(code).toBe(EXIT.OK); + expect(stdout).toMatch(/\n {6}entry operation discount\(/u); + expect(stdout).not.toMatch(/entry\? operation /u); + expect(stderr).toMatch(/^boundaries: .* — \d+ entry rows?, \d+ uncalled and named by no rule \(not marked\)\.$/mu); + }); + + it("refuses an unreadable boundaries file before reading the model", () => { + const { code, stderr } = dataop([JAVA, "--boundaries", join(scratch, "missing.json")]); + expect(code).toBe(EXIT.USAGE); + expect(stderr).toContain("--boundaries"); + }); +}); + +describe("dataop: through the real dispatcher", () => { + it("appears in the global help, and has its own", () => { + const io = captureIo(); + expect(runSync(["--help"], io)).toBe(EXIT.OK); + expect(io.stdout()).toContain("dataop"); + const own = captureIo(); + expect(runSync(["dataop", "--help"], own)).toBe(EXIT.OK); + for (const flag of ["--out", "--name", "--boundaries", "--scope"]) expect(own.stdout()).toContain(flag); + }); +}); diff --git a/packages/cli/test/golden/explain/java-max-scc-1/model.insights.sha256 b/packages/cli/test/golden/explain/java-max-scc-1/model.insights.sha256 index e83cc263..8b0c841a 100644 --- a/packages/cli/test/golden/explain/java-max-scc-1/model.insights.sha256 +++ b/packages/cli/test/golden/explain/java-max-scc-1/model.insights.sha256 @@ -44,7 +44,7 @@ i operation java:com.acme.order/Order.channel() sha256=fad121e2b29f5cb2a79f2c172 i operation java:com.acme.order/Order.discount(int) sha256=4a82e317ff21c040410fdc9d361e76e9a9d44fdbe71165eb6ff78dc577aeba91 i operation java:com.acme.order/OrderService.(com.megacorp.ledger.LedgerClient) sha256=d732fb9c0366064ac23108b284d0e8dace39db8c2bf169e25e45f2da9788a151 i operation java:com.acme.order/OrderService.archive(com.acme.order.legacy.List) sha256=39ae895db5523062b871c78240b02cdcd416d3e2aef5dea47df80924ff69f48d -i operation java:com.acme.order/OrderService.archive(java.util.List) sha256=b7465e0e9138361841e69ca31c3416439ad94b40146d727ffe5f263e8fabcd4a +i operation java:com.acme.order/OrderService.archive(java.util.List) sha256=0f6475278cd601dc5c22164645833b849a8f23d456ffe75c45c3b120b2c8d6f9 i operation java:com.acme.order/OrderService.bill(com.acme.order.Order) sha256=054849a7a0fced712fed1bdae5688bd4f6b741ee64b33491637221cb38c8c079 i operation java:com.acme.order/Priceable.price() sha256=128a3d0cd22a80f7b8e2158cf62d23e11a4f90d4345a967db2e99aecdbf15673 i operation java:com.acme.order/Reporting.() sha256=6c7ec1a345c1ba3b60298655acd7eb2ba60976fed44c4e29192d66d6ae114e59 @@ -71,11 +71,11 @@ i type java:com.acme.order/EmptyBasketException sha256=ef9b35621c3ed8787f6dfd234 i type java:com.acme.order/Money sha256=415197c0693ae6ce603d19b69023330e08845d7f8ec960aa0c6f10daa430b277 i type java:com.acme.order/Notifications sha256=a684f2240f174a90097d5efa9405ff00c43b162da0d2e28df90d66d37481ec75 i type java:com.acme.order/Order sha256=7d7ec956929d106dbd2ed563d88ca78e3e97f6f2d980b51fd1253fa5a56a92e4 -i type java:com.acme.order/OrderService sha256=b7529e4242741ab15f78b46476edf24d90c4558a75d1770610d2440efbf4313f +i type java:com.acme.order/OrderService sha256=809812de78570f462dc7a9fd93a20072d17e67123bba223c42a918a4209f1ca8 i type java:com.acme.order/Priceable sha256=bcd3efb3273f9af691b075ec93e04793b030cabc767b5023ea5e5c81db2e8458 i type java:com.acme.order/Reporting sha256=87cd68c3330f08e9096da5d58640fec492d4a5b74b6d86b14e02e727a3f60085 i type java:com.acme.order/StockGuard sha256=b641ff89201c63ed30531ded96ee11d17854a90c33600241df2d03f69b9f5f1e -i module java:com.acme.order sha256=0b0839382c4167fe6f0e498c012dcdae692f35525e8c87ec7327173aff735f5f +i module java:com.acme.order sha256=ad4b063726c054c3f42f3cb0e387b610bd770bb1c6776f475fd42667177df7fd i module java:com.acme.order.adapter sha256=51602051a23022f9fbb76977b4b758a18ed654d1494c14830008ec4ecaa4be53 i module java:com.acme.order.legacy sha256=3a816b142c3d7b225694a9f2ef207659a2657c49bb48714bd9a155e39a5c873e {"t":"eof","counts":{"records":79,"llm":70,"template":9,"reused":0,"failed":0},"usage":{"promptTokens":70000,"completionTokens":4480,"cost":0.01708984375},"generatedAt":"2026-11-21T00:00:00.000Z"} diff --git a/packages/cli/test/golden/explain/java-max-scc-1/plan.jsonl b/packages/cli/test/golden/explain/java-max-scc-1/plan.jsonl index 2b19dd03..dda6328d 100644 --- a/packages/cli/test/golden/explain/java-max-scc-1/plan.jsonl +++ b/packages/cli/test/golden/explain/java-max-scc-1/plan.jsonl @@ -1,4 +1,4 @@ -{"kind":"codegraph.explainPlan/1","models":{"leaf":"openai/gpt-5.6-luna","rollup":"openai/gpt-5.6-luna"},"depth":1,"estimates":{"calls":70,"promptTokens":117342,"completionTokens":52415,"byLevel":{"operation":{"calls":48,"promptTokens":78159,"completionTokens":30120,"units":57},"type":{"calls":19,"promptTokens":34193,"completionTokens":15470,"units":17},"module":{"calls":3,"promptTokens":4990,"completionTokens":6825,"units":3}},"byStatus":{"llm":68,"template":9,"reuse":0,"skip-scope":0,"skip-budget":0}},"steps":"77 steps, one per line below"} +{"kind":"codegraph.explainPlan/1","models":{"leaf":"openai/gpt-5.6-luna","rollup":"openai/gpt-5.6-luna"},"depth":1,"estimates":{"calls":70,"promptTokens":117347,"completionTokens":52415,"byLevel":{"operation":{"calls":48,"promptTokens":78161,"completionTokens":30120,"units":57},"type":{"calls":19,"promptTokens":34196,"completionTokens":15470,"units":17},"module":{"calls":3,"promptTokens":4990,"completionTokens":6825,"units":3}},"byStatus":{"llm":68,"template":9,"reuse":0,"skip-scope":0,"skip-budget":0}},"steps":"77 steps, one per line below"} {"id":"java:com.acme.order.adapter/LedgerAdapter.()","level":"operation","members":["java:com.acme.order.adapter/LedgerAdapter.()"],"layer":0,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1599} {"id":"java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)","level":"operation","members":["java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)"],"layer":0,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1647} {"id":"java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List)","level":"operation","members":["java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List)"],"layer":0,"status":"template","model":"openai/gpt-5.6-luna","calls":0,"promptTokens":0} @@ -51,7 +51,7 @@ {"id":"java:com.acme.order/Money.zero()","level":"operation","members":["java:com.acme.order/Money.zero()"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1597} {"id":"java:com.acme.order/Notifications.both(com.acme.order.Order)","level":"operation","members":["java:com.acme.order/Notifications.both(com.acme.order.Order)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1722} {"id":"java:com.acme.order/OrderService.archive(com.acme.order.legacy.List)","level":"operation","members":["java:com.acme.order/OrderService.archive(com.acme.order.legacy.List)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1647} -{"id":"java:com.acme.order/OrderService.archive(java.util.List)","level":"operation","members":["java:com.acme.order/OrderService.archive(java.util.List)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1657} +{"id":"java:com.acme.order/OrderService.archive(java.util.List)","level":"operation","members":["java:com.acme.order/OrderService.archive(java.util.List)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1659} {"id":"java:com.acme.order/OrderService.bill(com.acme.order.Order)","level":"operation","members":["java:com.acme.order/OrderService.bill(com.acme.order.Order)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1665} {"id":"java:com.acme.order/StockGuard.ensure(int)","level":"operation","members":["java:com.acme.order/StockGuard.ensure(int)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1726} {"id":"java:com.acme.order.adapter","level":"module","members":["java:com.acme.order.adapter"],"layer":2,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1573} @@ -74,5 +74,5 @@ {"id":"java:com.acme.order/Order.(java.lang.String)","level":"operation","members":["java:com.acme.order/Order.(java.lang.String)"],"layer":4,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1653} {"id":"java:com.acme.order/Order","level":"type","members":["java:com.acme.order/Order"],"layer":5,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1992} {"id":"java:com.acme.order/Notifications","level":"type","members":["java:com.acme.order/Notifications"],"layer":6,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":2001} -{"id":"java:com.acme.order/OrderService","level":"type","members":["java:com.acme.order/OrderService"],"layer":6,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1894} +{"id":"java:com.acme.order/OrderService","level":"type","members":["java:com.acme.order/OrderService"],"layer":6,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1897} {"id":"java:com.acme.order","level":"module","members":["java:com.acme.order"],"layer":7,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1861} diff --git a/packages/cli/test/golden/explain/java-max-scc-1/prompts-planned.sha256 b/packages/cli/test/golden/explain/java-max-scc-1/prompts-planned.sha256 index 95885489..0593c3aa 100644 --- a/packages/cli/test/golden/explain/java-max-scc-1/prompts-planned.sha256 +++ b/packages/cli/test/golden/explain/java-max-scc-1/prompts-planned.sha256 @@ -41,7 +41,7 @@ 41 operation java:com.acme.order/Money.zero() codegraph_operation system=dc45667c9ad4bd03 user=aee9e00d5e24ca215d84f50ebda5bdff1e5947ab195087278596a463e13b7723 42 operation java:com.acme.order/Notifications.both(com.acme.order.Order) codegraph_operation system=dc45667c9ad4bd03 user=32571dd9bff8b75172864835154c55e89744eb6951f639781d681c338371e255 43 operation java:com.acme.order/OrderService.archive(com.acme.order.legacy.List) codegraph_operation system=dc45667c9ad4bd03 user=1e60cd4b8718744ce7eb6f5e94644d829b8edd7faa52726ee5f199455e2be858 -44 operation java:com.acme.order/OrderService.archive(java.util.List) codegraph_operation system=dc45667c9ad4bd03 user=91adbae821d924845e5a965c37229d3ff65ba8b7639d7f7b7e2a5fb18e1e32e8 +44 operation java:com.acme.order/OrderService.archive(java.util.List) codegraph_operation system=dc45667c9ad4bd03 user=301d0594619a8fc35301392b0c7301554b6303fb3b158f400b4dda172c7da25c 45 operation java:com.acme.order/OrderService.bill(com.acme.order.Order) codegraph_operation system=dc45667c9ad4bd03 user=2ae28bed2aa2f0609532128dd1f6fc9a06b931efce336fcb07420fa23044aa15 46 operation java:com.acme.order/StockGuard.ensure(int) codegraph_operation system=dc45667c9ad4bd03 user=eb81427168996cf491d2843da738fa2eb20f881f801db6acc8eed7405bfb030c 47 module java:com.acme.order.adapter codegraph_module system=206d67daaf006b8b user=e9988aa1b80f0bd816e94e4ab95bdd147f0ae28ffa92459b089091f60eaef46b @@ -66,5 +66,5 @@ 66 operation java:com.acme.order/Order.(java.lang.String) codegraph_operation system=dc45667c9ad4bd03 user=d6fb0f18ee27bd33e2fce2017a61c20c4a96bf967b867d57118e516b98c6ee3b 67 type java:com.acme.order/Order codegraph_type system=e269e40492f79aa0 user=e7f2acd241150b6e05fa2b206094c298517e765e4dd7fef4580099973e3f190d 68 type java:com.acme.order/Notifications codegraph_type system=e269e40492f79aa0 user=8d030919e5f5ced8ed6b25711453f6873e0f5dd7c6cb77c1981c4f37b48d1e10 -69 type java:com.acme.order/OrderService codegraph_type system=e269e40492f79aa0 user=00c1d217f20ec040d378437a9486600b64ece7e9014c00d4e81560c71d8b7f95 +69 type java:com.acme.order/OrderService codegraph_type system=e269e40492f79aa0 user=a08f995f398cd4c669761747ab34be97e25a4c197d44a8c8de993ef81c981e70 70 module java:com.acme.order codegraph_module system=206d67daaf006b8b user=18bf502cb7b14f291723df6d3c55b9412154c79a841897bd4374451d374270a3 diff --git a/packages/cli/test/golden/explain/java-max-scc-1/prompts.sha256 b/packages/cli/test/golden/explain/java-max-scc-1/prompts.sha256 index 2a38f5f3..c484586b 100644 --- a/packages/cli/test/golden/explain/java-max-scc-1/prompts.sha256 +++ b/packages/cli/test/golden/explain/java-max-scc-1/prompts.sha256 @@ -41,7 +41,7 @@ 41 operation java:com.acme.order/Money.zero() codegraph_operation system=dc45667c9ad4bd03 user=6e704afd5963d941ced0417676c8c4b5a70e0385cda9de251e6eb2ef9111d272 model=openai/gpt-5.6-luna 42 operation java:com.acme.order/Notifications.both(com.acme.order.Order) codegraph_operation system=dc45667c9ad4bd03 user=d386634a3b1983be09c90dd7eeb2f2b143646b15de39334964d410d4cd021cc8 model=openai/gpt-5.6-luna 43 operation java:com.acme.order/OrderService.archive(com.acme.order.legacy.List) codegraph_operation system=dc45667c9ad4bd03 user=74f8db2d70b8aa116acff66a52dbb687f74a78b7947af7bdb7cb20d20aaaf239 model=openai/gpt-5.6-luna -44 operation java:com.acme.order/OrderService.archive(java.util.List) codegraph_operation system=dc45667c9ad4bd03 user=0b39dcdd33d68b9571511273752656bce5e8975ac2584a018fa9f5f59dd6bdc4 model=openai/gpt-5.6-luna +44 operation java:com.acme.order/OrderService.archive(java.util.List) codegraph_operation system=dc45667c9ad4bd03 user=929a174751e3b358acf4c5b7e2bbdadde978d2fbec8a2eb2d4fe7c9a31c938b4 model=openai/gpt-5.6-luna 45 operation java:com.acme.order/OrderService.bill(com.acme.order.Order) codegraph_operation system=dc45667c9ad4bd03 user=611920f7f922b960c9d4dadda790995c5a39df5a3391dcdf1962bdaa3b6b3ab4 model=openai/gpt-5.6-luna 46 operation java:com.acme.order/StockGuard.ensure(int) codegraph_operation system=dc45667c9ad4bd03 user=38744725ae326ee6a181e3274154043ca6cbaebbbd2119eb6a76363e5f9a4926 model=openai/gpt-5.6-luna 47 module java:com.acme.order.adapter codegraph_module system=206d67daaf006b8b user=2b8d0927e4c205993dfdfbec02fa1b74936964cc6e45627f242bbe8c6e7195a7 model=openai/gpt-5.6-luna @@ -66,5 +66,5 @@ 66 operation java:com.acme.order/Order.(java.lang.String) codegraph_operation system=dc45667c9ad4bd03 user=f6bb2f582e92a49f616a0cd93920f33f2aa74447b7c076cde9913b98b59759e3 model=openai/gpt-5.6-luna 67 type java:com.acme.order/Order codegraph_type system=e269e40492f79aa0 user=394bfe9d61037b548abd31129c82ea4150f94b7c3abeb56726cbb8c0ac5c83a3 model=openai/gpt-5.6-luna 68 type java:com.acme.order/Notifications codegraph_type system=e269e40492f79aa0 user=afff00eedaadbd2c2a596fa49ea6712e049cf5d1f9a63954a2f6801cbb34ce3a model=openai/gpt-5.6-luna -69 type java:com.acme.order/OrderService codegraph_type system=e269e40492f79aa0 user=f86055ff16da42d6da9bd8001da82c95f66bf39e9a0163a65d979e07a45c9ff6 model=openai/gpt-5.6-luna +69 type java:com.acme.order/OrderService codegraph_type system=e269e40492f79aa0 user=ff074a4fbad98cb57bbfc144c41a4996f5325ca3d46c639e9749f461f2380873 model=openai/gpt-5.6-luna 70 module java:com.acme.order codegraph_module system=206d67daaf006b8b user=f44e6c5b17379f4031791b81c452e39ef9eb83d62cd96a554fcdb39080b7b2a9 model=openai/gpt-5.6-luna diff --git a/packages/cli/test/golden/explain/java-max-scc-1/units.txt b/packages/cli/test/golden/explain/java-max-scc-1/units.txt index 5cfa5f84..6194c327 100644 --- a/packages/cli/test/golden/explain/java-max-scc-1/units.txt +++ b/packages/cli/test/golden/explain/java-max-scc-1/units.txt @@ -50,7 +50,7 @@ operation java:com.acme.order/Money.times(int) llm fingerprint=da2326b64ebfdfdac operation java:com.acme.order/Money.zero() llm fingerprint=a364a12d92a26fc10d2750b6bc3a7c42cc9bb0329fb7d641693f67acd77b35c0 chain=49a13a1b5fef7c37d39ff08ab1814c307423699f62a3a640858e5649d664ed65 stamped=9d176eea263a1cf1f0b2cc8afab78f1b8077dcabb293be3020e5ebdda542f64b operation java:com.acme.order/Notifications.both(com.acme.order.Order) llm fingerprint=2695f482c2ba36c746e569ac866c178aa8f111c6ab106f40ce17963618f49a56 chain=2c28d39958216d9fa7390060df2f77e0d5b8b1f520dc4398253bdfe4c61f7622 stamped=405f9cfe0b1561c89a92082037728406a39bc3f04fabad062acbc68bc41e84ae operation java:com.acme.order/OrderService.archive(com.acme.order.legacy.List) llm fingerprint=c7a45fd599ddd35399035f33ef88b553c3c5f42d7bf9164d57d994efc1002102 chain=7483d17eac5d40a6454cf75c675e932a05a3db00a78da9c038fdf347b77e29ac stamped=8dc0338829527ea4e7cbc4fb6d582489294d6afa9a8d852d5b0c736d98d0f1d9 -operation java:com.acme.order/OrderService.archive(java.util.List) llm fingerprint=5014c95fd755888907ec4b1f8148ba250f81792cc80046234f8efc6562489979 chain=de018c799d2b0031de3a25a2d444af86dc9365fa768e2f3bcccaa92f02efa147 stamped=22ec4347bac0df33543ed198bc351418e00c8a4fbb029dbf8ca0564e0cc6349c +operation java:com.acme.order/OrderService.archive(java.util.List) llm fingerprint=67f96bfbaa187e7769386b919ae013be2d0995232a8df18efcb4a823e4b412fd chain=343cde3675d5b3513cb0f8baf9a0e0cba18f95c803fb715148791eedd1989cbe stamped=64797cccaba1f498d71be99c8c973843c27f8836d63ae36bbaf3b186cc4fed7a operation java:com.acme.order/OrderService.bill(com.acme.order.Order) llm fingerprint=c229926c94a504cfc95904666c6a13e450cb391710008f7d9f71070ad660dbbd chain=ae243cd612510f274a13ed96f983bacc0470236e7d57b0b6f5bfb0f826ac88ee stamped=c23efc407657d4bf30d8a526d82578f2295bb4a396962f6274eabfc8ee01d6e9 operation java:com.acme.order/StockGuard.ensure(int) llm fingerprint=4b670b6e7e7cd2270199477474ed04bda7ec1eea956f520921ab25af7e9c6787 chain=56372d54bdadac7dd6fc038fafddde2ba5f24f753ec0d220e362708aa6806fbc stamped=2d1c4136a0e310922e00980d8db38d9c43a6d242a44242e731ded007c0543176 module java:com.acme.order.adapter llm fingerprint=cefb6fd8308187787e107595b7c9c371cabe8f28589d800396b0c69916f4496e chain=ff47c9fe75385ca90db5b32647424d2fad301757661a0f1453d311f1878b30a4 stamped=72f4ce44c00f52bf9383124dbdfc9359ce7924210e861f6e20c9d74483c36bf0 @@ -73,5 +73,5 @@ type java:com.acme.order/AbstractOrder llm fingerprint=207ca5d95fab853c713af0ac3 operation java:com.acme.order/Order.(java.lang.String) llm fingerprint=7410566c6f499ccd66812de9028828206bd391a2800cf9c7b94de470a128d899 chain=80b8f5ff1bf86e47457e843263bbb1a0319ed43e52057811adb186b533c8c0d9 stamped=b13141fff0fe439638433e527b8320614e995b0f7fa4e25d61031adbf9b60edc type java:com.acme.order/Order llm fingerprint=e64326dad720bbc3f977e69e23cb1c9689b9fc3f2b4be0abb5c76df4065a362e chain=2036f6aa3d3444362846531aa056881fff5ca0b59032dbfa56f9461d4874f7f9 stamped=4ac567f3b61b1f04b82fc8a1bc9b152b1413930fafa5094ec89b7538fbeef1de type java:com.acme.order/Notifications llm fingerprint=938722ac874b3c355882f97c303b53758fb10f46990a79fa2a93cfb9e87894a8 chain=acdce7dd25408b0f4a6315a0199dee914426a7ee7f1e17ca3d165ac7b519ca59 stamped=5504d2bd67a3391f0a12309dc934af3960510f3a978349d77ad821021d6064ed -type java:com.acme.order/OrderService llm fingerprint=6bf7da2e7e2e475d56b72e3f4e1a71b096e7ffa4f248a45619a4340b1fca165e chain=4626d27e8f44cde8d841500c7c6550161651ee0c9f18a8bc279a91e37e649f01 stamped=5134c03d2bb7c5135b7285e5134086a34f34f6a15053606f90546679e3f99833 -module java:com.acme.order llm fingerprint=6687324da963a818b521bac404ffdd5252700b36ab84c9de9e93cd0dbf6582f5 chain=cabca33f124b8fa40e1d034de638c2ab92c55e4856e88d663e640aef5473558a stamped=2ce927d45590eee9430d7f28fd05e557d7d8f965c91ac2efdcbbf0a3d427cf1f +type java:com.acme.order/OrderService llm fingerprint=7a9db040b2a6d715ac35e3407cf8c035cc19a65d60d610191bc5015fa38bdcb9 chain=a295cbb1151c475d70935de8cabfd948c94710ae1cb012777f1dba0471202142 stamped=4559c489b167f10c19eb9ba03964e6055b91e85205e129b99cf6cc3f54907c14 +module java:com.acme.order llm fingerprint=03cf006e56357c42721222d6a86f06b5b84f899d1bbc1284651de1a5b52d8758 chain=d07feadce7a6f9fd2d25c333219d846d2655f022df12f878955bb628d202d5e7 stamped=a5cc6430a3599cdeb43aea8199ad03b8fd5339f390a9dc533934e7da8c9f07e2 diff --git a/packages/cli/test/golden/explain/java-scope-order/model.insights.sha256 b/packages/cli/test/golden/explain/java-scope-order/model.insights.sha256 index f05270c7..7ef11213 100644 --- a/packages/cli/test/golden/explain/java-scope-order/model.insights.sha256 +++ b/packages/cli/test/golden/explain/java-scope-order/model.insights.sha256 @@ -41,7 +41,7 @@ i operation java:com.acme.order/Order.channel() sha256=fad121e2b29f5cb2a79f2c172 i operation java:com.acme.order/Order.discount(int) sha256=4a82e317ff21c040410fdc9d361e76e9a9d44fdbe71165eb6ff78dc577aeba91 i operation java:com.acme.order/OrderService.(com.megacorp.ledger.LedgerClient) sha256=d732fb9c0366064ac23108b284d0e8dace39db8c2bf169e25e45f2da9788a151 i operation java:com.acme.order/OrderService.archive(com.acme.order.legacy.List) sha256=39ae895db5523062b871c78240b02cdcd416d3e2aef5dea47df80924ff69f48d -i operation java:com.acme.order/OrderService.archive(java.util.List) sha256=b7465e0e9138361841e69ca31c3416439ad94b40146d727ffe5f263e8fabcd4a +i operation java:com.acme.order/OrderService.archive(java.util.List) sha256=0f6475278cd601dc5c22164645833b849a8f23d456ffe75c45c3b120b2c8d6f9 i operation java:com.acme.order/OrderService.bill(com.acme.order.Order) sha256=054849a7a0fced712fed1bdae5688bd4f6b741ee64b33491637221cb38c8c079 i operation java:com.acme.order/Priceable.price() sha256=128a3d0cd22a80f7b8e2158cf62d23e11a4f90d4345a967db2e99aecdbf15673 i operation java:com.acme.order/Reporting.() sha256=6c7ec1a345c1ba3b60298655acd7eb2ba60976fed44c4e29192d66d6ae114e59 @@ -66,9 +66,9 @@ i type java:com.acme.order/EmptyBasketException sha256=ef9b35621c3ed8787f6dfd234 i type java:com.acme.order/Money sha256=eb906eb4441e0e25457e9de968a74ee328475ded3561a4be175d40cca44caa3f i type java:com.acme.order/Notifications sha256=a684f2240f174a90097d5efa9405ff00c43b162da0d2e28df90d66d37481ec75 i type java:com.acme.order/Order sha256=7d7ec956929d106dbd2ed563d88ca78e3e97f6f2d980b51fd1253fa5a56a92e4 -i type java:com.acme.order/OrderService sha256=f87d8e47710eb92d9634f35471d484eb26b78afbb92b2223e9cf38391fe6c903 +i type java:com.acme.order/OrderService sha256=5ca0bd9bd0071b9619aa41617e8d32f34be3389a94e7b6f2cd76804a4d94a53b i type java:com.acme.order/Priceable sha256=d7ec64180172bcdee9d8d444f16bb5e7d796451711d9f7b6504fed503feb0911 i type java:com.acme.order/Reporting sha256=87cd68c3330f08e9096da5d58640fec492d4a5b74b6d86b14e02e727a3f60085 i type java:com.acme.order/StockGuard sha256=b641ff89201c63ed30531ded96ee11d17854a90c33600241df2d03f69b9f5f1e -i module java:com.acme.order sha256=196e2a0a0a1afb30fc5344a2026c14685b7fcf767f451d0b4c47d371a7268920 +i module java:com.acme.order sha256=4ef9f027765f16610e01989f80d6745ea84331f7f6fb07b15048664b4860158f {"t":"eof","counts":{"records":72,"llm":63,"template":9,"reused":0,"failed":0},"usage":{"promptTokens":61000,"completionTokens":3904,"cost":0.014892578125},"generatedAt":"2026-11-21T00:00:00.000Z"} diff --git a/packages/cli/test/golden/explain/java-scope-order/plan.jsonl b/packages/cli/test/golden/explain/java-scope-order/plan.jsonl index 2bbfa30b..4607546b 100644 --- a/packages/cli/test/golden/explain/java-scope-order/plan.jsonl +++ b/packages/cli/test/golden/explain/java-scope-order/plan.jsonl @@ -1,4 +1,4 @@ -{"kind":"codegraph.explainPlan/1","models":{"leaf":"openai/gpt-5.6-luna","rollup":"openai/gpt-5.6-luna"},"depth":1,"estimates":{"calls":61,"promptTokens":102742,"completionTokens":46815,"byLevel":{"operation":{"calls":45,"promptTokens":73329,"completionTokens":28350,"units":57},"type":{"calls":15,"promptTokens":27552,"completionTokens":13690,"units":17},"module":{"calls":1,"promptTokens":1861,"completionTokens":4775,"units":3}},"byStatus":{"llm":61,"template":9,"reuse":0,"skip-scope":7,"skip-budget":0}},"steps":"77 steps, one per line below"} +{"kind":"codegraph.explainPlan/1","models":{"leaf":"openai/gpt-5.6-luna","rollup":"openai/gpt-5.6-luna"},"depth":1,"estimates":{"calls":61,"promptTokens":102747,"completionTokens":46815,"byLevel":{"operation":{"calls":45,"promptTokens":73331,"completionTokens":28350,"units":57},"type":{"calls":15,"promptTokens":27555,"completionTokens":13690,"units":17},"module":{"calls":1,"promptTokens":1861,"completionTokens":4775,"units":3}},"byStatus":{"llm":61,"template":9,"reuse":0,"skip-scope":7,"skip-budget":0}},"steps":"77 steps, one per line below"} {"id":"java:com.acme.order.adapter/LedgerAdapter.()","level":"operation","members":["java:com.acme.order.adapter/LedgerAdapter.()"],"layer":0,"status":"skip-scope","model":"openai/gpt-5.6-luna","calls":0,"promptTokens":0} {"id":"java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)","level":"operation","members":["java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)"],"layer":0,"status":"skip-scope","model":"openai/gpt-5.6-luna","calls":0,"promptTokens":0} {"id":"java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List)","level":"operation","members":["java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List)"],"layer":0,"status":"template","model":"openai/gpt-5.6-luna","calls":0,"promptTokens":0} @@ -51,7 +51,7 @@ {"id":"java:com.acme.order/Money.zero()","level":"operation","members":["java:com.acme.order/Money.zero()"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1597} {"id":"java:com.acme.order/Notifications.both(com.acme.order.Order)","level":"operation","members":["java:com.acme.order/Notifications.both(com.acme.order.Order)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1722} {"id":"java:com.acme.order/OrderService.archive(com.acme.order.legacy.List)","level":"operation","members":["java:com.acme.order/OrderService.archive(com.acme.order.legacy.List)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1647} -{"id":"java:com.acme.order/OrderService.archive(java.util.List)","level":"operation","members":["java:com.acme.order/OrderService.archive(java.util.List)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1657} +{"id":"java:com.acme.order/OrderService.archive(java.util.List)","level":"operation","members":["java:com.acme.order/OrderService.archive(java.util.List)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1659} {"id":"java:com.acme.order/OrderService.bill(com.acme.order.Order)","level":"operation","members":["java:com.acme.order/OrderService.bill(com.acme.order.Order)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1665} {"id":"java:com.acme.order/StockGuard.ensure(int)","level":"operation","members":["java:com.acme.order/StockGuard.ensure(int)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1726} {"id":"java:com.acme.order.adapter","level":"module","members":["java:com.acme.order.adapter"],"layer":2,"status":"skip-scope","model":"openai/gpt-5.6-luna","calls":0,"promptTokens":0} @@ -74,5 +74,5 @@ {"id":"java:com.acme.order/Order.(java.lang.String)","level":"operation","members":["java:com.acme.order/Order.(java.lang.String)"],"layer":4,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1653} {"id":"java:com.acme.order/Order","level":"type","members":["java:com.acme.order/Order"],"layer":5,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1992} {"id":"java:com.acme.order/Notifications","level":"type","members":["java:com.acme.order/Notifications"],"layer":6,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":2001} -{"id":"java:com.acme.order/OrderService","level":"type","members":["java:com.acme.order/OrderService"],"layer":6,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1894} +{"id":"java:com.acme.order/OrderService","level":"type","members":["java:com.acme.order/OrderService"],"layer":6,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1897} {"id":"java:com.acme.order","level":"module","members":["java:com.acme.order"],"layer":7,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1861} diff --git a/packages/cli/test/golden/explain/java-scope-order/prompts-planned.sha256 b/packages/cli/test/golden/explain/java-scope-order/prompts-planned.sha256 index 5fb33dbf..07ec3e89 100644 --- a/packages/cli/test/golden/explain/java-scope-order/prompts-planned.sha256 +++ b/packages/cli/test/golden/explain/java-scope-order/prompts-planned.sha256 @@ -36,7 +36,7 @@ 36 operation java:com.acme.order/Money.zero() codegraph_operation system=dc45667c9ad4bd03 user=aee9e00d5e24ca215d84f50ebda5bdff1e5947ab195087278596a463e13b7723 37 operation java:com.acme.order/Notifications.both(com.acme.order.Order) codegraph_operation system=dc45667c9ad4bd03 user=32571dd9bff8b75172864835154c55e89744eb6951f639781d681c338371e255 38 operation java:com.acme.order/OrderService.archive(com.acme.order.legacy.List) codegraph_operation system=dc45667c9ad4bd03 user=1e60cd4b8718744ce7eb6f5e94644d829b8edd7faa52726ee5f199455e2be858 -39 operation java:com.acme.order/OrderService.archive(java.util.List) codegraph_operation system=dc45667c9ad4bd03 user=91adbae821d924845e5a965c37229d3ff65ba8b7639d7f7b7e2a5fb18e1e32e8 +39 operation java:com.acme.order/OrderService.archive(java.util.List) codegraph_operation system=dc45667c9ad4bd03 user=301d0594619a8fc35301392b0c7301554b6303fb3b158f400b4dda172c7da25c 40 operation java:com.acme.order/OrderService.bill(com.acme.order.Order) codegraph_operation system=dc45667c9ad4bd03 user=2ae28bed2aa2f0609532128dd1f6fc9a06b931efce336fcb07420fa23044aa15 41 operation java:com.acme.order/StockGuard.ensure(int) codegraph_operation system=dc45667c9ad4bd03 user=eb81427168996cf491d2843da738fa2eb20f881f801db6acc8eed7405bfb030c 42 operation java:com.acme.order/AbstractOrder.(java.lang.String) codegraph_operation system=dc45667c9ad4bd03 user=1cbf33345a46f2fe1458ca0f9d7289cf42201ac0f77d2eee95b388909d85f778 @@ -57,5 +57,5 @@ 57 operation java:com.acme.order/Order.(java.lang.String) codegraph_operation system=dc45667c9ad4bd03 user=d6fb0f18ee27bd33e2fce2017a61c20c4a96bf967b867d57118e516b98c6ee3b 58 type java:com.acme.order/Order codegraph_type system=e269e40492f79aa0 user=e7f2acd241150b6e05fa2b206094c298517e765e4dd7fef4580099973e3f190d 59 type java:com.acme.order/Notifications codegraph_type system=e269e40492f79aa0 user=8d030919e5f5ced8ed6b25711453f6873e0f5dd7c6cb77c1981c4f37b48d1e10 -60 type java:com.acme.order/OrderService codegraph_type system=e269e40492f79aa0 user=00c1d217f20ec040d378437a9486600b64ece7e9014c00d4e81560c71d8b7f95 +60 type java:com.acme.order/OrderService codegraph_type system=e269e40492f79aa0 user=a08f995f398cd4c669761747ab34be97e25a4c197d44a8c8de993ef81c981e70 61 module java:com.acme.order codegraph_module system=206d67daaf006b8b user=18bf502cb7b14f291723df6d3c55b9412154c79a841897bd4374451d374270a3 diff --git a/packages/cli/test/golden/explain/java-scope-order/prompts.sha256 b/packages/cli/test/golden/explain/java-scope-order/prompts.sha256 index e6a6b3da..5f8a96aa 100644 --- a/packages/cli/test/golden/explain/java-scope-order/prompts.sha256 +++ b/packages/cli/test/golden/explain/java-scope-order/prompts.sha256 @@ -36,7 +36,7 @@ 36 operation java:com.acme.order/Money.zero() codegraph_operation system=dc45667c9ad4bd03 user=6e704afd5963d941ced0417676c8c4b5a70e0385cda9de251e6eb2ef9111d272 model=openai/gpt-5.6-luna 37 operation java:com.acme.order/Notifications.both(com.acme.order.Order) codegraph_operation system=dc45667c9ad4bd03 user=d386634a3b1983be09c90dd7eeb2f2b143646b15de39334964d410d4cd021cc8 model=openai/gpt-5.6-luna 38 operation java:com.acme.order/OrderService.archive(com.acme.order.legacy.List) codegraph_operation system=dc45667c9ad4bd03 user=74f8db2d70b8aa116acff66a52dbb687f74a78b7947af7bdb7cb20d20aaaf239 model=openai/gpt-5.6-luna -39 operation java:com.acme.order/OrderService.archive(java.util.List) codegraph_operation system=dc45667c9ad4bd03 user=0b39dcdd33d68b9571511273752656bce5e8975ac2584a018fa9f5f59dd6bdc4 model=openai/gpt-5.6-luna +39 operation java:com.acme.order/OrderService.archive(java.util.List) codegraph_operation system=dc45667c9ad4bd03 user=929a174751e3b358acf4c5b7e2bbdadde978d2fbec8a2eb2d4fe7c9a31c938b4 model=openai/gpt-5.6-luna 40 operation java:com.acme.order/OrderService.bill(com.acme.order.Order) codegraph_operation system=dc45667c9ad4bd03 user=611920f7f922b960c9d4dadda790995c5a39df5a3391dcdf1962bdaa3b6b3ab4 model=openai/gpt-5.6-luna 41 operation java:com.acme.order/StockGuard.ensure(int) codegraph_operation system=dc45667c9ad4bd03 user=38744725ae326ee6a181e3274154043ca6cbaebbbd2119eb6a76363e5f9a4926 model=openai/gpt-5.6-luna 42 operation java:com.acme.order/AbstractOrder.(java.lang.String) codegraph_operation system=dc45667c9ad4bd03 user=58fa221ceb128c83cd3824c17674a2615c4ab7429db791412d3f7edff189cdcb model=openai/gpt-5.6-luna @@ -57,5 +57,5 @@ 57 operation java:com.acme.order/Order.(java.lang.String) codegraph_operation system=dc45667c9ad4bd03 user=f6bb2f582e92a49f616a0cd93920f33f2aa74447b7c076cde9913b98b59759e3 model=openai/gpt-5.6-luna 58 type java:com.acme.order/Order codegraph_type system=e269e40492f79aa0 user=394bfe9d61037b548abd31129c82ea4150f94b7c3abeb56726cbb8c0ac5c83a3 model=openai/gpt-5.6-luna 59 type java:com.acme.order/Notifications codegraph_type system=e269e40492f79aa0 user=afff00eedaadbd2c2a596fa49ea6712e049cf5d1f9a63954a2f6801cbb34ce3a model=openai/gpt-5.6-luna -60 type java:com.acme.order/OrderService codegraph_type system=e269e40492f79aa0 user=1da10f170d5eabe53815b2cb5dccac5f7c48a64645ebe1b5e657845fa06f0a1b model=openai/gpt-5.6-luna +60 type java:com.acme.order/OrderService codegraph_type system=e269e40492f79aa0 user=68272e4de85f79405793cd6cfd9074beaed7e1755075b821cb77d5b69cefe6ea model=openai/gpt-5.6-luna 61 module java:com.acme.order codegraph_module system=206d67daaf006b8b user=f44e6c5b17379f4031791b81c452e39ef9eb83d62cd96a554fcdb39080b7b2a9 model=openai/gpt-5.6-luna diff --git a/packages/cli/test/golden/explain/java-scope-order/units.txt b/packages/cli/test/golden/explain/java-scope-order/units.txt index e84c11c2..61fee484 100644 --- a/packages/cli/test/golden/explain/java-scope-order/units.txt +++ b/packages/cli/test/golden/explain/java-scope-order/units.txt @@ -50,7 +50,7 @@ operation java:com.acme.order/Money.times(int) llm fingerprint=da2326b64ebfdfdac operation java:com.acme.order/Money.zero() llm fingerprint=a364a12d92a26fc10d2750b6bc3a7c42cc9bb0329fb7d641693f67acd77b35c0 chain=49a13a1b5fef7c37d39ff08ab1814c307423699f62a3a640858e5649d664ed65 stamped=9d176eea263a1cf1f0b2cc8afab78f1b8077dcabb293be3020e5ebdda542f64b operation java:com.acme.order/Notifications.both(com.acme.order.Order) llm fingerprint=2695f482c2ba36c746e569ac866c178aa8f111c6ab106f40ce17963618f49a56 chain=2c28d39958216d9fa7390060df2f77e0d5b8b1f520dc4398253bdfe4c61f7622 stamped=405f9cfe0b1561c89a92082037728406a39bc3f04fabad062acbc68bc41e84ae operation java:com.acme.order/OrderService.archive(com.acme.order.legacy.List) llm fingerprint=c7a45fd599ddd35399035f33ef88b553c3c5f42d7bf9164d57d994efc1002102 chain=7483d17eac5d40a6454cf75c675e932a05a3db00a78da9c038fdf347b77e29ac stamped=8dc0338829527ea4e7cbc4fb6d582489294d6afa9a8d852d5b0c736d98d0f1d9 -operation java:com.acme.order/OrderService.archive(java.util.List) llm fingerprint=5014c95fd755888907ec4b1f8148ba250f81792cc80046234f8efc6562489979 chain=de018c799d2b0031de3a25a2d444af86dc9365fa768e2f3bcccaa92f02efa147 stamped=22ec4347bac0df33543ed198bc351418e00c8a4fbb029dbf8ca0564e0cc6349c +operation java:com.acme.order/OrderService.archive(java.util.List) llm fingerprint=67f96bfbaa187e7769386b919ae013be2d0995232a8df18efcb4a823e4b412fd chain=343cde3675d5b3513cb0f8baf9a0e0cba18f95c803fb715148791eedd1989cbe stamped=64797cccaba1f498d71be99c8c973843c27f8836d63ae36bbaf3b186cc4fed7a operation java:com.acme.order/OrderService.bill(com.acme.order.Order) llm fingerprint=c229926c94a504cfc95904666c6a13e450cb391710008f7d9f71070ad660dbbd chain=ae243cd612510f274a13ed96f983bacc0470236e7d57b0b6f5bfb0f826ac88ee stamped=c23efc407657d4bf30d8a526d82578f2295bb4a396962f6274eabfc8ee01d6e9 operation java:com.acme.order/StockGuard.ensure(int) llm fingerprint=4b670b6e7e7cd2270199477474ed04bda7ec1eea956f520921ab25af7e9c6787 chain=56372d54bdadac7dd6fc038fafddde2ba5f24f753ec0d220e362708aa6806fbc stamped=2d1c4136a0e310922e00980d8db38d9c43a6d242a44242e731ded007c0543176 module java:com.acme.order.adapter skip-scope fingerprint=d31d3351b5edb7aba06eba6da5ad31f61ff2d49cbdb16838d787c25550bb9b14 chain=af4d70e7ef47a0f1318b5b966307ae688158f5f20be10f8a223db86dbf61d6d1 stamped=94c96afc756576ce74d2a29c8d178ef13256df50ae06dae1a70f166f0c7582b1 @@ -73,5 +73,5 @@ type java:com.acme.order/AbstractOrder llm fingerprint=207ca5d95fab853c713af0ac3 operation java:com.acme.order/Order.(java.lang.String) llm fingerprint=7410566c6f499ccd66812de9028828206bd391a2800cf9c7b94de470a128d899 chain=80b8f5ff1bf86e47457e843263bbb1a0319ed43e52057811adb186b533c8c0d9 stamped=b13141fff0fe439638433e527b8320614e995b0f7fa4e25d61031adbf9b60edc type java:com.acme.order/Order llm fingerprint=e64326dad720bbc3f977e69e23cb1c9689b9fc3f2b4be0abb5c76df4065a362e chain=2036f6aa3d3444362846531aa056881fff5ca0b59032dbfa56f9461d4874f7f9 stamped=4ac567f3b61b1f04b82fc8a1bc9b152b1413930fafa5094ec89b7538fbeef1de type java:com.acme.order/Notifications llm fingerprint=938722ac874b3c355882f97c303b53758fb10f46990a79fa2a93cfb9e87894a8 chain=acdce7dd25408b0f4a6315a0199dee914426a7ee7f1e17ca3d165ac7b519ca59 stamped=5504d2bd67a3391f0a12309dc934af3960510f3a978349d77ad821021d6064ed -type java:com.acme.order/OrderService llm fingerprint=1e836e0a4f308980d7a71ccd0b02ad2ab9a78cc4eb64b708f803407e034b682e chain=073e7e699bb9ac897ed855c5ae548a36177afa2efc7e9c1073b87165dd49cac2 stamped=62d3fd7c99d563eee7349886672258d9939539354ca963845fb4cfe8dfb8ae52 -module java:com.acme.order llm fingerprint=a456304f75c467d140f76264e6b2ad7aa0daf060928c9f99f19ec58a7e568ccc chain=217cab989e59f7cb8804cd32653919a3b2e6c1cc2e8484e619d6ec30976eec5f stamped=8bfac5771485d8e3187359ff76ad93cbd2af831ddf7149453001b916aa02c7ad +type java:com.acme.order/OrderService llm fingerprint=e44b2cb8613caaca56e33fd201922a99f98fd32c8be82e6041cd6d79762ab45b chain=d731f322d11830e4c96c20b29a4ecb9f1410fa6d17cb9ab8e89b505637b271b6 stamped=7bd9614188814132d659668ac54709d117f5c05155e6032488f6bb12cb1285e3 +module java:com.acme.order llm fingerprint=4285bfd53e568e38ee82579fbd4af1e93f047cd18b2d03c253004926683cf31a chain=65d58f42828770ca051d52aced3fd71f1a4977e5327c2455d305eafba5b9dc82 stamped=4c05a7f73824a45763f667b6badd154435d0d88a5f6ba5a0eaea9277227bc580 diff --git a/packages/cli/test/golden/explain/java/model.insights.jsonl b/packages/cli/test/golden/explain/java/model.insights.jsonl index 3539c8f5..d0613345 100644 --- a/packages/cli/test/golden/explain/java/model.insights.jsonl +++ b/packages/cli/test/golden/explain/java/model.insights.jsonl @@ -44,7 +44,7 @@ {"t":"i","id":"java:com.acme.order/Order.discount(int)","key":{"lang":"java","module":"com.acme.order","symbol":"Order.discount(int)"},"level":"operation","kind":"method","name":"discount","file":"com/acme/order/Order.java","origin":"llm","block":{"name":"Order.discount(int)","description":"Operation Order.discount(int).","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[{"word":"discount","in":["discount"],"concern":"domain","sense":"discount","meaning":"discount in Order.discount(int).","confidence":0.5},{"word":"percent","in":["percent"],"concern":"domain","sense":"percent","meaning":"percent in Order.discount(int).","confidence":0.5}],"confidence":0.5},"fingerprint":"5fe6bc6e87876a1d8bbcac9c4982f553cef2ace8f8883bf7cc0906e7a701a446","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order/OrderService.(com.megacorp.ledger.LedgerClient)","key":{"lang":"java","module":"com.acme.order","symbol":"OrderService.(com.megacorp.ledger.LedgerClient)"},"level":"operation","kind":"constructor","file":"com/acme/order/OrderService.java","origin":"template","block":{"name":"OrderService","description":"Constructor: assigns the fields of `OrderService` (`ledger`).","safe":false,"idempotent":false,"owner":"unknown","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":["ledger"],"confidence":1},"fingerprint":"4c19d1e3356edfc95e1eaf604cf562ecf45d19b071691f83b689606565b6d84b"} {"t":"i","id":"java:com.acme.order/OrderService.archive(com.acme.order.legacy.List)","key":{"lang":"java","module":"com.acme.order","symbol":"OrderService.archive(com.acme.order.legacy.List)"},"level":"operation","kind":"method","name":"archive","file":"com/acme/order/OrderService.java","origin":"llm","block":{"name":"OrderService.archive(com.acme.order.legacy.List)","description":"Operation OrderService.archive(com.acme.order.legacy.List).","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[{"word":"archive","in":["archive"],"concern":"domain","sense":"archive","meaning":"archive in OrderService.archive(com.acme.order.legacy.List).","confidence":0.5},{"word":"orders","in":["orders"],"concern":"domain","sense":"orders","meaning":"orders in OrderService.archive(com.acme.order.legacy.List).","confidence":0.5}],"confidence":0.5},"fingerprint":"c7a45fd599ddd35399035f33ef88b553c3c5f42d7bf9164d57d994efc1002102","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} -{"t":"i","id":"java:com.acme.order/OrderService.archive(java.util.List)","key":{"lang":"java","module":"com.acme.order","symbol":"OrderService.archive(java.util.List)"},"level":"operation","kind":"method","name":"archive","file":"com/acme/order/OrderService.java","origin":"llm","block":{"name":"OrderService.archive(java.util.List)","description":"Operation OrderService.archive(java.util.List).","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[{"word":"archive","in":["archive"],"concern":"domain","sense":"archive","meaning":"archive in OrderService.archive(java.util.List).","confidence":0.5},{"word":"orders","in":["orders"],"concern":"domain","sense":"orders","meaning":"orders in OrderService.archive(java.util.List).","confidence":0.5}],"confidence":0.5},"fingerprint":"5014c95fd755888907ec4b1f8148ba250f81792cc80046234f8efc6562489979","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} +{"t":"i","id":"java:com.acme.order/OrderService.archive(java.util.List)","key":{"lang":"java","module":"com.acme.order","symbol":"OrderService.archive(java.util.List)"},"level":"operation","kind":"method","name":"archive","file":"com/acme/order/OrderService.java","origin":"llm","block":{"name":"OrderService.archive(java.util.List)","description":"Operation OrderService.archive(java.util.List).","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[{"word":"archive","in":["archive"],"concern":"domain","sense":"archive","meaning":"archive in OrderService.archive(java.util.List).","confidence":0.5},{"word":"orders","in":["orders"],"concern":"domain","sense":"orders","meaning":"orders in OrderService.archive(java.util.List).","confidence":0.5}],"confidence":0.5},"fingerprint":"67f96bfbaa187e7769386b919ae013be2d0995232a8df18efcb4a823e4b412fd","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order/OrderService.bill(com.acme.order.Order)","key":{"lang":"java","module":"com.acme.order","symbol":"OrderService.bill(com.acme.order.Order)"},"level":"operation","kind":"method","name":"bill","file":"com/acme/order/OrderService.java","origin":"llm","block":{"name":"OrderService.bill(com.acme.order.Order)","description":"Operation OrderService.bill(com.acme.order.Order).","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[{"word":"bill","in":["bill"],"concern":"domain","sense":"bill","meaning":"bill in OrderService.bill(com.acme.order.Order).","confidence":0.5},{"word":"order","in":["order"],"concern":"domain","sense":"order","meaning":"order in OrderService.bill(com.acme.order.Order).","confidence":0.5}],"confidence":0.5},"fingerprint":"c229926c94a504cfc95904666c6a13e450cb391710008f7d9f71070ad660dbbd","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order/Priceable.price()","key":{"lang":"java","module":"com.acme.order","symbol":"Priceable.price()"},"level":"operation","kind":"method","name":"price","file":"com/acme/order/Priceable.java","origin":"llm","block":{"name":"Priceable.price()","description":"Operation Priceable.price().","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[{"word":"price","in":["price"],"concern":"domain","sense":"price","meaning":"price in Priceable.price().","confidence":0.5}],"confidence":0.5},"fingerprint":"7e5506cf9483f4e1b1f55759c3b7783d0afe292fbff3b9787cac902755fb5ed8","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order/Reporting.()","key":{"lang":"java","module":"com.acme.order","symbol":"Reporting.()"},"level":"operation","kind":"constructor","file":"com/acme/order/Reporting.java","origin":"llm","block":{"name":"Reporting.()","description":"Operation Reporting.().","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[],"confidence":0.5},"fingerprint":"1d8a615d24bf79a35116455d5ec431c034522679ae4089bd9e219ca5a7d4b0e6","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} @@ -71,11 +71,11 @@ {"t":"i","id":"java:com.acme.order/Money","key":{"lang":"java","module":"com.acme.order","symbol":"Money"},"level":"type","kind":"record","name":"Money","file":"com/acme/order/Money.java","scc":["java:com.acme.order/Money","java:com.acme.order/Priceable"],"origin":"llm","block":{"name":"Money","description":"Type Money.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"money","in":["Money"],"concern":"domain","sense":"money","meaning":"money in Money.","confidence":0.5},{"word":"cents","in":["cents"],"concern":"domain","sense":"cents","meaning":"cents in Money.","confidence":0.5}],"confidence":0.5},"fingerprint":"4637eb55fc5ad7c3eaee40d04513148eb745ccdf267da3bfc76394dfb819a372","model":"openai/gpt-5.6-luna","usage":{"promptTokens":500,"completionTokens":32,"cost":0.0001220703125}} {"t":"i","id":"java:com.acme.order/Notifications","key":{"lang":"java","module":"com.acme.order","symbol":"Notifications"},"level":"type","kind":"class","name":"Notifications","file":"com/acme/order/Notifications.java","origin":"llm","block":{"name":"Notifications","description":"Type Notifications.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"notifications","in":["Notifications"],"concern":"domain","sense":"notifications","meaning":"notifications in Notifications.","confidence":0.5},{"word":"shipped","in":["onShipped"],"concern":"domain","sense":"shipped","meaning":"shipped in Notifications.","confidence":0.5}],"confidence":0.5},"fingerprint":"938722ac874b3c355882f97c303b53758fb10f46990a79fa2a93cfb9e87894a8","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order/Order","key":{"lang":"java","module":"com.acme.order","symbol":"Order"},"level":"type","kind":"class","name":"Order","file":"com/acme/order/Order.java","origin":"llm","block":{"name":"Order","description":"Type Order.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"order","in":["Order"],"concern":"domain","sense":"order","meaning":"order in Order.","confidence":0.5},{"word":"max","in":["MAX_LINES"],"concern":"domain","sense":"max","meaning":"max in Order.","confidence":0.5},{"word":"lines","in":["MAX_LINES"],"concern":"domain","sense":"lines","meaning":"lines in Order.","confidence":0.5},{"word":"channel","in":["channel"],"concern":"domain","sense":"channel","meaning":"channel in Order.","confidence":0.5},{"word":"trail","in":["trail"],"concern":"domain","sense":"trail","meaning":"trail in Order.","confidence":0.5}],"confidence":0.5},"fingerprint":"e64326dad720bbc3f977e69e23cb1c9689b9fc3f2b4be0abb5c76df4065a362e","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} -{"t":"i","id":"java:com.acme.order/OrderService","key":{"lang":"java","module":"com.acme.order","symbol":"OrderService"},"level":"type","kind":"class","name":"OrderService","file":"com/acme/order/OrderService.java","origin":"llm","block":{"name":"OrderService","description":"Type OrderService.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"order","in":["OrderService"],"concern":"domain","sense":"order","meaning":"order in OrderService.","confidence":0.5},{"word":"service","in":["OrderService"],"concern":"domain","sense":"service","meaning":"service in OrderService.","confidence":0.5},{"word":"ledger","in":["ledger"],"concern":"domain","sense":"ledger","meaning":"ledger in OrderService.","confidence":0.5}],"confidence":0.5},"fingerprint":"6bf7da2e7e2e475d56b72e3f4e1a71b096e7ffa4f248a45619a4340b1fca165e","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} +{"t":"i","id":"java:com.acme.order/OrderService","key":{"lang":"java","module":"com.acme.order","symbol":"OrderService"},"level":"type","kind":"class","name":"OrderService","file":"com/acme/order/OrderService.java","origin":"llm","block":{"name":"OrderService","description":"Type OrderService.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"order","in":["OrderService"],"concern":"domain","sense":"order","meaning":"order in OrderService.","confidence":0.5},{"word":"service","in":["OrderService"],"concern":"domain","sense":"service","meaning":"service in OrderService.","confidence":0.5},{"word":"ledger","in":["ledger"],"concern":"domain","sense":"ledger","meaning":"ledger in OrderService.","confidence":0.5}],"confidence":0.5},"fingerprint":"7a9db040b2a6d715ac35e3407cf8c035cc19a65d60d610191bc5015fa38bdcb9","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order/Priceable","key":{"lang":"java","module":"com.acme.order","symbol":"Priceable"},"level":"type","kind":"interface","name":"Priceable","file":"com/acme/order/Priceable.java","scc":["java:com.acme.order/Money","java:com.acme.order/Priceable"],"origin":"llm","block":{"name":"Priceable","description":"Type Priceable.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"priceable","in":["Priceable"],"concern":"domain","sense":"priceable","meaning":"priceable in Priceable.","confidence":0.5}],"confidence":0.5},"fingerprint":"4637eb55fc5ad7c3eaee40d04513148eb745ccdf267da3bfc76394dfb819a372","model":"openai/gpt-5.6-luna","usage":{"promptTokens":500,"completionTokens":32,"cost":0.0001220703125}} {"t":"i","id":"java:com.acme.order/Reporting","key":{"lang":"java","module":"com.acme.order","symbol":"Reporting"},"level":"type","kind":"class","name":"Reporting","file":"com/acme/order/Reporting.java","origin":"llm","block":{"name":"Reporting","description":"Type Reporting.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"reporting","in":["Reporting"],"concern":"domain","sense":"reporting","meaning":"reporting in Reporting.","confidence":0.5}],"confidence":0.5},"fingerprint":"59fccba95d1271f51f41a77609dc338697c72e76ecf6be77b7038e2b7bf2946d","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order/StockGuard","key":{"lang":"java","module":"com.acme.order","symbol":"StockGuard"},"level":"type","kind":"class","name":"StockGuard","file":"com/acme/order/StockGuard.java","origin":"llm","block":{"name":"StockGuard","description":"Type StockGuard.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"stock","in":["StockGuard"],"concern":"domain","sense":"stock","meaning":"stock in StockGuard.","confidence":0.5},{"word":"guard","in":["StockGuard"],"concern":"domain","sense":"guard","meaning":"guard in StockGuard.","confidence":0.5}],"confidence":0.5},"fingerprint":"0f066f5f08784d5f56ae32aa795c13d767d9f251c3512d72cb14b409e633b464","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} -{"t":"i","id":"java:com.acme.order","key":{"lang":"java","module":"com.acme.order","symbol":""},"level":"module","kind":"package","name":"com.acme.order","origin":"llm","block":{"name":"java:com.acme.order","description":"Module java:com.acme.order.","apis":[],"spis":[],"dependsOn":[],"concepts":[],"boundedContextHint":null,"sharedKernelHint":null,"ubiquitousLanguage":[],"words":[{"word":"order","in":["com.acme.order"],"concern":"domain","sense":"order","meaning":"order in java:com.acme.order.","confidence":0.5}],"glossary":[{"word":"order","concern":"domain","sense":"order","meaning":"order in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"basket","concern":"domain","sense":"basket","meaning":"basket in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"channel","concern":"domain","sense":"channel","meaning":"channel in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"discount","concern":"domain","sense":"discount","meaning":"discount in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"cursor","concern":"domain","sense":"cursor","meaning":"cursor in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"lines","concern":"domain","sense":"lines","meaning":"lines in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"total","concern":"domain","sense":"total","meaning":"total in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"reference","concern":"domain","sense":"reference","meaning":"reference in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"amount","concern":"domain","sense":"amount","meaning":"amount in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"line","concern":"domain","sense":"line","meaning":"line in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"audited","concern":"domain","sense":"audited","meaning":"audited in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"batch","concern":"domain","sense":"batch","meaning":"batch in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"cents","concern":"domain","sense":"cents","meaning":"cents in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"discountable","concern":"domain","sense":"discountable","meaning":"discountable in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"empty","concern":"domain","sense":"empty","meaning":"empty in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"exception","concern":"domain","sense":"exception","meaning":"exception in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"guard","concern":"domain","sense":"guard","meaning":"guard in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"money","concern":"domain","sense":"money","meaning":"money in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"notifications","concern":"domain","sense":"notifications","meaning":"notifications in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"priceable","concern":"domain","sense":"priceable","meaning":"priceable in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"reporting","concern":"domain","sense":"reporting","meaning":"reporting in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"service","concern":"domain","sense":"service","meaning":"service in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"stock","concern":"domain","sense":"stock","meaning":"stock in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"max","concern":"domain","sense":"max","meaning":"max in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"shipped","concern":"domain","sense":"shipped","meaning":"shipped in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"counts","concern":"domain","sense":"counts","meaning":"counts in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"ledger","concern":"domain","sense":"ledger","meaning":"ledger in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"prices","concern":"domain","sense":"prices","meaning":"prices in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"index","concern":"domain","sense":"index","meaning":"index in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"phone","concern":"domain","sense":"phone","meaning":"phone in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"store","concern":"domain","sense":"store","meaning":"store in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"trail","concern":"domain","sense":"trail","meaning":"trail in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"web","concern":"domain","sense":"web","meaning":"web in java:com.acme.order.","polysemous":false,"senses":[]}],"confidence":0.5},"fingerprint":"6687324da963a818b521bac404ffdd5252700b36ab84c9de9e93cd0dbf6582f5","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} +{"t":"i","id":"java:com.acme.order","key":{"lang":"java","module":"com.acme.order","symbol":""},"level":"module","kind":"package","name":"com.acme.order","origin":"llm","block":{"name":"java:com.acme.order","description":"Module java:com.acme.order.","apis":[],"spis":[],"dependsOn":[],"concepts":[],"boundedContextHint":null,"sharedKernelHint":null,"ubiquitousLanguage":[],"words":[{"word":"order","in":["com.acme.order"],"concern":"domain","sense":"order","meaning":"order in java:com.acme.order.","confidence":0.5}],"glossary":[{"word":"order","concern":"domain","sense":"order","meaning":"order in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"basket","concern":"domain","sense":"basket","meaning":"basket in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"channel","concern":"domain","sense":"channel","meaning":"channel in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"discount","concern":"domain","sense":"discount","meaning":"discount in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"cursor","concern":"domain","sense":"cursor","meaning":"cursor in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"lines","concern":"domain","sense":"lines","meaning":"lines in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"total","concern":"domain","sense":"total","meaning":"total in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"reference","concern":"domain","sense":"reference","meaning":"reference in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"amount","concern":"domain","sense":"amount","meaning":"amount in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"line","concern":"domain","sense":"line","meaning":"line in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"audited","concern":"domain","sense":"audited","meaning":"audited in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"batch","concern":"domain","sense":"batch","meaning":"batch in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"cents","concern":"domain","sense":"cents","meaning":"cents in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"discountable","concern":"domain","sense":"discountable","meaning":"discountable in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"empty","concern":"domain","sense":"empty","meaning":"empty in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"exception","concern":"domain","sense":"exception","meaning":"exception in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"guard","concern":"domain","sense":"guard","meaning":"guard in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"money","concern":"domain","sense":"money","meaning":"money in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"notifications","concern":"domain","sense":"notifications","meaning":"notifications in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"priceable","concern":"domain","sense":"priceable","meaning":"priceable in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"reporting","concern":"domain","sense":"reporting","meaning":"reporting in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"service","concern":"domain","sense":"service","meaning":"service in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"stock","concern":"domain","sense":"stock","meaning":"stock in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"max","concern":"domain","sense":"max","meaning":"max in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"shipped","concern":"domain","sense":"shipped","meaning":"shipped in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"counts","concern":"domain","sense":"counts","meaning":"counts in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"ledger","concern":"domain","sense":"ledger","meaning":"ledger in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"prices","concern":"domain","sense":"prices","meaning":"prices in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"index","concern":"domain","sense":"index","meaning":"index in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"phone","concern":"domain","sense":"phone","meaning":"phone in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"store","concern":"domain","sense":"store","meaning":"store in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"trail","concern":"domain","sense":"trail","meaning":"trail in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"web","concern":"domain","sense":"web","meaning":"web in java:com.acme.order.","polysemous":false,"senses":[]}],"confidence":0.5},"fingerprint":"03cf006e56357c42721222d6a86f06b5b84f899d1bbc1284651de1a5b52d8758","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order.adapter","key":{"lang":"java","module":"com.acme.order.adapter","symbol":""},"level":"module","kind":"package","name":"com.acme.order.adapter","origin":"llm","block":{"name":"java:com.acme.order.adapter","description":"Module java:com.acme.order.adapter.","apis":[],"spis":[],"dependsOn":[],"concepts":[],"boundedContextHint":null,"sharedKernelHint":null,"ubiquitousLanguage":[],"words":[{"word":"adapter","in":["com.acme.order.adapter"],"concern":"domain","sense":"adapter","meaning":"adapter in java:com.acme.order.adapter.","confidence":0.5}],"glossary":[{"word":"adapter","concern":"domain","sense":"adapter","meaning":"adapter in java:com.acme.order.adapter.","polysemous":false,"senses":[]},{"word":"ledger","concern":"domain","sense":"ledger","meaning":"ledger in java:com.acme.order.adapter.","polysemous":false,"senses":[]},{"word":"trail","concern":"domain","sense":"trail","meaning":"trail in java:com.acme.order.adapter.","polysemous":false,"senses":[]}],"confidence":0.5},"fingerprint":"cefb6fd8308187787e107595b7c9c371cabe8f28589d800396b0c69916f4496e","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order.legacy","key":{"lang":"java","module":"com.acme.order.legacy","symbol":""},"level":"module","kind":"package","name":"com.acme.order.legacy","origin":"llm","block":{"name":"java:com.acme.order.legacy","description":"Module java:com.acme.order.legacy.","apis":[],"spis":[],"dependsOn":[],"concepts":[],"boundedContextHint":null,"sharedKernelHint":null,"ubiquitousLanguage":[],"words":[{"word":"legacy","in":["com.acme.order.legacy"],"concern":"domain","sense":"legacy","meaning":"legacy in java:com.acme.order.legacy.","confidence":0.5}],"glossary":[{"word":"head","concern":"domain","sense":"head","meaning":"head in java:com.acme.order.legacy.","polysemous":false,"senses":[]},{"word":"list","concern":"domain","sense":"list","meaning":"list in java:com.acme.order.legacy.","polysemous":false,"senses":[]},{"word":"tail","concern":"domain","sense":"tail","meaning":"tail in java:com.acme.order.legacy.","polysemous":false,"senses":[]}],"confidence":0.5},"fingerprint":"35a959fc1c2d2ae9863563dced8e8aa22718ed45ce4af6b0f57140b45aeceb53","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"eof","counts":{"records":79,"llm":70,"template":9,"reused":0,"failed":0},"usage":{"promptTokens":68000,"completionTokens":4352,"cost":0.0166015625},"generatedAt":"2026-11-21T00:00:00.000Z"} diff --git a/packages/cli/test/golden/explain/java/plan.jsonl b/packages/cli/test/golden/explain/java/plan.jsonl index 868bc11c..5a801807 100644 --- a/packages/cli/test/golden/explain/java/plan.jsonl +++ b/packages/cli/test/golden/explain/java/plan.jsonl @@ -1,4 +1,4 @@ -{"kind":"codegraph.explainPlan/1","models":{"leaf":"openai/gpt-5.6-luna","rollup":"openai/gpt-5.6-luna"},"depth":1,"estimates":{"calls":68,"promptTokens":114149,"completionTokens":52415,"byLevel":{"operation":{"calls":48,"promptTokens":78159,"completionTokens":30120,"units":57},"type":{"calls":17,"promptTokens":31000,"completionTokens":15470,"units":17},"module":{"calls":3,"promptTokens":4990,"completionTokens":6825,"units":3}},"byStatus":{"llm":68,"template":9,"reuse":0,"skip-scope":0,"skip-budget":0}},"steps":"77 steps, one per line below"} +{"kind":"codegraph.explainPlan/1","models":{"leaf":"openai/gpt-5.6-luna","rollup":"openai/gpt-5.6-luna"},"depth":1,"estimates":{"calls":68,"promptTokens":114154,"completionTokens":52415,"byLevel":{"operation":{"calls":48,"promptTokens":78161,"completionTokens":30120,"units":57},"type":{"calls":17,"promptTokens":31003,"completionTokens":15470,"units":17},"module":{"calls":3,"promptTokens":4990,"completionTokens":6825,"units":3}},"byStatus":{"llm":68,"template":9,"reuse":0,"skip-scope":0,"skip-budget":0}},"steps":"77 steps, one per line below"} {"id":"java:com.acme.order.adapter/LedgerAdapter.()","level":"operation","members":["java:com.acme.order.adapter/LedgerAdapter.()"],"layer":0,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1599} {"id":"java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)","level":"operation","members":["java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)"],"layer":0,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1647} {"id":"java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List)","level":"operation","members":["java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List)"],"layer":0,"status":"template","model":"openai/gpt-5.6-luna","calls":0,"promptTokens":0} @@ -51,7 +51,7 @@ {"id":"java:com.acme.order/Money.zero()","level":"operation","members":["java:com.acme.order/Money.zero()"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1597} {"id":"java:com.acme.order/Notifications.both(com.acme.order.Order)","level":"operation","members":["java:com.acme.order/Notifications.both(com.acme.order.Order)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1722} {"id":"java:com.acme.order/OrderService.archive(com.acme.order.legacy.List)","level":"operation","members":["java:com.acme.order/OrderService.archive(com.acme.order.legacy.List)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1647} -{"id":"java:com.acme.order/OrderService.archive(java.util.List)","level":"operation","members":["java:com.acme.order/OrderService.archive(java.util.List)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1657} +{"id":"java:com.acme.order/OrderService.archive(java.util.List)","level":"operation","members":["java:com.acme.order/OrderService.archive(java.util.List)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1659} {"id":"java:com.acme.order/OrderService.bill(com.acme.order.Order)","level":"operation","members":["java:com.acme.order/OrderService.bill(com.acme.order.Order)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1665} {"id":"java:com.acme.order/StockGuard.ensure(int)","level":"operation","members":["java:com.acme.order/StockGuard.ensure(int)"],"layer":1,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1726} {"id":"java:com.acme.order.adapter","level":"module","members":["java:com.acme.order.adapter"],"layer":2,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1573} @@ -74,5 +74,5 @@ {"id":"java:com.acme.order/Order.(java.lang.String)","level":"operation","members":["java:com.acme.order/Order.(java.lang.String)"],"layer":4,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1653} {"id":"java:com.acme.order/Order","level":"type","members":["java:com.acme.order/Order"],"layer":5,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1992} {"id":"java:com.acme.order/Notifications","level":"type","members":["java:com.acme.order/Notifications"],"layer":6,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":2001} -{"id":"java:com.acme.order/OrderService","level":"type","members":["java:com.acme.order/OrderService"],"layer":6,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1894} +{"id":"java:com.acme.order/OrderService","level":"type","members":["java:com.acme.order/OrderService"],"layer":6,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1897} {"id":"java:com.acme.order","level":"module","members":["java:com.acme.order"],"layer":7,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1861} diff --git a/packages/cli/test/golden/explain/java/prompts-planned.sha256 b/packages/cli/test/golden/explain/java/prompts-planned.sha256 index ff6f5a78..17edf013 100644 --- a/packages/cli/test/golden/explain/java/prompts-planned.sha256 +++ b/packages/cli/test/golden/explain/java/prompts-planned.sha256 @@ -41,7 +41,7 @@ 41 operation java:com.acme.order/Money.zero() codegraph_operation system=dc45667c9ad4bd03 user=aee9e00d5e24ca215d84f50ebda5bdff1e5947ab195087278596a463e13b7723 42 operation java:com.acme.order/Notifications.both(com.acme.order.Order) codegraph_operation system=dc45667c9ad4bd03 user=32571dd9bff8b75172864835154c55e89744eb6951f639781d681c338371e255 43 operation java:com.acme.order/OrderService.archive(com.acme.order.legacy.List) codegraph_operation system=dc45667c9ad4bd03 user=1e60cd4b8718744ce7eb6f5e94644d829b8edd7faa52726ee5f199455e2be858 -44 operation java:com.acme.order/OrderService.archive(java.util.List) codegraph_operation system=dc45667c9ad4bd03 user=91adbae821d924845e5a965c37229d3ff65ba8b7639d7f7b7e2a5fb18e1e32e8 +44 operation java:com.acme.order/OrderService.archive(java.util.List) codegraph_operation system=dc45667c9ad4bd03 user=301d0594619a8fc35301392b0c7301554b6303fb3b158f400b4dda172c7da25c 45 operation java:com.acme.order/OrderService.bill(com.acme.order.Order) codegraph_operation system=dc45667c9ad4bd03 user=2ae28bed2aa2f0609532128dd1f6fc9a06b931efce336fcb07420fa23044aa15 46 operation java:com.acme.order/StockGuard.ensure(int) codegraph_operation system=dc45667c9ad4bd03 user=eb81427168996cf491d2843da738fa2eb20f881f801db6acc8eed7405bfb030c 47 module java:com.acme.order.adapter codegraph_module system=206d67daaf006b8b user=e9988aa1b80f0bd816e94e4ab95bdd147f0ae28ffa92459b089091f60eaef46b @@ -64,5 +64,5 @@ 64 operation java:com.acme.order/Order.(java.lang.String) codegraph_operation system=dc45667c9ad4bd03 user=d6fb0f18ee27bd33e2fce2017a61c20c4a96bf967b867d57118e516b98c6ee3b 65 type java:com.acme.order/Order codegraph_type system=e269e40492f79aa0 user=e7f2acd241150b6e05fa2b206094c298517e765e4dd7fef4580099973e3f190d 66 type java:com.acme.order/Notifications codegraph_type system=e269e40492f79aa0 user=8d030919e5f5ced8ed6b25711453f6873e0f5dd7c6cb77c1981c4f37b48d1e10 -67 type java:com.acme.order/OrderService codegraph_type system=e269e40492f79aa0 user=00c1d217f20ec040d378437a9486600b64ece7e9014c00d4e81560c71d8b7f95 +67 type java:com.acme.order/OrderService codegraph_type system=e269e40492f79aa0 user=a08f995f398cd4c669761747ab34be97e25a4c197d44a8c8de993ef81c981e70 68 module java:com.acme.order codegraph_module system=206d67daaf006b8b user=18bf502cb7b14f291723df6d3c55b9412154c79a841897bd4374451d374270a3 diff --git a/packages/cli/test/golden/explain/java/prompts.txt b/packages/cli/test/golden/explain/java/prompts.txt index 2aff845b..567ce93b 100644 --- a/packages/cli/test/golden/explain/java/prompts.txt +++ b/packages/cli/test/golden/explain/java/prompts.txt @@ -1195,7 +1195,7 @@ archive(java.util.List) metrics: cyclomatic=2, sloc=5 Source (com/acme/order/OrderService.java:23-27): ````java - public void archive(java.util.List orders) { + public void archive(java.util.List orders) { for (Order order : orders) { ledger.archive(order.reference()); } @@ -2201,7 +2201,7 @@ public class OrderService { return invoice; } - public void archive(java.util.List orders) { + public void archive(java.util.List orders) { for (Order order : orders) { ledger.archive(order.reference()); } diff --git a/packages/cli/test/golden/explain/java/units.txt b/packages/cli/test/golden/explain/java/units.txt index 5cfa5f84..6194c327 100644 --- a/packages/cli/test/golden/explain/java/units.txt +++ b/packages/cli/test/golden/explain/java/units.txt @@ -50,7 +50,7 @@ operation java:com.acme.order/Money.times(int) llm fingerprint=da2326b64ebfdfdac operation java:com.acme.order/Money.zero() llm fingerprint=a364a12d92a26fc10d2750b6bc3a7c42cc9bb0329fb7d641693f67acd77b35c0 chain=49a13a1b5fef7c37d39ff08ab1814c307423699f62a3a640858e5649d664ed65 stamped=9d176eea263a1cf1f0b2cc8afab78f1b8077dcabb293be3020e5ebdda542f64b operation java:com.acme.order/Notifications.both(com.acme.order.Order) llm fingerprint=2695f482c2ba36c746e569ac866c178aa8f111c6ab106f40ce17963618f49a56 chain=2c28d39958216d9fa7390060df2f77e0d5b8b1f520dc4398253bdfe4c61f7622 stamped=405f9cfe0b1561c89a92082037728406a39bc3f04fabad062acbc68bc41e84ae operation java:com.acme.order/OrderService.archive(com.acme.order.legacy.List) llm fingerprint=c7a45fd599ddd35399035f33ef88b553c3c5f42d7bf9164d57d994efc1002102 chain=7483d17eac5d40a6454cf75c675e932a05a3db00a78da9c038fdf347b77e29ac stamped=8dc0338829527ea4e7cbc4fb6d582489294d6afa9a8d852d5b0c736d98d0f1d9 -operation java:com.acme.order/OrderService.archive(java.util.List) llm fingerprint=5014c95fd755888907ec4b1f8148ba250f81792cc80046234f8efc6562489979 chain=de018c799d2b0031de3a25a2d444af86dc9365fa768e2f3bcccaa92f02efa147 stamped=22ec4347bac0df33543ed198bc351418e00c8a4fbb029dbf8ca0564e0cc6349c +operation java:com.acme.order/OrderService.archive(java.util.List) llm fingerprint=67f96bfbaa187e7769386b919ae013be2d0995232a8df18efcb4a823e4b412fd chain=343cde3675d5b3513cb0f8baf9a0e0cba18f95c803fb715148791eedd1989cbe stamped=64797cccaba1f498d71be99c8c973843c27f8836d63ae36bbaf3b186cc4fed7a operation java:com.acme.order/OrderService.bill(com.acme.order.Order) llm fingerprint=c229926c94a504cfc95904666c6a13e450cb391710008f7d9f71070ad660dbbd chain=ae243cd612510f274a13ed96f983bacc0470236e7d57b0b6f5bfb0f826ac88ee stamped=c23efc407657d4bf30d8a526d82578f2295bb4a396962f6274eabfc8ee01d6e9 operation java:com.acme.order/StockGuard.ensure(int) llm fingerprint=4b670b6e7e7cd2270199477474ed04bda7ec1eea956f520921ab25af7e9c6787 chain=56372d54bdadac7dd6fc038fafddde2ba5f24f753ec0d220e362708aa6806fbc stamped=2d1c4136a0e310922e00980d8db38d9c43a6d242a44242e731ded007c0543176 module java:com.acme.order.adapter llm fingerprint=cefb6fd8308187787e107595b7c9c371cabe8f28589d800396b0c69916f4496e chain=ff47c9fe75385ca90db5b32647424d2fad301757661a0f1453d311f1878b30a4 stamped=72f4ce44c00f52bf9383124dbdfc9359ce7924210e861f6e20c9d74483c36bf0 @@ -73,5 +73,5 @@ type java:com.acme.order/AbstractOrder llm fingerprint=207ca5d95fab853c713af0ac3 operation java:com.acme.order/Order.(java.lang.String) llm fingerprint=7410566c6f499ccd66812de9028828206bd391a2800cf9c7b94de470a128d899 chain=80b8f5ff1bf86e47457e843263bbb1a0319ed43e52057811adb186b533c8c0d9 stamped=b13141fff0fe439638433e527b8320614e995b0f7fa4e25d61031adbf9b60edc type java:com.acme.order/Order llm fingerprint=e64326dad720bbc3f977e69e23cb1c9689b9fc3f2b4be0abb5c76df4065a362e chain=2036f6aa3d3444362846531aa056881fff5ca0b59032dbfa56f9461d4874f7f9 stamped=4ac567f3b61b1f04b82fc8a1bc9b152b1413930fafa5094ec89b7538fbeef1de type java:com.acme.order/Notifications llm fingerprint=938722ac874b3c355882f97c303b53758fb10f46990a79fa2a93cfb9e87894a8 chain=acdce7dd25408b0f4a6315a0199dee914426a7ee7f1e17ca3d165ac7b519ca59 stamped=5504d2bd67a3391f0a12309dc934af3960510f3a978349d77ad821021d6064ed -type java:com.acme.order/OrderService llm fingerprint=6bf7da2e7e2e475d56b72e3f4e1a71b096e7ffa4f248a45619a4340b1fca165e chain=4626d27e8f44cde8d841500c7c6550161651ee0c9f18a8bc279a91e37e649f01 stamped=5134c03d2bb7c5135b7285e5134086a34f34f6a15053606f90546679e3f99833 -module java:com.acme.order llm fingerprint=6687324da963a818b521bac404ffdd5252700b36ab84c9de9e93cd0dbf6582f5 chain=cabca33f124b8fa40e1d034de638c2ab92c55e4856e88d663e640aef5473558a stamped=2ce927d45590eee9430d7f28fd05e557d7d8f965c91ac2efdcbbf0a3d427cf1f +type java:com.acme.order/OrderService llm fingerprint=7a9db040b2a6d715ac35e3407cf8c035cc19a65d60d610191bc5015fa38bdcb9 chain=a295cbb1151c475d70935de8cabfd948c94710ae1cb012777f1dba0471202142 stamped=4559c489b167f10c19eb9ba03964e6055b91e85205e129b99cf6cc3f54907c14 +module java:com.acme.order llm fingerprint=03cf006e56357c42721222d6a86f06b5b84f899d1bbc1284651de1a5b52d8758 chain=d07feadce7a6f9fd2d25c333219d846d2655f022df12f878955bb628d202d5e7 stamped=a5cc6430a3599cdeb43aea8199ad03b8fd5339f390a9dc533934e7da8c9f07e2 diff --git a/packages/core/src/container-contract.ts b/packages/core/src/container-contract.ts index 494e70e7..5e8b1d44 100644 --- a/packages/core/src/container-contract.ts +++ b/packages/core/src/container-contract.ts @@ -110,6 +110,14 @@ ${rows} | \`f\`, \`o\` | every edge record | surrogate | | \`candidates\` | edge record | array of surrogates | +Two keys hold a TREE rather than a reference, and every id inside the tree is a +surrogate by the same rule: \`value\` (\`TWithValue\`, a \`$defs/Literal\`; its +\`enum\`, \`type\` and \`annotation\` forms name a type) with an edge's +\`arguments\`, and \`typeExpr\` (\`TTypedEntity\`, since 1.2.0, a +\`$defs/TypeExpr\`; its \`named\` form names a type in \`type\`). Closure reaches +inside both: a surrogate in a tree that resolves to no entity is an error like +any other. + Surrogates are **file-scoped and not identity**: they are assigned by canonical order, so they change whenever the model changes, and they must never be stored outside the file that assigned them or compared across files. Joining two models @@ -138,7 +146,7 @@ function traitKeys(): string { An entity record carries **exactly** the keys its declared traits contribute: present when the trait is declared, absent when it is not. Optional-valued keys -(\`declaredType\`) may be absent even when their trait is declared. +(\`declaredType\`, \`typeExpr\`) may be absent even when their trait is declared. | trait | keys on the wire | | |---|---|---| @@ -175,6 +183,11 @@ A conforming file satisfies all of: an \`invocation\`, \`access\` or \`reference\` edge whose \`o\` is a stub. A member of a corpus entity is an entity, and the edge points at it. The member is a string, never a reference: no entity is made for it. +- **A receiver only where a member needs an instance** (since 1.2.0) — an + edge's \`receiver\` (\`"self"\` through the accessor's own receiver, written or + implied; \`"other"\` through any other expression) is legal only on an + \`access\` edge whose \`o\` is **not** a stub: a stub has no members, so the + model holds nothing a receiver could be about. - **Counts** — \`eof.counts\` states how many \`f\`, \`e\` and \`x\` records were written. A reader that reaches end-of-input without an \`eof\`, or whose tallies disagree with it, must reject the file: that is how a truncated or killed run @@ -191,10 +204,13 @@ Entities are sorted by natural key — \`lang\`, then \`module\`, then \`symbol\ order **is** the surrogate assignment. Edges follow, sorted by \`f\`, then \`o\`, then edge kind, then anchor -(file, start, end), then provenance, then \`member\` with the absent one first -(UTF-16 code units). Within an edge record the keys are written \`t\`, \`k\`, -\`f\`, \`o\`, \`p\`, then \`member\`, \`candidates\`, \`arguments\`, \`isRead\`, -\`isWrite\`, \`sourceFile\`, \`anchor\` — each optional key only when present. +(file, start, end), then provenance, then \`member\`, then \`receiver\` — each of +the last two with the absent one first, then by UTF-16 code units. Within an +edge record the keys are written \`t\`, \`k\`, \`f\`, \`o\`, \`p\`, then \`member\`, +\`candidates\`, \`arguments\`, \`isRead\`, \`isWrite\`, \`receiver\`, \`sourceFile\`, +\`anchor\` — each optional key only when present. Inside a \`typeExpr\` the keys +are written \`k\` first, then the form's own in the order \`$defs/TypeExpr\` +lists them; nothing inside a tree is sorted, since written order is a fact. File records are sorted by path; dictionary entries are sorted. diff --git a/packages/core/src/edges.ts b/packages/core/src/edges.ts index 6db06fe8..e5508904 100644 --- a/packages/core/src/edges.ts +++ b/packages/core/src/edges.ts @@ -19,6 +19,8 @@ const edgeBase = { sourceFile: z.string().min(1).optional(), // Refused rather than stripped on every kind but the three below (MM-6). member: z.never().optional(), + // Refused rather than stripped on every kind but `access` (MM-8). + receiver: z.never().optional(), }; /** @@ -31,6 +33,18 @@ const edgeBase = { export const MEMBER_EDGE_KINDS = ["invocation", "access", "reference"] as const; const member = { member: z.string().min(1).optional() }; +/** + * MM-8: how an access reached its target. `self` — through the accessor's own + * receiver, written (`this.lines`) or implied (`lines`); `other` — through any + * other expression (`other.lines`). Absent when the target has no receiver, or + * when the extractor does not say. Legal on `access` only; that the target is + * not a stub is `receiverViolations`'s to say, since it needs the entity. + */ +export const RECEIVER_EDGE_KINDS = ["access"] as const; +export const RECEIVERS = ["self", "other"] as const; +export const Receiver = z.enum(RECEIVERS); +export type Receiver = z.infer; + /** Module → Module. The first-class cross-language comparison layer. */ export const ImportEdge = z.object({ edge: z.literal("import"), ...edgeBase }); @@ -53,6 +67,7 @@ export const AccessEdge = z.object({ ...member, isRead: z.boolean(), isWrite: z.boolean(), + receiver: Receiver.optional(), }); /** Entity → Type: type usage that is none of the other kinds (generics, casts, annotations). */ diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 959002a8..78d54de4 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -22,6 +22,9 @@ export * from "./entity.js"; // Written declaration-site values (METAMODEL.md §1.6). export * from "./literal.js"; +// Written types (METAMODEL.md §1.7, MM-7). +export * from "./type-expr.js"; + // The single relationship concept (METAMODEL.md §4). export * from "./edges.js"; diff --git a/packages/core/src/integrity.ts b/packages/core/src/integrity.ts index 190dfac5..d3d5ae54 100644 --- a/packages/core/src/integrity.ts +++ b/packages/core/src/integrity.ts @@ -1,7 +1,8 @@ import type { TraitName } from "./names.js"; import type { Entity } from "./entity.js"; -import { MEMBER_EDGE_KINDS, type Edge } from "./edges.js"; +import { MEMBER_EDGE_KINDS, RECEIVER_EDGE_KINDS, type Edge } from "./edges.js"; import { argumentReferences, literalReferences, type Literal } from "./literal.js"; +import { typeExprReferences, type TypeExpr } from "./type-expr.js"; import type { Model } from "./model.js"; /** @@ -53,6 +54,17 @@ function valueReferences(entity: Entity, index: number): UnknownReference[] { return literalReferences(value as Literal, `entities[${index}].value`); } +/** + * `TTypedEntity.typeExpr` (MM-7) is a tree for the same reason, and is walked + * the same way: its `declaredType` sibling stays in the table above. + */ +function typeExprRefs(entity: Entity, index: number): UnknownReference[] { + if (!entity.traits.includes("TTypedEntity")) return []; + const expr = (entity as unknown as Record)["typeExpr"]; + if (expr === undefined) return []; + return typeExprReferences(expr as TypeExpr, `entities[${index}].typeExpr`); +} + function entityReferences(entity: Entity, index: number): UnknownReference[] { const out: UnknownReference[] = []; const bag = entity as unknown as Record; @@ -97,6 +109,7 @@ export function references(model: Model): UnknownReference[] { model.entities.forEach((entity, i) => { out.push(...entityReferences(entity, i)); out.push(...valueReferences(entity, i)); + out.push(...typeExprRefs(entity, i)); }); model.edges.forEach((edge, i) => out.push(...edgeReferences(edge, i))); return out; @@ -147,6 +160,36 @@ export function memberViolations(model: Model): MemberViolation[] { return out; } +/** Why an edge may not carry its `receiver` (MM-8). */ +export type ReceiverViolationReason = "kind" | "target-stub"; + +export interface ReceiverViolation { + readonly path: string; + readonly edge: Edge; + readonly reason: ReceiverViolationReason; +} + +/** + * MM-8's rule: `receiver` present ⇒ the kind is `access` AND the target is not + * a stub. A stub has no members (METAMODEL.md §6), so nothing the model holds + * says the field reached needs an instance. A target this model does not + * declare is closure's finding, not this one's, so it is not reported twice. + */ +export function receiverViolations(model: Model): ReceiverViolation[] { + const stub = new Map(); + for (const entity of model.entities) { + stub.set(entity.id, (entity as unknown as Record)["isStub"] === true); + } + const out: ReceiverViolation[] = []; + model.edges.forEach((edge, index) => { + if (edge.receiver === undefined) return; + const path = `edges[${index}]`; + if (!(RECEIVER_EDGE_KINDS as readonly string[]).includes(edge.edge)) out.push({ path, edge, reason: "kind" }); + else if (stub.get(edge.to) === true) out.push({ path, edge, reason: "target-stub" }); + }); + return out; +} + /** Edges whose `from` equals its `to` — forbidden by METAMODEL.md §4. */ export function selfReferences(model: Model): { readonly path: string; readonly edge: Edge }[] { const out: { path: string; edge: Edge }[] = []; diff --git a/packages/core/src/jsonl.ts b/packages/core/src/jsonl.ts index fc53b2f9..0ffcacc5 100644 --- a/packages/core/src/jsonl.ts +++ b/packages/core/src/jsonl.ts @@ -3,6 +3,7 @@ import type { Edge } from "./edges.js"; import type { Entity } from "./entity.js"; import { ENTITY_REFERENCE_KEYS } from "./integrity.js"; import type { Literal, NamedArgument } from "./literal.js"; +import { mapTypeExpr, type TypeExpr } from "./type-expr.js"; import { type NaturalKey, compareNaturalKeys, naturalKeyIndex, parseRenderedId, renderId } from "./identity.js"; import type { EdgeKind, TraitName } from "./names.js"; import type { Model } from "./model.js"; @@ -18,6 +19,7 @@ import { type WireAnchor, type WireLiteral, type WireNamedArgument, + type WireTypeExpr, } from "./wire.js"; /** @@ -37,6 +39,8 @@ const ENTITY_KEY_ORDER = [ "name", "signature", "declaredType", + // MM-7: beside the erased head it refines. An entity without one writes the bytes it wrote before. + "typeExpr", "isStub", "parent", "attachedTo", @@ -50,8 +54,18 @@ const ENTITY_KEY_ORDER = [ "anchor", ] as const; -// `member` (MM-6) first: it qualifies `o`. An edge without one writes the bytes it wrote before. -const EDGE_KEY_ORDER = ["member", "candidates", "arguments", "isRead", "isWrite", "sourceFile", "anchor"] as const; +// `member` (MM-6) first: it qualifies `o`. `receiver` (MM-8) beside the access +// flags it qualifies. An edge without either writes the bytes it wrote before. +const EDGE_KEY_ORDER = [ + "member", + "candidates", + "arguments", + "isRead", + "isWrite", + "receiver", + "sourceFile", + "anchor", +] as const; /** The record's own fields — everything else on a line is an extension key. */ const ENTITY_RECORD_KEYS: readonly string[] = ["t", "i", "k", "tr", "m", "s", "d"]; @@ -67,6 +81,7 @@ const EDGE_RECORD_KEYS: readonly string[] = [ "arguments", "isRead", "isWrite", + "receiver", "sourceFile", ]; @@ -261,7 +276,10 @@ export function* encodeModel(model: Model): Generator { compareText(a.edge.provenance, b.edge.provenance) || // MM-6: two calls on one line to two members of one stub are two edges, // in one order. Absent sorts first, so an edge without one never moves. - compareMember(a.edge.member, b.edge.member), + compareOptional(a.edge.member, b.edge.member) || + // MM-8: `this.x = other.x` is a self and an other access at one site — + // two facts, in one order, by the same rule. + compareOptional(a.edge.receiver, b.edge.receiver), ); for (const { edge, f, o } of edges) { @@ -315,6 +333,10 @@ export function* encodeModel(model: Model): Generator { if (key === "value") { return encodeLiteral(value as Literal, (id) => ref(id, `${owner}.value`)); } + // A type expression is a tree of references too (MM-7, §1.7): same rule. + if (key === "typeExpr") { + return mapTypeExpr(value as TypeExpr, (id) => ref(id, `${owner}.typeExpr`)); + } if (key === "arguments") { return encodeArguments(value as readonly NamedArgument[], (id) => ref(id, `${owner}.arguments`), @@ -332,7 +354,8 @@ function compareText(a: string, b: string): number { return a < b ? -1 : a > b ? 1 : 0; } -function compareMember(a: string | undefined, b: string | undefined): number { +/** An optional text key as a sort key: absent first, then UTF-16 code units. */ +function compareOptional(a: string | undefined, b: string | undefined): number { if (a === undefined || b === undefined) return a === b ? 0 : a === undefined ? -1 : 1; return compareText(a, b); } @@ -414,6 +437,16 @@ function literalRefs(value: WireLiteral, out: number[] = []): number[] { } } +/** Every surrogate a type expression points at (MM-7) — what the reader checks closure against. */ +function typeExprRefs(expr: WireTypeExpr): number[] { + const out: number[] = []; + mapTypeExpr(expr, (ref) => { + out.push(ref); + return ref; + }); + return out; +} + /** The same, over an annotation use's argument list. */ function argumentRefs(args: readonly WireNamedArgument[]): number[] { const out: number[] = []; @@ -657,6 +690,11 @@ export class RecordReader { this.#noteEntityRef(ref, `entity ${record.i} value`); } } + if (record.typeExpr !== undefined) { + for (const ref of typeExprRefs(record.typeExpr)) { + this.#noteEntityRef(ref, `entity ${record.i} typeExpr`); + } + } this.#noteEntityRef(record.m, `entity ${record.i} module`); return record; } @@ -813,6 +851,9 @@ export class ModelBuilder { edge["arguments"] = decodeArguments(record.arguments ?? [], (ref) => this.#id(ref)); } if (record.member !== undefined) edge["member"] = record.member; + // Where the `Edge` schema's shape puts it (edgeBase declares the key, the + // access kind narrows it): a parsed and a decoded edge then agree key for key. + if (record.receiver !== undefined) edge["receiver"] = record.receiver; if (record.isRead !== undefined) edge["isRead"] = record.isRead; if (record.isWrite !== undefined) edge["isWrite"] = record.isWrite; if (record.sourceFile !== undefined) edge["sourceFile"] = this.#path(record.sourceFile); @@ -897,6 +938,7 @@ export class ModelBuilder { #decodeValue(key: string, value: unknown): unknown { if (key === "anchor") return this.#anchor(value as WireAnchor); if (key === "value") return decodeLiteral(value as WireLiteral, (ref) => this.#id(ref)); + if (key === "typeExpr") return mapTypeExpr(value as WireTypeExpr, (ref) => this.#id(ref)); if (key in PATH_KEYS) return (value as number[]).map((ref) => this.#path(ref)); const many = REF_KEYS.get(key); if (many === undefined) return value; diff --git a/packages/core/src/model.ts b/packages/core/src/model.ts index 1bed5e85..81685555 100644 --- a/packages/core/src/model.ts +++ b/packages/core/src/model.ts @@ -4,11 +4,12 @@ import { Entity } from "./entity.js"; /** * Version of the interchange contract carried by every model.json. 1.1.0 added - * the optional edge `member` (MM-6); a reader accepts any version it is - * handed, so a 1.0.0 file decodes unchanged, and an extractor states the - * version it writes. + * the optional edge `member` (MM-6); 1.2.0 the optional `typeExpr` of + * `TTypedEntity` (MM-7), the marker `TWithReceiver` and the optional access + * `receiver` (MM-8). A reader accepts any version it is handed, so a 1.1.0 or + * 1.0.0 file decodes unchanged, and an extractor states the version it writes. */ -export const SCHEMA_VERSION = "1.1.0"; +export const SCHEMA_VERSION = "1.2.0"; /** * Provenance of the model itself. Loose on purpose: extractor-specific flags diff --git a/packages/core/src/names.ts b/packages/core/src/names.ts index 385cfb2c..55eb18db 100644 --- a/packages/core/src/names.ts +++ b/packages/core/src/names.ts @@ -29,6 +29,8 @@ export const TRAIT_NAMES = [ // structure "TStructural", "TWithAccesses", + // A marker: evaluated against an instance of its type (METAMODEL.md §3.6, MM-8). + "TWithReceiver", // measures (METAMODEL.md §3.8) "TMetrics", // values (METAMODEL.md §3.6, §1.6) diff --git a/packages/core/src/profiles/clojure.ts b/packages/core/src/profiles/clojure.ts index 17dcbae4..234e231f 100644 --- a/packages/core/src/profiles/clojure.ts +++ b/packages/core/src/profiles/clojure.ts @@ -125,6 +125,7 @@ export const clojureProfile: Profile = { "Higher-order use of vars (`(map inc coll)`, `(partial f x)`) yields `reference` edges to the var, never `invocation` edges — the call happens elsewhere and its site is unknown.", "Runtime resolution (`resolve`, `requiring-resolve`, `eval`, `(var-get (ns-resolve ...))`) and dynamically computed `require` are static blind spots: no `import` or `invocation` edge is emitted for them.", "`:refer :all` and `:refer` bring vars into scope without qualification; the `import` edge is namespace -> namespace, so the module layer stays exact even when a symbol's origin needs var resolution.", + "MM-7 and MM-8 (contract 1.2.0) are not emitted by any extractor of this language (none ships) yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses `TWithReceiver` on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not \"no written type\", not \"no receiver\" (PLAN.md §26.10).", ], lexicon: { diff --git a/packages/core/src/profiles/csharp.ts b/packages/core/src/profiles/csharp.ts index fede0a1e..9382ac5f 100644 --- a/packages/core/src/profiles/csharp.ts +++ b/packages/core/src/profiles/csharp.ts @@ -219,6 +219,7 @@ export const csharpProfile: Profile = { "Neither a `.sln` nor a `.csproj` is read: the extractor parses every `*.cs` under the source roots into ONE compilation (no MSBuild, no restore), so a legacy tree with no restorable project graph still extracts, and a missing package is a stub rather than a build failure. Consequences: one preprocessor configuration is parsed (no `--define` yet); source-generated and XAML/Razor code-behind partials are absent unless their output is under the roots; a name declared twice across projects that never see each other collides as one entity.", "The metrics pass (`codegraph-metrics`, PLAN.md §18): a property with accessors is joined to its accessor spaces — `{ get; set; }` is two, so it carries the pass's charged keys only (cognitive, exits, ABC). An implicit constructor (anchored on the type's name) and a record's positional members have no space and carry none of its keys. tree-sitter-c-sharp 0.23.5 misparses a C# 14 extension block: its members go unmeasured by the pass, and the enclosing class is joined by containment (charged keys only). tree-sitter does not evaluate `#if`: in a file with conditional blocks big-code-analysis measures EVERY branch, where Roslyn — and so this extractor's `sloc` — keeps the active one; on Humanizer such files are the 37 exact joins whose `sloc` and big-code-analysis's `ploc` disagree.", "MM-6 (an edge's `member`, contract 1.1.0): an edge to a stub names the member the site wrote, by its SIMPLE name as written — no parameter types, no type arguments (`Select(…)` → `Select`). A method call on a stub type is an `invocation` naming the method (`builder.Append(x)` → `Append`); so is a static call, with or without its type (`Console.WriteLine(x)` → `WriteLine`, `Round(v)` under `using static System.Math` → `Round`), and so is an extension method call, on the static class that declares it (`xs.Select(…)` → `Select` on `System.Linq/Enumerable`); `d.Invoke(x)` on a delegate names `Invoke`. A field, property or event read or written is an `access` naming it (`DateTime.Today` → `Today`, `b.Length = 0` → `Length`, `AppDomain.CurrentDomain.ProcessExit += h` → `ProcessExit`); a method group used as a value is a `reference` naming the method (`Action w = Console.WriteLine` → `WriteLine`). A receiver Roslyn cannot bind is a `reference` to its stub in `` naming the ONE name written right after it (`JsonConvert.SerializeObject(x)` → `SerializeObject`, `JsonConvert.Settings` → `Settings`, `JsonConvert.Deserialize(s)` → `Deserialize`); a longer chain names only that first name (`A.B.C()` with `A` unbound → `B`), and nothing is invented for what follows. An unbound name carries no symbol, so the extractor cannot tell a type from a namespace prefix or a member inherited from an unresolved base: it names the member on every unbound-receiver reference it already emits. A call in a field initializer is an invocation from the field and names its method alike. Named nowhere: a constructor call (`new T()`, `new()`, `base(…)`, `this(…)` — the edge to the type says all the site wrote), a delegate call (`first()` writes no member of `Action`), an indexer (`xs[0]` writes no name; the access and its read/write flags are the fact), a user-defined operator (`a - b` on `DateTime`), `typeof`, `nameof`, an attribute use, a written type use (an unbound one included: `Unbound x`, `new Unbound()`, `typeof(Unbound)`, `List`), and every edge to a corpus entity — its member is an entity, and the edge points at it; a call to a member Roslyn synthesizes on a corpus record folds to the record and names none. The member is part of the edge (EdgeExtractor's `seen` key): `values.Count == 0 ? null : values[0]` is two accesses of `List` (`Count`, and the indexer naming none) where it was one, `amounts.Select(…).DefaultIfEmpty(0L).Max()` three invocations of `Enumerable`; a read and a write of one member at one site stay two accesses, one per flag pair, as before. Measured on the reference corpus: 17 of 119 edges to stubs named, 292 edges become 295.", + "MM-7 and MM-8 (contract 1.2.0) are not emitted by this language's extractor yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses `TWithReceiver` on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not \"no written type\", not \"no receiver\" (PLAN.md §26.10).", ], lexicon: { diff --git a/packages/core/src/profiles/elixir.ts b/packages/core/src/profiles/elixir.ts index 89fc6414..c4912e33 100644 --- a/packages/core/src/profiles/elixir.ts +++ b/packages/core/src/profiles/elixir.ts @@ -134,6 +134,7 @@ export const elixirProfile: Profile = { "Measures (TMetrics, METAMODEL.md §3.8): `sloc` on the file, every module and every invocable — lines of its own span that are neither blank nor comment-only, a comment being what the compiler's own parser reports as one: every non-blank line a heredoc, a sigil or a multi-line string spans is code, a `#` inside one included; `cyclomatic` on invocables: 1 + clause heads beyond the first + `case`/`cond`/`with`/`receive`/`try` clauses beyond the first + `if`/`unless` + `and`/`or`/`&&`/`||` + `rescue`/`catch` clauses. A nested `fn` contributes to its enclosing invocable: an anonymous function is not an entity.", "The metrics pass (`codegraph-metrics`, PLAN.md §18): big-code-analysis opens one space per `def` clause, so a function of several clauses is joined by containment and carries the charged keys only (cognitive, exits, ABC) — no `lloc`, Halstead or `mi`, which do not add up over clauses. `defprotocol` and `defimpl` bodies, `defguard` and `defdelegate` have no space and carry none of the pass's keys. The join's witness (`sloc` = big-code-analysis's `ploc`) cannot hold over a heredoc: big-code-analysis leaves a heredoc's text lines out of `ploc`, which METAMODEL's `sloc` counts (Phoenix's `mix_app_path`: `sloc` 19, `ploc` 13).", "MM-6 (an edge's `member`, contract 1.1.0, header `schemaVersion` 1.1.0): an `invocation`, `access` or `reference` to a stub names the member its site writes, as `name/arity` with the arity the site really has — arity is identity on the BEAM. A remote call `M.f(a, b)`, a macro `Logger.info(msg)` and an Erlang call `:ets.lookup(t, k)` name `f/2`, `info/1`, `lookup/2`; a pipe counts its left side (`x |> Enum.map(f)` is `map/2`); a capture `&M.f/2` or `&M.f(&1, x)` is a `reference` naming `f/2`; a local call an `import` of the stub provides (`config :app, k: v` under `import Config`) names `config/2`; `use M` is the invocation of `__using__/1`; `defdelegate f(a), to: M, as: :g` names `g/1`; a remote type in a typespec (`String.t()`) is a `reference` naming `t/0`; a `--trace` edge names its call the same way. A field of a stub struct — `%Ecto.Changeset{valid?: v}` in a pattern, `%M{s | k: v}` in an update, `%M{k: v}` in a construction — is one `access` to the stub module per field written, naming the field as written, with no arity (`valid?`): `isRead` in a pattern, `isWrite` otherwise, as for a corpus struct. So `:ets.lookup` and `:ets.insert` on one table are two edges, a read and a write told apart. No member: a module written as a value (`{Registry, keys: :unique}`, `children = [Mod]`), an `import` edge, a `throws` or `interfaceImplementation` edge, and every edge to a corpus entity, which already points at the member. `codegraph validate` on the fixture prints `members named: 37 of 42 edges to stubs` — the 5 are 3 modules written as values and 2 `%Ecto.Changeset{…}` struct references, whose fields are the named accesses.", + "MM-7 and MM-8 (contract 1.2.0) are not emitted by this language's extractor yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses `TWithReceiver` on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not \"no written type\", not \"no receiver\" (PLAN.md §26.10).", ], lexicon: { diff --git a/packages/core/src/profiles/go.ts b/packages/core/src/profiles/go.ts index 2218be43..89804f38 100644 --- a/packages/core/src/profiles/go.ts +++ b/packages/core/src/profiles/go.ts @@ -108,6 +108,7 @@ export const goProfile: Profile = { "Calls through an interface value cannot be resolved statically: they are emitted against the interface method with provenance \"dynamic-candidate\" and the satisfying implementations as candidates.", "Invisible to static extraction: reflect, the plugin package, cgo, go:generate and go:linkname directives, and side effects of init() functions pulled in by blank imports (`import _ \"…\"`), which are still emitted as ordinary import edges.", "Build tags and GOOS/GOARCH constrained files mean a single extraction run sees one build configuration; entities excluded by the active tags are absent from the model.", + "MM-7 and MM-8 (contract 1.2.0) are not emitted by any extractor of this language (none ships) yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses `TWithReceiver` on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not \"no written type\", not \"no receiver\" (PLAN.md §26.10).", ], lexicon: { diff --git a/packages/core/src/profiles/java.ts b/packages/core/src/profiles/java.ts index 46970fd8..87b675b1 100644 --- a/packages/core/src/profiles/java.ts +++ b/packages/core/src/profiles/java.ts @@ -96,8 +96,9 @@ export const javaProfile: Profile = { "TSourceAnchor", ], // TWithValue on a METHOD is the annotation-element `default` — the one - // place Java writes a value on something invocable. - optional: ["TComment", "TMetrics", "TWithValue"], + // place Java writes a value on something invocable. TWithReceiver (MM-8): + // an instance method; a static one does not carry it. + optional: ["TComment", "TMetrics", "TWithValue", "TWithReceiver"], }, // No TNamed (a constructor has no own name) and no TTypedEntity (it has no @@ -115,7 +116,8 @@ export const javaProfile: Profile = { "TChildOf", "TSourceAnchor", ] satisfies readonly TraitName[], - optional: ["TComment", "TMetrics"] satisfies readonly TraitName[], + // TWithReceiver (MM-8): a constructor initializes an instance. + optional: ["TComment", "TMetrics", "TWithReceiver"] satisfies readonly TraitName[], }, // Lambdas and anonymous classes: invocable but nameless; the id's @@ -137,9 +139,12 @@ export const javaProfile: Profile = { // TWithValue: a `static final` compile-time constant's initializer (§1.6). // Optional and often absent — an initializer that is not constant carries // no value at all, which is not the same claim as an empty one. + // TWithReceiver (MM-8): an instance field; a static field and an enum + // constant do not carry it. Optional, so a model written before contract + // 1.2.0 stays valid. attribute: { required: ["TNamed", "TStructural", "TTypedEntity", "TChildOf", "TSourceAnchor"], - optional: ["TComment", "TWithValue"], + optional: ["TComment", "TWithValue", "TWithReceiver"], }, parameter: { @@ -176,7 +181,7 @@ export const javaProfile: Profile = { "A `throws` edge is emitted per written `throw` statement whose static exception type resolves, anchored at the throw site — the evidence a guard clause (`if (x) throw new E(...)`) leaves in the model. A method's `throws` CLAUSE stays a plain reference edge: it declares propagation, not a failure exit of this body. A rethrow (`throw e;`) targets the caught variable's static type; a throw whose type Spoon cannot name is dropped and counted, like any unidentifiable target.", "Static and on-demand (`import x.y.*`) imports are folded to module-level import edges; the wildcard case names the package, not the individual types it brings in.", "Overloads are distinguished by the id's signature disambiguator, so an unresolved parameter type changes the id — a resolution failure shows up as a stub target, never as a merged entity.", - "Java generics are erased in the model: type arguments are emitted as reference edges from the declaring entity, and declaredType carries the raw type.", + "Java generics are erased in an id and in `declaredType`, which carries the raw type; type arguments are still emitted as reference edges from the declaring entity. What the source WROTE is `typeExpr` (MM-7, contract 1.2.0), on every field, parameter, local variable, method return, record component and explicitly typed lambda parameter: `List` a `named` List with its argument, `int` a `primitive`, `int[]` an `array` of one (a varargs parameter too, nested for `int[][]`), a type parameter `T` a `variable`. A wildcard (`? extends Order`, `?`), an intersection, an outer type's arguments (`Outer.Inner`) and a type Spoon cannot name are `unevaluated`, with their source text (whitespace folded). None on what is not written: `var`, an implicitly typed lambda parameter, a `void` return, a constructor; a record's implicit members carry their component's written type. A `named` target is the same id `declaredType` and the edges use; one that no entity declares — not even a stub, since the type expression never makes one — is kept as `unevaluated` text, never as a fabricated id. Java writes no `nullable` (an annotation is not inferred into one), no `function` and no `union`.", "noClasspath resolution rate, measured (M2 audit): 100.0% on apache/commons-lang (263 files, 133478 type references, 0 unresolved) and 77.8% on spring-petclinic (30 files, 2189 references, 487 unresolved, all of them Spring and Jakarta types whose jars are absent). The rate is a property of the corpus's DEPENDENCY SURFACE, not of the extractor: commons-lang is self-contained and depends on nothing but the JDK, which resolves against the runner's own classpath. A jar that is not on the classpath cannot be resolved by any extractor, so a corpus with third-party dependencies has a structural ceiling well below 100% and a single cross-corpus target number is not meaningful. The stub discipline, not the resolution rate, is the property worth asserting.", "The resolution rate counts neither type variables nor ``: neither names anything that could have a declaration, so counting them measures the corpus's writing style. This is not cosmetic — ``, Spoon's static type for the `null` literal, was ALL 1466 of commons-lang's originally-reported unresolved references, making the headline number a function of how many `return null;` statements the corpus contains.", "In noClasspath Spoon promotes an unresolvable RECEIVER to a type in the enclosing package: `typeHint -> typeHint.with(...)` and `cm.setStatisticsEnabled(...)` produced stub classes named `typeHint` and `cm` inside the corpus's own package on spring-petclinic. They are correctly stubbed (membership is the declared-id whitelist), and they are why the whitelist exists — but the stub set of a real corpus therefore contains a tail of entities named after local variables, and a stub count is not a count of external types.", @@ -187,6 +192,7 @@ export const javaProfile: Profile = { "Spoon materializes the implicit constructor of an anonymous class with synthetic parameters named `$anonymousN`. They are emitted (implicit members are, deliberately, so that `new Foo()` does not dangle), so the model contains a handful of parameter entities nobody wrote, carrying no anchor of their own — 5 of 15338 entities on commons-lang.", "The metrics pass (`codegraph-metrics`, PLAN.md §18) joins big-code-analysis spaces to entities on their anchors. Spoon starts a declaration AFTER its annotations and tree-sitter AT them; the pass bridges the two when nothing but annotation lines lies between (a LEADING join — most of a Spring corpus). It measures nothing on a lambda (big-code-analysis opens no space for one and charges its cognitive, exits and ABC to the enclosing method), on an implicit constructor (anchored on its class) or on an annotation element (no body): those carry none of the pass's keys.", "MM-6 (an edge's `member`, contract 1.1.0): an edge to a stub names the member the site wrote, by its SIMPLE name — no parameter types, since an external method's erased types need a classpath and the extractor runs noClasspath. A method call on a stub type is an `invocation` naming the method (`lines.add(x)` → `add`, a static call through a static import included: `asList`); a method reference `Integer::parseInt` names `parseInt`; a field read or written is an `access` naming the field (`System.out` → `out`), and a read and a write of one field at one site stay one access with both flags; written outside every invocable (a field initializer, an annotation argument) the call or the field read degrades to a `reference` that keeps the name (`Logger.getLogger(…)` → `getLogger`, `@Retention(RetentionPolicy.RUNTIME)` → `RUNTIME`). Named nowhere: a constructor call or reference (`new ArrayList<>()`, `super(…)`, `ArrayList::new` — the edge to the type says all the site wrote), a class literal (`Foo.class` is no member of Foo), a written type use, a supertype clause, and every edge to a corpus entity — its member is an entity, and the edge points at it. The member is part of the edge: `values.isEmpty() ? null : values.get(0)` is two invocations of `List`, where it was one. Measured on spring-petclinic: 723 of 1 164 edges to stubs named, 2 800 edges become 2 847 (42 sites split). A call to a member a corpus type INHERITS from a library one (`owners.save(owner)` on a Spring Data `JpaRepository`) has no declaring type in noClasspath; where the ancestor rule (the `ancestor-attributed` note) charges it to the one library ancestor, the edge names the member like any other (`save`, `saveAndFlush`): the five repository writes of spring-petclinic.", + "MM-7 and MM-8 (contract 1.2.0, emitted since M25b): the profile licenses `TWithReceiver`, optional, on `attribute`, `method` and `constructor`. It is carried by an instance field (a record component included), an instance method (abstract and default interface methods included, and an annotation element: it is read on an annotation instance, `audited.value()`) and every constructor; not by a static field or method, an enum constant, an interface or annotation-type field (implicitly static), a lambda or anonymous class, a parameter or a local variable. On those three kinds the absence of `TWithReceiver` means \"no receiver\", in a model whose header states contract 1.2.0 or later; a model written before carries the marker nowhere, and there its absence says nothing. An `access` to a corpus field with a receiver states `receiver`: `self` when reached through the accessor's own `this` — written, implied (`lines`), through `super.x`, or inherited — where \"own\" is the innermost type the access is written in, so a lambda's `this.x` is `self` (a lambda has no receiver of its own); `other` through any other expression (`order.lines`), including an inner, local or anonymous class reaching its OUTER instance (`lines` in `Basket.Cursor`, implied `Basket.this.lines`). Absent on an access to a static field or to a stub. A self and an other access at one site are two edges. Measured on spring-petclinic: 460 of 590 typed entities carry a `typeExpr` (400 `named`, 53 `primitive`, 5 `array`, 2 `variable` at the top; 5 `unevaluated` nodes, all `?`), 289 entities `TWithReceiver`, and of 371 accesses 183 are `self`, 46 `other` (mostly `@Nested` test classes reading their outer class's fields) and 142 state none.", ], lexicon: { diff --git a/packages/core/src/profiles/javascript.ts b/packages/core/src/profiles/javascript.ts index 1b28e47c..c544602a 100644 --- a/packages/core/src/profiles/javascript.ts +++ b/packages/core/src/profiles/javascript.ts @@ -110,6 +110,7 @@ export const javascriptProfile: Profile = { "`this` rebinding (`call`/`apply`/`bind`, arrow lexical `this`, extracted methods) breaks receiver-based resolution; edges through a rebound `this` are not reconstructed.", "Getters/setters are emitted as `method` entities; reads and writes of the underlying value at call sites are `access` edges, so a property read that runs code is visible as access, not invocation.", "Class fields and object literal members share the `property` kind; object literals used as namespaces therefore appear as a `variable` with `property` children.", + "MM-7 and MM-8 (contract 1.2.0) are not emitted by any extractor of this language (none ships) yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses `TWithReceiver` on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not \"no written type\", not \"no receiver\" (PLAN.md §26.10).", ], // The module is the file: its name is a path whose extension is not a word. diff --git a/packages/core/src/profiles/php.ts b/packages/core/src/profiles/php.ts index 7a975bde..3af07e74 100644 --- a/packages/core/src/profiles/php.ts +++ b/packages/core/src/profiles/php.ts @@ -122,6 +122,7 @@ export const phpProfile: Profile = { "Single inheritance for classes (at most one inheritance edge); interfaces may extend several, so N edges are legal there.", "Gradual typing: parameter, property and return type declarations are optional, so TTypedEntity.declaredType is often absent. Docblock types (@var, @param) are not authoritative and must not be promoted to declaredType.", "Namespaces are 1-N with files: TModule.definedIn lists every file declaring into the namespace. A file with no `namespace` statement declares into the global namespace.", + "MM-7 and MM-8 (contract 1.2.0) are not emitted by any extractor of this language (none ships) yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses `TWithReceiver` on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not \"no written type\", not \"no receiver\" (PLAN.md §26.10).", ], lexicon: { diff --git a/packages/core/src/profiles/python.ts b/packages/core/src/profiles/python.ts index 5eecf72d..0aa106b1 100644 --- a/packages/core/src/profiles/python.ts +++ b/packages/core/src/profiles/python.ts @@ -128,6 +128,7 @@ export const pythonProfile: Profile = { "Explicitly NOT extracted: members a decorator or a metaclass synthesizes — a dataclass's `__init__`, a Django model's manager; the class's own written fields ARE attributes. Monkey patching (`Order.total = total`): the model shows the original definition site only. Protocol (PEP 544) conformance: structural, so `interfaceImplementation` stays in the profile for a `derived` enrichment of the analyzer, never mixed in, and the extractor writes none — `class X(Protocol)` is a plain inheritance. What a string names (`ForeignKey(\"orders.Order\")`, `INSTALLED_APPS`, an entry point in `pyproject.toml`): framework semantics. `isinstance` narrowing, notebooks and Cython.", "Audit (M22c, every model `validate`-clean with the metrics pass applied, nothing installed read, nothing run): psf/requests (37 files, 2 529 entities / 3 593 edges, 0.06 s, 20 MB) resolves 81.6 % of 5 768 sites; Django (2 922 files, 111 593 / 229 360, 2.9 s, 433 MB) 73.4 % of 278 073, 18 816 of them `unbound-dynamic` (its test models, `ConnectionProxy`, `LazySettings`); Zulip (2 125 files, 54 725 / 174 640, 2.0 s, 307 MB) 81.9 % of 228 523, 6 508 `ambiguous-ancestor` (test cases under two Django test classes the extractor cannot order); CPython 3.14.10 `Lib/` (1 876 files, 206 234 / 420 124, 5.1 s, 822 MB) 77.0 % of 623 485; CPython 2.7.18 `Lib/` (1 613 files, 590 of them Python 2 syntax the parser recovers, 141 281 / 217 345, 2.8 s, 478 MB) 78.7 % of 303 632. `untyped-receiver` is the largest remainder everywhere. Keyed where typeshed declares it, no standard-library class has two keys in any of the five models (the same-name pairs left are different classes: `threading.Event` and `asyncio.locks.Event`, `binascii.Error` and `configparser.Error`…); the dotted-module guess keys 66 `` classes over the five, one of them with a Capitalized segment before the last (Zulip's `pika.spec` `Basic.Deliver`, a nested class the guess takes for a module); a corpus class written as a receiver, whatever its member, adds 14 340 `reference`s on Django, 5 780 on Zulip, 1 654 on 2.7, 1 360 on 3.14 and 1 on requests — the sites it names stay dropped where they were: no rate and no drop counter moves. In CPython 3's own `Lib/`, every import of a module that has a file there reaches that file; the 229 modules reached outside it have none (built into the interpreter, or registered at run time: `os.path`, `collections.abc`). Oracles, each in a container with no network: CPython's `ast` (lib2to3 for 2.7) and the model agree on every class, function and method by (file, line, kind, name) once the stated folds are applied (a redefinition, `@overload`, a form-made class) — all of requests, Django and Zulip, 83 413 of 83 415 on 3.14, 43 112 of 43 117 on 2.7, the rest `redefinition-of-another-kind`; grimp 3.20 on Django finds 3 209 of the model's 3 211 module edges (it has 3 214), every difference `from pkg import sub` where `pkg` binds its own submodule: grimp names the submodule, the model the package (the re-export rule); pyright (scip-python 0.6.8), where it resolves a site, agrees with 98.6 % (requests), 98.3 % (Zulip) and 98.8 % (Django) of the `declared` edges, 99.1 % / 98.9 % of `annotation-typed`, 100 % / 96.3 % of `flow-typed`, every `ancestor-attributed` one it resolves — up to the stated folds (a class called is its `__init__`, a library function its module, a library member its class, an attribute its root-most owner, a library name as the site imports it); requests' own tests (615 passed) execute 282 import statements, 262 reaching what the model says and 2 a run-time alias (`os.path` is `posixpath`; `requests.packages.urllib3` is `urllib3`); the other 18 are no statement — imports the interpreter makes inside a call (`warnings.warn`, `time.strptime`, `pickle`) — and one computed `__import__`, counted.", "MM-6 (an edge's `member`, contract 1.1.0, header `schemaVersion` 1.1.0): an `invocation`, `access` or `reference` that folds into a stub names the ATTRIBUTE PATH the site writes below it, dotted. Below a module stub, the name in that module: `json.dumps(x)` → `dumps`, `os.path.join` → `join` on `%2Fos.path` (a module of its own), `os.environ.get(k)` → `environ.get` (a value of `os`), a name a `from` import binds called or read directly under the module's own name, not the alias (`from json import loads as parse; parse(s)` → `loads`, `if TYPE_CHECKING:` → `TYPE_CHECKING`). Below a class stub, the attributes after it: a method or attribute of an instance typed as a library class (`r: Response` then `r.json()` → `json`), and the ancestor-attributed edges — a member a corpus class's one library ancestor answers — where it matters most: `self.assertTrue(…)` → `assertTrue`, `super().setUp()` → `setUp`, `Tracked.objects.filter()` → `objects.filter`, so `objects.create` is told from `objects.filter`. A read is a `reference` naming the attribute (`sys.platform` → `platform`), a write an `access` (`sys.path = []` → `path`). No member: a library class called (`Enum(…)`, `TypeVar(\"T\")` — the construction lands on the class itself), a class read as a value (`TestCase = unittest.TestCase`) or caught (`except KeyError`), a type annotation (the stub IS the type, as in Java and TypeScript), a decorator (`annotationUse`), what a call RETURNS — `json.loads(s).get(k)` is an invocation naming `loads` and one naming none, since `get` is no member of `json` — and every edge to a corpus entity, which already points at the member. An instance a library class constructs names its attributes again (`e = Enum(…)` then `e.value` → `value`). The member is part of the edge: `json.dumps(json.loads(s))` is two invocations of `json`, where it was one. On the fixture `codegraph validate` prints `members named: 16 of 25 edges to stubs` — the 9 others are 5 caught builtins, 3 library classes called and one read; no fixture site splits. Measured on pip 24.0's own tree: 5 093 of 8 374 edges to stubs named, 43 457 edges become 43 736 (264 sites split; 96 of them pair a member-less edge — a library class constructed, or a call on a call's result — with a named one).", + "MM-7 and MM-8 (contract 1.2.0) are not emitted by this language's extractor yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses `TWithReceiver` on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not \"no written type\", not \"no receiver\" (PLAN.md §26.10).", ], lexicon: { diff --git a/packages/core/src/profiles/ruby.ts b/packages/core/src/profiles/ruby.ts index 6d0a18d9..e64502ea 100644 --- a/packages/core/src/profiles/ruby.ts +++ b/packages/core/src/profiles/ruby.ts @@ -115,6 +115,7 @@ export const rubyProfile: Profile = { "`--trace ` merges what `extractors/ruby/trace/codegraph_trace.rb` wrote from INSIDE the running program — the one thing the extractor never does is run corpus code, so the trace is a separate step, the user's, in a project that still boots. It names constants, files and lines, never a key: no entity is added and no edge of the source changes. A mixin the VM holds and no line writes is a `traitUsage` with provenance `generated`, anchored on the declaration of the type that has it. A call the program made at a site the baseline left unresolved is ONE `invocation` with provenance `dynamic-candidate`, `candidates` listing every method that site was seen to reach and `to` the first of them — what ran once, not what must run. A method the VM holds on a line that writes no `def` has no entity and gets none: it is counted.", "Audited (M18c) on rake 13.2.1, rubygems 3.6.2, Mastodon 4.3.0 and rails 8.0.2 — 100, 794, 2 541 and 3 334 files, every model `validate`-clean, rails in 4.7 s. Resolution rate 77.8 %, 54.4 %, 31.2 % and 57.0 % of the sites; Mastodon without `spec/` is 62.1 % (55 000 of its unbound calls are RSpec's DSL), rails' own `lib` and `app` 59.4 %. Four fifths of what stays unresolved in application code is `untyped-receiver` — the ceiling of any reader that does not run the code. ORACLES: Packwerk 3.3.1's reference extraction and ConstantResolver over Mastodon's autoload paths resolve 4 335 cross-file constant references in `app/` and `lib/`; the model has the same constant in the same file for 4 289 of them (98.9 %) — the 45 others are a `module Admin` WRAPPER, which Packwerk counts as a reference and the wrapper rule does not, and one an inherited constant Packwerk places by file name. The model names 346 more that Packwerk cannot: declarations outside the autoload paths. Run under its own tests in a container, rake's VM holds a method on the same line for 1 006 of the 1 012 methods the model declares in the 83 files it loaded (the six others: definitions under a platform or capability `if`, a `def` inside a method that never ran, methods of anonymous classes), and 200 methods the model has none for — 199 written by the metaprogramming loops of three files (`class_eval` of a string, `define_method` over a list), one the `else` branch of a platform test. Of the 2 829 calls observed during that run, 1 533 are edges the baseline wrote and 879 land on sites it had left untyped. The core-table misreading, measured on rubygems: 39 corpus bodies of 20 VM types (`Gem` alone 12), and 3 802 of 71 197 edges landing on the VM's stub of a type that corpus itself implements.", "MM-6 (an edge's `member`, contract 1.1.0, header `schemaVersion` 1.1.0): an `invocation` of a stub names the METHOD AS WRITTEN at the site, punctuation and all — `find_by`, `save!`, `empty?`, `name=` for `x.name = v`, `[]` for `Dir[…]`. Named: a call on a library or core constant (`Stripe::Charge.create` → `create`, `File.join` → `join`, though `join` is IO's), on a receiver typed as one (`Foo.new(…).x`, a local or an instance variable every assignment of which is `Foo.new`), the method a core class adds to a corpus reopening or subclass of it (`upcase` in a subclass of String), the call attributed to the one library ancestor that could answer (`has_many`, `where` in an ActiveRecord model), a method some library adds to a core class (`Time.zone`), and `super`, which names the enclosing `def`'s name — the method Ruby calls one step up (`def save; super; end` → `save`, `super(…)` in `initialize` → `initialize`). `Foo.new` names `new`: in Ruby it is an ordinary singleton method the site writes (and a class may redefine), and it tells instantiation from `Foo.create` on the same stub; the chain is still searched for `initialize`, so a corpus `initialize` is the corpus edge it always was. No member: a constant read (`Foo`, `Foo::BAR`, `include Comparable` — the stub IS the constant written: a library's `Foo::BAR` is a stub of its own, since a reader cannot tell a nested type from a value), an `import`, `inheritance`, `traitUsage` or `throws` edge, a `--trace` candidate, and every edge to a corpus entity, which already points at the method. The member is part of the edge: `Stripe::Charge.create(Stripe::Charge.retrieve(id))` and `Logger.new(io).info(m)` are two invocations of one stub at one site, where they were one. On the fixture `codegraph validate` prints `members named: 13 of 24 edges to stubs` — the 11 others are constant reads; no fixture site splits.", + "MM-7 and MM-8 (contract 1.2.0) are not emitted by this language's extractor yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses `TWithReceiver` on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not \"no written type\", not \"no receiver\" (PLAN.md §26.10).", ], lexicon: { diff --git a/packages/core/src/profiles/rust.ts b/packages/core/src/profiles/rust.ts index a45d1a6e..1dba9f85 100644 --- a/packages/core/src/profiles/rust.ts +++ b/packages/core/src/profiles/rust.ts @@ -103,6 +103,7 @@ export const rustProfile: Profile = { "Enum variants are not reified as a kind of their own: the enum is the type-level unit, variant payload types appear as `reference` edges from it, and named variant fields are `field` children.", "`static` items map to the `const` kind. Tuple-struct fields are named by their position (\"0\", \"1\", ...). Shadowed `let` bindings produce several localVariable entities disambiguated by (file, startLine).", "The `self` receiver is not emitted as a parameter; the receiver relation is the impl block's attachment.", + "MM-7 and MM-8 (contract 1.2.0) are not emitted by any extractor of this language (none ships) yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses `TWithReceiver` on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not \"no written type\", not \"no receiver\" (PLAN.md §26.10).", ], lexicon: { diff --git a/packages/core/src/profiles/typescript.ts b/packages/core/src/profiles/typescript.ts index b5027c02..1231fcf6 100644 --- a/packages/core/src/profiles/typescript.ts +++ b/packages/core/src/profiles/typescript.ts @@ -249,6 +249,7 @@ export const typescriptProfile: Profile = { "A written value (TWithValue) is emitted for a `const` variable, a `readonly` property, an enum member and a parameter default whose initializer is CONSTANT-SHAPED — a literal, `-N`, an enum member, a type used as a value, arrays and operator expressions over those. TypeScript folds nothing at the declaration, so `4 * 25` rides `unevaluated` with its source text where Java would fold it; an enum member's value is the checker's computed constant. An initializer that is code — a call, a `new`, a function, an object literal — carries no value at all: absence is a claim. Such an initializer's calls and accesses are edges FROM the variable or property (the narrowest declared owner), which then carries TWithInvocations/TWithAccesses.", "The metrics pass (`codegraph-metrics`, PLAN.md §18): namespaces, enums, type aliases, interface members without a body and ambient declarations have no big-code-analysis space and carry none of the pass's keys. An exported class's decorators precede tree-sitter's class node; the pass joins across the decorator lines. In a `.tsx` file big-code-analysis's `ploc` can count a line or two fewer than this extractor's `sloc` (a JSX text token counts every line it spans here), so the join's witness differs there by that much.", "MM-6 (an edge's `member`, contract 1.1.0): an `invocation`, `access` or `reference` that folds into a stub names the member it reached, spelled as the DECLARATION writes it — the property name. A method call or a property read or write on an external type: `push`, `size` (`isRead`/`isWrite` as at any access; a getter or setter is its property's name). A free function, variable or namespace member of a module: the name the module EXPORTS it under, so an aliased import `import { readFileSync as r }` names `readFileSync`, a default export `default`, a namespace import `fs.readFileSync(…)` `readFileSync`; a member of a namespace is its dotted path below the stub (`util.format`, `constants.R_OK`), and `declare global` is a scope, not a segment. A function used as a value (`reference`), a tagged template's tag and a JSX component name the function. No member where the site reaches the stub itself: `new T()` and a constructor, a call or construct signature (`String(x)`, `super(…)`, `expect(x)`), calling an `export =` module, a type reference (the stub IS the type), a variable folded to its declared type (`declare var Math: Math`), and a property of a signature's anonymous type (`readConfigFile(…).config`). Decorators are `annotationUse` and name none. An edge to a corpus entity never names one, even when an external declaration merges into it. Measured on codegraph itself (2026-11-28): 29 641 of 47 493 edges to stubs named, entity and edge counts unchanged (this extractor never merged edges).", + "MM-7 and MM-8 (contract 1.2.0) are not emitted by this language's extractor yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses `TWithReceiver` on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not \"no written type\", not \"no receiver\" (PLAN.md §26.10).", ], // The module is the file: its name is a path whose extension is not a word. diff --git a/packages/core/src/traits.ts b/packages/core/src/traits.ts index 647cc3cc..33a134d2 100644 --- a/packages/core/src/traits.ts +++ b/packages/core/src/traits.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import type { TraitName } from "./names.js"; import { Literal } from "./literal.js"; import { EntityId, SourceAnchor } from "./primitives.js"; +import { TypeExpr } from "./type-expr.js"; /** * One partial schema per trait: exactly the keys that trait contributes to the @@ -35,7 +36,9 @@ export const TRAITS = { TWithInheritances: z.object({}), TWithImplements: z.object({}), // Optional even when the trait is declared: inferred types, `var`, dynamic languages. - TTypedEntity: z.object({ declaredType: EntityId.optional() }), + // `declaredType` is the erased head (a reference); `typeExpr` the type AS + // WRITTEN, a tree (MM-7, METAMODEL.md §1.7) — absent wherever nothing is written. + TTypedEntity: z.object({ declaredType: EntityId.optional(), typeExpr: TypeExpr.optional() }), // behavior TInvocable: z.object({ signature: z.string() }), @@ -46,6 +49,10 @@ export const TRAITS = { // structure TStructural: z.object({}), TWithAccesses: z.object({}), + // MM-8: evaluated against an instance of the type it is written in or attached + // to (an instance field, an instance method, a constructor). Where a profile + // licenses it on a kind, absence means "no receiver"; elsewhere, nothing. + TWithReceiver: z.object({}), // measures (METAMODEL.md §3.8). ONLY an extractor writes this: every value // required reading source no consumer sees. The keys are deliberately open — @@ -73,6 +80,7 @@ const MARKER_TRAIT_NAMES = [ "TWithInvocations", "TStructural", "TWithAccesses", + "TWithReceiver", ] as const satisfies readonly TraitName[]; export const MARKER_TRAITS: ReadonlySet = new Set(MARKER_TRAIT_NAMES); diff --git a/packages/core/src/type-expr.ts b/packages/core/src/type-expr.ts new file mode 100644 index 00000000..04ab27a1 --- /dev/null +++ b/packages/core/src/type-expr.ts @@ -0,0 +1,184 @@ +import { z } from "zod"; +import { EntityId } from "./primitives.js"; + +/** + * THE TYPE DOOR (METAMODEL.md §1.7, MM-7): the type a declaration WRITES — + * `List`, `int[]`, `String?` — kept as a tree, where `declaredType` + * keeps only its erased head. Built as `Literal` is (§1.6), and for the same + * two reasons: + * + * 1. **A type expression is what is written, never what is inferred.** No + * `typeExpr` on a `var`, an untyped parameter or a `void` return; a written + * type the extractor did not structure (a wildcard, an intersection) is + * `unevaluated`, its source text kept. `nullable` is where the LANGUAGE + * writes it (`T?`, `T | null`), never inferred from an annotation. + * 2. **Ids inside count for closure** (§8a). A `named` type resolves to a + * declared entity or a stub exactly like an edge endpoint — and in the JSONL + * encoding it is a file-scoped surrogate, so a dangling one is unwritable. + * A type the extractor cannot name is `unevaluated`, never a fabricated id. + * + * A value never replaces a dependency: the `reference` edges a written type + * emits are still emitted. The tag set is closed and core-owned (MM-3). + */ +export type TypeExpr = TypeExprOf; + +/** The eight tags, in the order METAMODEL.md §1.7 lists them. */ +export const TYPE_EXPR_FORMS = [ + "named", + "primitive", + "array", + "nullable", + "function", + "union", + "variable", + "unevaluated", +] as const; + +/** + * One schema shape for both the in-memory form (ids) and the wire form + * (surrogates): only the `named` target differs. Two canonical-form rules a + * Zod refinement could not publish are stated as plain bounds instead: + * `args`, when present, is non-empty (a raw use writes no list at all), and a + * `union` has at least two members. + */ +export function typeExprSchema(ref: z.ZodType, self: () => z.ZodType, description: string): z.ZodType { + return z + .discriminatedUnion("k", [ + z.object({ + k: z.literal("named"), + type: ref, + get args() { + return z.array(self()).min(1).optional(); + }, + }), + z.object({ k: z.literal("primitive"), name: z.string().min(1) }), + z.object({ + k: z.literal("array"), + get of() { + return self(); + }, + }), + z.object({ + k: z.literal("nullable"), + get of() { + return self(); + }, + }), + z.object({ + k: z.literal("function"), + get params() { + return z.array(self()); + }, + get returns() { + return self().optional(); + }, + }), + z.object({ + k: z.literal("union"), + get of() { + return z.array(self()).min(2); + }, + }), + z.object({ k: z.literal("variable"), name: z.string().min(1) }), + z.object({ k: z.literal("unevaluated"), source: z.string().min(1) }), + ]) + .meta({ id: "TypeExpr", description }) as unknown as z.ZodType; +} + +export const TypeExpr: z.ZodType = typeExprSchema( + EntityId, + () => TypeExpr, + "The type a declaration writes (METAMODEL.md §1.7), as a tree. Never inferred: " + + "a written type the extractor did not structure rides as `unevaluated` with its source text.", +); + +/** One id a type expression points at, and where inside it it was written. */ +export interface TypeExprReference { + readonly path: string; + readonly id: EntityId; +} + +/** + * Every id inside a type expression, in written order — what closure walks + * (§8a). Paths are relative to the expression; a caller prefixes its own + * (`entities[3].typeExpr`). + */ +export function typeExprReferences(expr: TypeExpr, prefix = ""): TypeExprReference[] { + switch (expr.k) { + case "named": + return [ + { path: `${prefix}.type`, id: expr.type }, + ...(expr.args ?? []).flatMap((arg, index) => typeExprReferences(arg, `${prefix}.args[${index}]`)), + ]; + case "array": + case "nullable": + return typeExprReferences(expr.of, `${prefix}.of`); + case "function": + return [ + ...expr.params.flatMap((param, index) => typeExprReferences(param, `${prefix}.params[${index}]`)), + ...(expr.returns === undefined ? [] : typeExprReferences(expr.returns, `${prefix}.returns`)), + ]; + case "union": + return expr.of.flatMap((member, index) => typeExprReferences(member, `${prefix}.of[${index}]`)); + default: + return []; + } +} + +/** + * The same tree with every id mapped — the one walk both directions of the + * encoding use (ids → surrogates, surrogates → ids), so encoder and decoder + * cannot disagree on which positions hold a reference. Key order is fixed + * (`k` first, then the form's keys as the table lists them): the encoded + * bytes are canonical whatever order the producer built the object in. + */ +export function mapTypeExpr( + expr: TypeExprOf, + map: (ref: From) => To, +): TypeExprOf { + switch (expr.k) { + case "named": + return expr.args === undefined + ? { k: "named", type: map(expr.type) } + : { k: "named", type: map(expr.type), args: expr.args.map((arg) => mapTypeExpr(arg, map)) }; + case "primitive": + return { k: "primitive", name: expr.name }; + case "array": + return { k: "array", of: mapTypeExpr(expr.of, map) }; + case "nullable": + return { k: "nullable", of: mapTypeExpr(expr.of, map) }; + case "function": { + const params = expr.params.map((param) => mapTypeExpr(param, map)); + return expr.returns === undefined + ? { k: "function", params } + : { k: "function", params, returns: mapTypeExpr(expr.returns, map) }; + } + case "union": + return { k: "union", of: expr.of.map((member) => mapTypeExpr(member, map)) }; + case "variable": + return { k: "variable", name: expr.name }; + case "unevaluated": + return { k: "unevaluated", source: expr.source }; + } +} + +/** + * A type expression whose `named` targets are `R` — an `EntityId` in memory + * ({@link TypeExpr}), a surrogate on the wire (`WireTypeExpr`). + */ +export type TypeExprOf = + /** A declared type or a stub, with its WRITTEN type arguments in order (absent when none). */ + | { readonly k: "named"; readonly type: R; readonly args?: readonly TypeExprOf[] } + /** The language's own word: `int`, `long`, `boolean`, `char`. */ + | { readonly k: "primitive"; readonly name: string } + | { readonly k: "array"; readonly of: TypeExprOf } + /** Only where the language writes it (`T?`, `T | null`). */ + | { readonly k: "nullable"; readonly of: TypeExprOf } + /** `returns` absent = the function returns no value. */ + | { readonly k: "function"; readonly params: readonly TypeExprOf[]; readonly returns?: TypeExprOf } + /** Written alternatives, in written order; at least two. */ + | { readonly k: "union"; readonly of: readonly TypeExprOf[] } + /** A type parameter, by its written name. */ + | { readonly k: "variable"; readonly name: string } + /** A written type the extractor did not structure; the text is still a fact. */ + | { readonly k: "unevaluated"; readonly source: string }; diff --git a/packages/core/src/wire.ts b/packages/core/src/wire.ts index 6d52930a..198d9c7c 100644 --- a/packages/core/src/wire.ts +++ b/packages/core/src/wire.ts @@ -2,6 +2,8 @@ import { z } from "zod"; import { EdgeKind, TraitName } from "./names.js"; import { Provenance, Space } from "./primitives.js"; import { ExtractorInfo, Repository } from "./model.js"; +import { Receiver } from "./edges.js"; +import { typeExprSchema, type TypeExprOf } from "./type-expr.js"; /** * The JSONL interchange records (docs/model-encoding.md §2). One JSON object @@ -111,6 +113,21 @@ export const WireNamedArgument: z.ZodType = z description: "One argument of an annotation use; an implicit name is normalized explicit.", }) as unknown as z.ZodType; +/** + * A TypeExpr (§1.7, MM-7) with every `named` target a surrogate — the rule + * `WireLiteral` follows, for the same reason: a type naming an entity the file + * does not declare has no surrogate to name it with, so it cannot be written. + */ +export type WireTypeExpr = TypeExprOf; + +export const WireTypeExpr: z.ZodType = typeExprSchema( + Ref, + () => WireTypeExpr, + "The type a declaration writes (METAMODEL.md §1.7), as a tree, with entity ids as " + + "surrogates. Never inferred: a written type the extractor did not structure rides as " + + "`unevaluated` with its source text.", +); + /** * The wire form of each trait's contributed keys — the mirror of `TRAITS`, with * every EntityId replaced by a surrogate and every path by a file reference. @@ -133,7 +150,7 @@ export const WIRE_TRAITS = { TType: z.object({ isStub: z.boolean() }), TWithInheritances: z.object({}), TWithImplements: z.object({}), - TTypedEntity: z.object({ declaredType: Ref.optional() }), + TTypedEntity: z.object({ declaredType: Ref.optional(), typeExpr: WireTypeExpr.optional() }), TInvocable: z.object({ signature: z.string() }), TWithParameters: z.object({ parameters: z.array(Ref) }), @@ -142,6 +159,7 @@ export const WIRE_TRAITS = { TStructural: z.object({}), TWithAccesses: z.object({}), + TWithReceiver: z.object({}), // Measures ride verbatim: no ids, no paths, nothing to intern (§3.8). TMetrics: z.object({ metrics: z.record(z.string().min(1), z.number()) }), @@ -208,6 +226,7 @@ export const EntityRec = z.looseObject({ definedIn: z.array(FileRef).optional(), isStub: z.boolean().optional(), declaredType: Ref.optional(), + typeExpr: WireTypeExpr.optional(), signature: z.string().optional(), parameters: z.array(Ref).optional(), localVariables: z.array(Ref).optional(), @@ -237,6 +256,8 @@ export const EdgeRec = z.looseObject({ arguments: z.array(WireNamedArgument).optional(), isRead: z.boolean().optional(), isWrite: z.boolean().optional(), + // MM-8: access only, to an entity that is not a stub — integrity rules again. + receiver: Receiver.optional(), sourceFile: FileRef.optional(), }); export type EdgeRec = z.infer; diff --git a/packages/core/test/member.test.ts b/packages/core/test/member.test.ts index 1d3661c7..43e33716 100644 --- a/packages/core/test/member.test.ts +++ b/packages/core/test/member.test.ts @@ -117,8 +117,11 @@ describe("the wire", () => { }); describe("the schema version (1.0.0 → 1.1.0, additive)", () => { - it("is 1.1.0", () => { - expect(SCHEMA_VERSION).toBe("1.1.0"); + // The member arrived in 1.1.0; a later, additive step keeps it (1.2.0: MM-7, MM-8). + it("is 1.1.0 or later", () => { + const [major, minor] = SCHEMA_VERSION.split(".").map(Number); + expect(major).toBe(1); + expect(minor).toBeGreaterThanOrEqual(1); }); it("still decodes a 1.0.0 file, and keeps the version it states", () => { diff --git a/packages/core/test/model.test.ts b/packages/core/test/model.test.ts index ffc3b287..d54e9717 100644 --- a/packages/core/test/model.test.ts +++ b/packages/core/test/model.test.ts @@ -57,7 +57,7 @@ const model = { describe("Model", () => { it("pins the interchange contract version", () => { - expect(SCHEMA_VERSION).toBe("1.1.0"); + expect(SCHEMA_VERSION).toBe("1.2.0"); }); it("parses the worked example model of METAMODEL §10 / PLAN §4.6", () => { diff --git a/packages/core/test/properties.test.ts b/packages/core/test/properties.test.ts index 39862b8a..d6d5fcae 100644 --- a/packages/core/test/properties.test.ts +++ b/packages/core/test/properties.test.ts @@ -59,8 +59,23 @@ function traitKeys(trait: TraitName, ids: fc.Arbitrary): Record): fc.Arbitrary { + .map(([kind, from, to, provenance, anchor, candidates, sourceFile, isRead, isWrite, receiver]) => { const edge: Record = { edge: kind, from, to, provenance, anchor }; // An annotation use always carries its (possibly empty) argument list. if (kind === "annotationUse") edge["arguments"] = []; @@ -173,6 +189,8 @@ function edgeArb(profile: Profile, ids: fc.Arbitrary): fc.Arbitrary = { edge: kind, from: merge, to, provenance: "declared", anchor: { file: "O.java", span: [at, at] } }; + if (kind === "access") Object.assign(edge, { isRead: true, isWrite: false }); + if (kind === "annotationUse") edge["arguments"] = []; + if (receiver !== undefined) edge["receiver"] = receiver; + return edge as unknown as Edge; +} + +function model(edges: Edge[], schemaVersion = SCHEMA_VERSION): Model { + return { schemaVersion, lang: "java", extractor: { name: "test", version: "0" }, root: "demo", entities: ENTITIES, edges } as unknown as Model; +} + +const edgeLines = (m: Model): string[] => [...encodeModel(m)].filter((text) => text.startsWith('{"t":"x"')); + +describe("the marker (MM-8)", () => { + it("is one more name of the closed vocabulary, contributing no key", () => { + expect(TRAIT_NAMES).toContain("TWithReceiver"); + expect(MARKER_TRAITS.has("TWithReceiver")).toBe(true); + expect(Object.keys(TRAITS.TWithReceiver.shape)).toEqual([]); + expect(Object.keys(WIRE_TRAITS.TWithReceiver.shape)).toEqual([]); + }); + + it("is licensed by the Java profile, optional, on attribute, method and constructor only", () => { + for (const [kind, spec] of Object.entries(javaProfile.kinds)) { + const licensed = ["attribute", "method", "constructor"].includes(kind); + expect(spec.optional.includes("TWithReceiver"), kind).toBe(licensed); + expect(spec.required, kind).not.toContain("TWithReceiver"); + } + }); + + it("keeps a member without it profile-valid, and refuses it on a lambda", () => { + for (const entity of ENTITIES.slice(2, 4)) { + expect(validateEntity(javaProfile, entity as never)).toEqual([]); + const without = { ...entity, traits: entity.traits.filter((t) => t !== "TWithReceiver") }; + expect(validateEntity(javaProfile, without as never)).toEqual([]); + } + const lambda = { + id: "java:com.acme.order/Order.merge(com.acme.order.Order)#O.java:5:9", + kind: "lambda", + traits: ["TInvocable", "TWithChildren", "TWithParameters", "TWithLocalVariables", "TWithInvocations", "TWithAccesses", "TChildOf", "TSourceAnchor", "TWithReceiver"], + signature: "lambda", + parameters: [], + localVariables: [], + parent: merge, + anchor: { file: "O.java", span: [5, 5] }, + }; + expect(validateEntity(javaProfile, lambda as never).map((issue) => issue.code)).toContain("trait-not-allowed"); + }); + + it("is licensed by no other profile, whose notes say its extractor does not emit MM-7 or MM-8 yet", () => { + for (const profile of Object.values(PROFILES)) { + const notes = (profile.notes ?? []).join("\n"); + if (profile === javaProfile) { + expect(notes).toMatch(/absence of `TWithReceiver` means "no receiver"/); + continue; + } + for (const spec of Object.values(profile.kinds)) expect(spec.optional, profile.lang).not.toContain("TWithReceiver"); + expect(notes, profile.lang).toMatch(/MM-7 and MM-8 .*not emitted/); + } + }); +}); + +describe("the attribute on an access (MM-8)", () => { + it("is legal on access, and on no other kind", () => { + expect([...RECEIVER_EDGE_KINDS]).toEqual(["access"]); + for (const kind of EDGE_KINDS) { + expect(Edge.safeParse(access("self", 4, lines, kind)).success, kind).toBe(kind === "access"); + } + }); + + it('is "self" or "other", nothing else', () => { + expect([...RECEIVERS]).toEqual(["self", "other"]); + expect(Edge.safeParse(access("this")).success).toBe(false); + expect(Edge.safeParse(access("")).success).toBe(false); + }); + + it("is one optional field on every edge type, so a consumer reads `edge.receiver` unnarrowed", () => { + const parsed: Edge = parseModel(model([access("other")])).edges[0]!; + const receiver: "self" | "other" | undefined = parsed.receiver; + expect(receiver).toBe("other"); + expect(parseModel(model([access(undefined)])).edges[0]!.receiver).toBeUndefined(); + }); +}); + +describe("the wire", () => { + it("writes `receiver` after the access flags, before sourceFile and anchor", () => { + const [text] = edgeLines(model([access("self")])); + expect(text).toBe('{"t":"x","k":0,"f":3,"o":2,"p":0,"isRead":true,"isWrite":false,"receiver":"self","anchor":[0,4,4]}'); + expect(EdgeRec.safeParse(JSON.parse(text!)).success).toBe(true); + expect(EdgeRec.safeParse({ ...JSON.parse(text!), receiver: "this" }).success).toBe(false); + }); + + it("round-trips the receiver, and an edge without one decodes without the key", () => { + const back = decodeModel(encodeModelToString(model([access("other"), access(undefined, 5)])).split("\n")); + expect(back.edges.map((e) => e.receiver)).toEqual(["other", undefined]); + expect(Object.hasOwn(back.edges[1]!, "receiver")).toBe(false); + }); + + // `this.lines = other.lines` writes one edge per receiver at one site: two facts. + it("keeps a self and an other access at one site as two edges, absent first, then by code unit", () => { + const edges = [access("self"), access(undefined), access("other")]; + const expected = edgeLines(model(edges)); + expect(expected.map((text) => (JSON.parse(text) as { receiver?: string }).receiver)).toEqual([undefined, "other", "self"]); + for (const order_ of [[2, 1, 0], [1, 0, 2], [0, 2, 1]]) { + expect(edgeLines(model(order_.map((i) => edges[i]!)))).toEqual(expected); + } + }); + + it("sorts it after member: an edge's member decides before its receiver", () => { + const named = (member: string, receiver: string): Edge => ({ ...access(receiver), member } as unknown as Edge); + const order_ = edgeLines(model([named("b", "other"), named("a", "self")])).map((text) => JSON.parse(text) as { member: string }); + expect(order_.map((e) => e.member)).toEqual(["a", "b"]); + }); +}); + +describe("the integrity rule: receiver ⇒ access, to an entity that is not a stub", () => { + it("accepts a receiver on an access to a corpus field", () => { + expect(receiverViolations(model([access("self"), access("other", 5)]))).toEqual([]); + }); + + it("names an access to a stub, and a receiver on another kind read off the wire", () => { + const toStub = { ...access("other", 5, system), member: "out" } as unknown as Edge; + const wrongKind = { ...access(undefined, 6, order, "reference"), receiver: "self" } as unknown as Edge; + expect(receiverViolations(model([access("self"), toStub, wrongKind])).map((v) => [v.path, v.reason])).toEqual([ + ["edges[1]", "target-stub"], + ["edges[2]", "kind"], + ]); + }); + + it("says nothing about an edge without one", () => { + expect(receiverViolations(model([access(undefined, 5, system)]))).toEqual([]); + }); +}); + +describe("properties", () => { + const isStub = new Set([system, stubPkg]); + const arbEdge = fc + .record({ + kind: fc.constantFrom("access", "invocation", "reference"), + to: fc.constantFrom(lines, order, system), + at: fc.integer({ min: 4, max: 6 }), + receiver: fc.option(fc.constantFrom(...RECEIVERS), { nil: undefined }), + }) + .map(({ kind, to, at, receiver }) => { + const edge = access(undefined, at, to, kind) as unknown as Record; + if (receiver !== undefined) edge["receiver"] = receiver; + return edge as unknown as Edge; + }); + + it("violations are exactly the receivers on another kind or to a stub", () => { + fc.assert( + fc.property(fc.array(arbEdge, { maxLength: 12 }), (edges) => { + const expected = edges.flatMap((edge, index) => { + if (edge.receiver === undefined) return []; + if (edge.edge !== "access") return [`edges[${index}]`]; + return isStub.has(edge.to) ? [`edges[${index}]`] : []; + }); + expect(receiverViolations(model(edges)).map((v) => v.path)).toEqual(expected); + }), + ); + }); + + it("encode is order-invariant and decode ∘ encode keeps every receiver", () => { + const accesses = arbEdge.filter((edge) => edge.edge === "access"); + fc.assert( + fc.property( + fc.array(accesses, { maxLength: 12 }).chain((edges) => fc.tuple(fc.constant(edges), fc.shuffledSubarray(edges, { minLength: edges.length, maxLength: edges.length }))), + ([edges, shuffled]) => { + const text = encodeModelToString(model(edges)); + expect(encodeModelToString(model(shuffled))).toBe(text); + const back = decodeModel(text.split("\n")); + const count = (list: readonly Edge[]): string[] => list.map((e) => JSON.stringify([e.to, e.anchor.span[0], e.receiver ?? null])).sort(); + expect(count(back.edges)).toEqual(count(edges)); + expect(encodeModelToString(back)).toBe(text); + }, + ), + ); + }); +}); diff --git a/packages/core/test/traits.test.ts b/packages/core/test/traits.test.ts index dfa9c690..f22f27a8 100644 --- a/packages/core/test/traits.test.ts +++ b/packages/core/test/traits.test.ts @@ -16,13 +16,16 @@ const EXPECTED_KEYS: Record = { TType: ["isStub"], TWithInheritances: [], TWithImplements: [], - TTypedEntity: ["declaredType"], + // MM-7: the written type as a tree, beside the erased head. + TTypedEntity: ["declaredType", "typeExpr"], TInvocable: ["signature"], TWithParameters: ["parameters"], TWithLocalVariables: ["localVariables"], TWithInvocations: [], TStructural: [], TWithAccesses: [], + // MM-8: a marker. + TWithReceiver: [], TMetrics: ["metrics"], TWithValue: ["value"], }; diff --git a/packages/core/test/type-expr.test.ts b/packages/core/test/type-expr.test.ts new file mode 100644 index 00000000..05707960 --- /dev/null +++ b/packages/core/test/type-expr.test.ts @@ -0,0 +1,270 @@ +import { existsSync, readFileSync, readdirSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import fc from "fast-check"; +import { describe, expect, it } from "vitest"; + +import { Entity } from "../src/entity.js"; +import { unknownReferences } from "../src/integrity.js"; +import { decodeModel, encodeModel, encodeModelToString } from "../src/jsonl.js"; +import { SCHEMA_VERSION, parseModel, type Model } from "../src/model.js"; +import { TRAITS } from "../src/traits.js"; +import { TYPE_EXPR_FORMS, TypeExpr, typeExprReferences } from "../src/type-expr.js"; +import { EntityRec, WIRE_TRAITS, WireTypeExpr } from "../src/wire.js"; + +/** + * MM-7 (docs/model-metamodel.md, PLAN §26.2): a typed entity carries the type + * it WRITES as a tree, ids inside as surrogates on the wire. + */ + +const pkg = "java:com.acme.order"; +const basket = "java:com.acme.order/Basket"; +const lines = "java:com.acme.order/Basket.lines"; +const line = "java:com.acme.order/OrderLine"; +const stubPkg = "java:java.util"; +const list = "java:java.util/List"; +const map = "java:java.util/Map"; + +const ENTITIES = [ + { id: pkg, kind: "package", traits: ["TNamed", "TModule", "TWithChildren"], name: "com.acme.order", definedIn: ["B.java"], isStub: false }, + { + id: basket, + kind: "class", + traits: ["TNamed", "TType", "TWithInheritances", "TWithImplements", "TWithChildren", "TChildOf", "TSourceAnchor"], + name: "Basket", + isStub: false, + parent: pkg, + anchor: { file: "B.java", span: [1, 9] }, + }, + { + id: line, + kind: "class", + traits: ["TNamed", "TType", "TWithInheritances", "TWithImplements", "TWithChildren", "TChildOf", "TSourceAnchor"], + name: "OrderLine", + isStub: false, + parent: pkg, + anchor: { file: "L.java", span: [1, 3] }, + }, + { id: stubPkg, kind: "package", traits: ["TNamed", "TModule", "TWithChildren"], name: "java.util", definedIn: [], isStub: true }, + { id: list, kind: "interface", traits: ["TNamed", "TType", "TChildOf"], name: "List", isStub: true, parent: stubPkg }, + { id: map, kind: "interface", traits: ["TNamed", "TType", "TChildOf"], name: "Map", isStub: true, parent: stubPkg }, +]; + +/** `Basket.lines`, typed `List` as written. */ +function field(typeExpr: TypeExpr | undefined, declaredType: string | undefined = list): Record { + const entity: Record = { + id: lines, + kind: "attribute", + traits: ["TNamed", "TStructural", "TTypedEntity", "TChildOf", "TSourceAnchor"], + name: "lines", + parent: basket, + anchor: { file: "B.java", span: [2, 2] }, + }; + if (declaredType !== undefined) entity["declaredType"] = declaredType; + if (typeExpr !== undefined) entity["typeExpr"] = typeExpr; + return entity; +} + +const LIST_OF_LINES: TypeExpr = { k: "named", type: list, args: [{ k: "named", type: line }] }; + +function model(extra: Record[], schemaVersion = SCHEMA_VERSION): Model { + return { + schemaVersion, + lang: "java", + extractor: { name: "test", version: "0" }, + root: "demo", + entities: [...ENTITIES, ...extra], + edges: [], + } as unknown as Model; +} + +const entityLine = (m: Model, symbol: string): string => + [...encodeModel(m)].find((text) => text.startsWith('{"t":"e"') && text.includes(`"s":"${symbol}"`))!; + +describe("the value (MM-7)", () => { + const EVERY_FORM: TypeExpr[] = [ + { k: "named", type: list, args: [{ k: "named", type: line }] }, + { k: "primitive", name: "long" }, + { k: "array", of: { k: "primitive", name: "int" } }, + { k: "nullable", of: { k: "named", type: line } }, + { k: "function", params: [{ k: "variable", name: "T" }], returns: { k: "primitive", name: "boolean" } }, + { k: "union", of: [{ k: "named", type: line }, { k: "primitive", name: "null" }] }, + { k: "variable", name: "T" }, + { k: "unevaluated", source: "? extends Number" }, + ]; + + it("is a closed tagged union of exactly the eight forms of PLAN §26.2", () => { + expect([...TYPE_EXPR_FORMS]).toEqual(["named", "primitive", "array", "nullable", "function", "union", "variable", "unevaluated"]); + expect(EVERY_FORM.map((expr) => expr.k)).toEqual([...TYPE_EXPR_FORMS]); + for (const expr of EVERY_FORM) expect(TypeExpr.safeParse(expr).success, expr.k).toBe(true); + expect(TypeExpr.safeParse({ k: "wildcard", bound: "Number" }).success).toBe(false); + }); + + it("keeps each form canonical: no empty argument list, no one-member union, no empty word", () => { + expect(TypeExpr.safeParse({ k: "named", type: list }).success).toBe(true); + expect(TypeExpr.safeParse({ k: "named", type: list, args: [] }).success).toBe(false); + expect(TypeExpr.safeParse({ k: "union", of: [{ k: "variable", name: "T" }] }).success).toBe(false); + expect(TypeExpr.safeParse({ k: "primitive", name: "" }).success).toBe(false); + expect(TypeExpr.safeParse({ k: "variable", name: "" }).success).toBe(false); + expect(TypeExpr.safeParse({ k: "unevaluated", source: "" }).success).toBe(false); + // A function returning nothing writes no `returns`; one taking nothing, an empty list. + expect(TypeExpr.safeParse({ k: "function", params: [] }).success).toBe(true); + }); + + it("is the optional second key of TTypedEntity; declaredType is untouched", () => { + expect(Object.keys(TRAITS.TTypedEntity.shape).sort()).toEqual(["declaredType", "typeExpr"]); + expect(TRAITS.TTypedEntity.safeParse({}).success).toBe(true); + expect(TRAITS.TTypedEntity.safeParse({ typeExpr: LIST_OF_LINES }).success).toBe(true); + expect(TRAITS.TTypedEntity.safeParse({ typeExpr: { k: "named", type: 3 } }).success).toBe(false); + expect(Entity.safeParse(field(LIST_OF_LINES)).success).toBe(true); + expect(Entity.safeParse(field({ k: "array" } as unknown as TypeExpr)).success).toBe(false); + }); + + it("names every id inside it, in written order, with its path", () => { + const fn: TypeExpr = { + k: "function", + params: [LIST_OF_LINES, { k: "array", of: { k: "nullable", of: { k: "named", type: map } } }], + returns: { k: "union", of: [{ k: "named", type: basket }, { k: "unevaluated", source: "?" }] }, + }; + expect(typeExprReferences(fn, "x")).toEqual([ + { path: "x.params[0].type", id: list }, + { path: "x.params[0].args[0].type", id: line }, + { path: "x.params[1].of.of.type", id: map }, + { path: "x.returns.of[0].type", id: basket }, + ]); + }); +}); + +describe("closure reaches inside a type expression", () => { + const missing = "java:com.acme.order/Missing"; + + it("reports a dangling id at its path", () => { + const dangling: TypeExpr = { k: "named", type: list, args: [{ k: "named", type: missing }] }; + const index = ENTITIES.length; + expect(unknownReferences(parseModel(model([field(dangling)])))).toEqual([ + { path: `entities[${index}].typeExpr.args[0].type`, id: missing }, + ]); + expect(unknownReferences(parseModel(model([field(LIST_OF_LINES)])))).toEqual([]); + }); + + it("makes a dangling id UNWRITABLE: the encoder has no surrogate to name it with", () => { + const dangling: TypeExpr = { k: "array", of: { k: "named", type: missing } }; + expect(() => encodeModelToString(model([field(dangling)]))).toThrow(/typeExpr references an entity this model does not declare/); + }); + + it("makes a dangling surrogate UNREADABLE: the reader refuses it as closure", () => { + const text = encodeModelToString(model([field(LIST_OF_LINES)])); + const broken = text.replace(/"typeExpr":\{"k":"named","type":\d+/, '"typeExpr":{"k":"named","type":999'); + expect(broken).not.toBe(text); + expect(() => decodeModel(broken.split("\n"))).toThrow(/typeExpr 999 resolves to no entity \(closure\)/); + }); +}); + +describe("the wire", () => { + it("writes surrogates inside the tree, right after declaredType, keys in canonical order", () => { + // Built with its keys in a scrambled order: the bytes must not care. + const scrambled = { args: [{ type: line, k: "named" }], type: list, k: "named" } as unknown as TypeExpr; + const text = entityLine(model([field(scrambled)]), "Basket.lines"); + expect(text).toBe( + '{"t":"e","i":2,"k":0,"tr":[2,4,6,0,3],"m":0,"s":"Basket.lines","name":"lines","declaredType":5,' + + '"typeExpr":{"k":"named","type":5,"args":[{"k":"named","type":3}]},"parent":1,"anchor":[0,2,2]}', + ); + expect(EntityRec.safeParse(JSON.parse(text)).success).toBe(true); + }); + + it("types the key on the record and on the trait, as surrogates only", () => { + expect(Object.keys(WIRE_TRAITS.TTypedEntity.shape).sort()).toEqual(["declaredType", "typeExpr"]); + expect(WireTypeExpr.safeParse({ k: "named", type: 3, args: [{ k: "primitive", name: "int" }] }).success).toBe(true); + expect(WireTypeExpr.safeParse({ k: "named", type: list }).success).toBe(false); + }); + + it("round-trips every form, and an entity without one decodes without the key", () => { + const fn: TypeExpr = { + k: "function", + params: [{ k: "array", of: { k: "primitive", name: "int" } }, { k: "variable", name: "T" }], + returns: { k: "nullable", of: { k: "union", of: [LIST_OF_LINES, { k: "unevaluated", source: "Map" }] } }, + }; + const original = model([field(fn), { ...field(undefined, undefined), id: `${lines}2`, name: "lines2" }]); + const back = decodeModel(encodeModelToString(original).split("\n")); + const byId = new Map(back.entities.map((entity) => [entity.id, entity as Record])); + expect(byId.get(lines)!["typeExpr"]).toEqual(fn); + expect(Object.hasOwn(byId.get(`${lines}2`)!, "typeExpr")).toBe(false); + }); +}); + +describe("the schema version (1.1.0 → 1.2.0, additive)", () => { + it("is 1.2.0", () => { + expect(SCHEMA_VERSION).toBe("1.2.0"); + }); + + it("still decodes a 1.1.0 and a 1.0.0 file, and keeps the version each states", () => { + for (const version of ["1.1.0", "1.0.0"]) { + const old = model([field(undefined)], version); + const back = decodeModel(encodeModelToString(old).split("\n")); + expect(back.schemaVersion).toBe(version); + expect(back.entities).toEqual(expect.arrayContaining(old.entities.map((e) => expect.objectContaining(e)))); + } + }); + + // Every committed snapshot was written before MM-7 (1.1.0 or 1.0.0): re-encoding + // each is the identity, so an entity with no typeExpr costs not one byte. + const fixtures = fileURLToPath(new URL("../../../fixtures/", import.meta.url)); + for (const lang of readdirSync(fixtures).sort()) { + for (const name of ["model.jsonl", "model.metrics.jsonl"]) { + const path = `${fixtures}${lang}/expected/${name}`; + if (!existsSync(path)) continue; + it(`re-encodes fixtures/${lang}/expected/${name} byte for byte`, () => { + const text = readFileSync(path, "utf8"); + expect(encodeModelToString(decodeModel(text.split("\n")))).toBe(text); + }); + } + } +}); + +describe("properties", () => { + const pool = [basket, line, list, map] as const; + const ids = fc.constantFrom(...pool); + const word = fc.constantFrom("int", "T", "K", "délai", 'a"b'); + + const { expr } = fc.letrec<{ expr: TypeExpr }>((tie) => ({ + expr: fc.oneof( + { depthSize: "small", withCrossShrink: true }, + fc.record({ k: fc.constant("primitive" as const), name: word }), + fc.record({ k: fc.constant("variable" as const), name: word }), + fc.record({ k: fc.constant("unevaluated" as const), source: word }), + fc + .tuple(ids, fc.option(fc.array(tie("expr"), { minLength: 1, maxLength: 2 }), { nil: undefined })) + .map(([type, args]): TypeExpr => (args === undefined ? { k: "named", type } : { k: "named", type, args })), + tie("expr").map((of): TypeExpr => ({ k: "array", of })), + tie("expr").map((of): TypeExpr => ({ k: "nullable", of })), + fc + .tuple(fc.array(tie("expr"), { maxLength: 2 }), fc.option(tie("expr"), { nil: undefined })) + .map(([params, returns]): TypeExpr => (returns === undefined ? { k: "function", params } : { k: "function", params, returns })), + fc.array(tie("expr"), { minLength: 2, maxLength: 3 }).map((of): TypeExpr => ({ k: "union", of })), + ), + })); + + it("every generated expression is a valid TypeExpr, its references drawn from the pool", () => { + fc.assert( + fc.property(expr, (value) => { + expect(TypeExpr.safeParse(value).success).toBe(true); + for (const ref of typeExprReferences(value)) expect(pool).toContain(ref.id); + }), + ); + }); + + it("decode ∘ encode is the identity on a model carrying type expressions, and encode is its fixed point", () => { + fc.assert( + fc.property(fc.array(fc.option(expr, { nil: undefined }), { minLength: 1, maxLength: 4 }), (exprs) => { + const fields: Record[] = exprs.map((value, index) => ({ ...field(value, index % 2 === 0 ? list : undefined), id: `${lines}${index}`, name: `f${index}` })); + for (const entity of fields) if (entity["typeExpr"] === undefined) delete entity["typeExpr"]; + const original = parseModel(model(fields)); + const text = encodeModelToString(original); + const back = decodeModel(text.split("\n")); + const sorted = (m: Model) => [...m.entities].sort((a, b) => (a.id < b.id ? -1 : 1)); + expect(sorted(back)).toEqual(sorted(original)); + expect(encodeModelToString(back)).toBe(text); + expect(unknownReferences(back)).toEqual([]); + }), + ); + }); +}); diff --git a/packages/dataop/package.json b/packages/dataop/package.json new file mode 100644 index 00000000..8308cef0 --- /dev/null +++ b/packages/dataop/package.json @@ -0,0 +1,34 @@ +{ + "name": "@codegraph/dataop", + "version": "0.4.0", + "license": "MIT", + "type": "module", + "description": "Codegraph Data & Operation lowering: a code graph printed as a Specy .dataop model at the observed level", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "build": "tsup", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@codegraph/analyzer": "workspace:*", + "@codegraph/core": "workspace:*" + }, + "devDependencies": { + "@types/node": "catalog:", + "fast-check": "catalog:", + "tsup": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:" + } +} diff --git a/packages/dataop/src/index.ts b/packages/dataop/src/index.ts new file mode 100644 index 00000000..18e027e0 --- /dev/null +++ b/packages/dataop/src/index.ts @@ -0,0 +1,16 @@ +/** + * `@codegraph/dataop` — a code graph lowered into a Specy Data & Operation + * model (`.dataop`) at the `observed` level (PLAN.md §26). + * + * PURE COMPUTATION, like `@codegraph/city` and `@codegraph/vocabulary`: it + * reads the analyzer's graph and returns text. No DOM, no I/O, no provider. + * `lower` builds the value, `print` writes it, `formatSummary` says what was + * and was not lowered. + */ +export * from "./model.js"; +export * from "./names.js"; +export * from "./type-tables.js"; +export { lower, defaultModelName, receiverKinds, DataOpError, type LowerOptions } from "./lower.js"; +export { print, printType, headerLines, receiverSentence, typeSentence, RECEIVER_FALLBACK } from "./print.js"; +export { summarize, formatSummary, type LoweringTally } from "./summary.js"; +export { compareText, qnameKey, refKey, typeKey } from "./keys.js"; diff --git a/packages/dataop/src/keys.ts b/packages/dataop/src/keys.ts new file mode 100644 index 00000000..6de45723 --- /dev/null +++ b/packages/dataop/src/keys.ts @@ -0,0 +1,39 @@ +import type { DataOpType, QName, Ref } from "./model.js"; + +/** + * Canonical keys over NAMES: what the lowering dedups and orders by. None of + * them reads an id, so the output's order is a function of the names the + * model holds and of nothing a producer is free to choose (§26.9). + */ + +/** UTF-16 code-unit order, the order every codegraph artifact uses. */ +export function compareText(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +/** NUL separates segments: no name a model holds may make two QNames collide. */ +export function qnameKey(name: QName): string { + return `${name.module === null ? "\u0001" : name.module.join("\u0000")}\u0002${name.path.join("\u0000")}`; +} + +export function refKey(ref: Ref): string { + return `${ref.kind}\u0003${qnameKey(ref.name)}`; +} + +/** A type's canonical text: equal exactly when the constructor trees are equal. */ +export function typeKey(type: DataOpType): string { + switch (type.k) { + case "scalar": + return type.name; + case "array": + return `array<${typeKey(type.of)}>`; + case "nullable": + return `${typeKey(type.of)}?`; + case "ref": + return [...(type.ref.name.module ?? []), ...type.ref.name.path].join("."); + case "function": + return `(${type.params.map(typeKey).join(", ")}) -> ${type.returns === undefined ? "void" : typeKey(type.returns)}`; + case "opaque": + return `opaque ${JSON.stringify(type.text)}`; + } +} diff --git a/packages/dataop/src/lower.ts b/packages/dataop/src/lower.ts new file mode 100644 index 00000000..24e233e6 --- /dev/null +++ b/packages/dataop/src/lower.ts @@ -0,0 +1,1128 @@ +import { + getProfile, + isStubEntity, + type Edge, + type Entity, + type EntityId, + type Literal, + type SourceAnchor, + type TypeExpr, +} from "@codegraph/core"; +import { entityName, folderFor, hasTrait, type CodeGraph } from "@codegraph/analyzer"; +import { isModelName, isOneLine, kebabModelName } from "./names.js"; +import { typeTableOf, isEmptyTable, type Scalar, type TypeTable } from "./type-tables.js"; +import type { + AccessItem, + DataOpModel, + DataOpType, + DependencyItem, + EdgeClause, + ErrorItem, + ExternalDecl, + FieldDecl, + Finding, + GlobalDecl, + InitialValue, + LanguageNote, + LedgerEntry, + ModuleDecl, + NotDeclaredReason, + OperationDecl, + Param, + QName, + Ref, + StructDecl, + UseItem, +} from "./model.js"; +import { summarize } from "./summary.js"; +import { compareText, qnameKey, refKey, typeKey } from "./keys.js"; + +/** + * THE LOWERING (PLAN.md §26.4): a code graph → a {@link DataOpModel}, at + * Specy's `observed` level. It states what the model holds and nothing else: + * where a fact is missing the value says `opaque`, `?` or a finding. + * + * Every name comes from an entity's `name` (and its ancestors', for a nested + * path) and every module from its module entity's `name`, split where its + * profile says the qualifier is a dot. No id is ever parsed or compared for + * order: an id is only a handle into the graph, so a model whose ids are + * scrambled lowers to the same text (§26.9). + */ + +export interface LowerOptions { + /** The model's name; default: the first model's root, last segment, kebab-case. */ + readonly name?: string | undefined; + /** Operations the boundary rules put in the entry inventory by a declaration-site rule (§25.2): marked `entry`. */ + readonly entries?: Iterable | undefined; + /** Operations the inventory INFERRED (no caller, a concept label): marked `entry?`, never `entry`. */ + readonly candidateEntries?: Iterable | undefined; + /** + * `--scope`: a module is lowered when this matches it or anything it + * contains. What falls outside is external. Absent: every corpus module. + */ + readonly scope?: { matches(id: EntityId): boolean } | undefined; +} + +/** A lowering that cannot produce a model: nothing to lower, or a bad name. */ +export class DataOpError extends Error { + constructor(message: string) { + super(message); + this.name = "DataOpError"; + } +} + +const CONTRACT_WITH_RECEIVER = [1, 2, 0] as const; + +function atLeast(version: string, floor: readonly number[]): boolean { + const parts = version.split(".").map((part) => Number.parseInt(part, 10)); + for (let i = 0; i < floor.length; i += 1) { + const have = parts[i] ?? 0; + const want = floor[i] ?? 0; + if (Number.isNaN(have)) return false; + if (have !== want) return have > want; + } + return true; +} + +function anchorOf(entity: Entity): SourceAnchor | undefined { + const anchor = (entity as Record)["anchor"]; + return typeof anchor === "object" && anchor !== null ? (anchor as SourceAnchor) : undefined; +} + +function keyOf(entity: Entity, key: string): T | undefined { + return (entity as Record)[key] as T | undefined; +} + +/** The model name a root gives (`fixtures/java/src` → `src`), or `model`. */ +export function defaultModelName(root: string): string { + const segments = root.split(/[\\/]/u).filter((segment) => segment.length > 0 && segment !== "."); + return kebabModelName(segments[segments.length - 1] ?? "") ?? "model"; +} + +export function lower(graph: CodeGraph, options: LowerOptions = {}): DataOpModel { + const folder = folderFor(graph); + const name = options.name ?? defaultModelName(graph.union.models[0]?.root ?? ""); + if (!isModelName(name)) { + throw new DataOpError(`"${name}" is not a model name: kebab-case words, each starting with a lowercase letter`); + } + + // ------------------------------------------------------------------ + // Which model each entity comes from: its language, its contract. + // ------------------------------------------------------------------ + const modelIndexOf = new Map(); + graph.union.models.forEach((model, index) => { + for (const entity of model.entities) if (!modelIndexOf.has(entity.id)) modelIndexOf.set(entity.id, index); + }); + const models = graph.union.models; + const writesTypeExprs = models.map( + (model) => + atLeast(model.schemaVersion, CONTRACT_WITH_RECEIVER) && + model.entities.some((entity) => keyOf(entity, "typeExpr") !== undefined), + ); + const langOf = (id: EntityId): string => models[modelIndexOf.get(id) ?? 0]?.lang ?? ""; + const tableOf = (id: EntityId): TypeTable => typeTableOf(langOf(id)); + const typedModel = (id: EntityId): boolean => writesTypeExprs[modelIndexOf.get(id) ?? 0] ?? false; + + const receiverKindsCache = new Map(); + const receiverKindsOf = (lang: string): readonly string[] => { + const cached = receiverKindsCache.get(lang); + if (cached !== undefined) return cached; + const kinds = receiverKinds(lang); + receiverKindsCache.set(lang, kinds); + return kinds; + }; + /** Whether this entity's `TWithReceiver` (or its absence) is a fact (the ruling of §26.4). */ + const receiverKnown = (entity: Entity): boolean => { + const model = models[modelIndexOf.get(entity.id) ?? 0]; + if (model === undefined || !atLeast(model.schemaVersion, CONTRACT_WITH_RECEIVER)) return false; + return receiverKindsOf(model.lang).includes(entity.kind); + }; + + // ------------------------------------------------------------------ + // Names and modules. + // ------------------------------------------------------------------ + const qualifierOf = (entity: Entity): string | undefined => { + const qualified = getProfile(langOf(entity.id))?.lexicon?.qualified; + return qualified !== undefined && Object.hasOwn(qualified, entity.kind) ? qualified[entity.kind] : undefined; + }; + const moduleSegmentsCache = new Map(); + /** A module's name, segment by segment where its profile's qualifier is the dot `.dataop` qualifies with. */ + const moduleSegments = (id: EntityId): readonly string[] => { + const cached = moduleSegmentsCache.get(id); + if (cached !== undefined) return cached; + const entity = graph.entity(id); + const name = entity === undefined ? "" : (entityName(entity) ?? ""); + const parts = entity !== undefined && qualifierOf(entity) === "." ? name.split(".") : [name]; + const segments = parts.every((part) => part.length > 0) ? parts : [name]; + moduleSegmentsCache.set(id, segments); + return segments; + }; + + const isModule = (entity: Entity): boolean => hasTrait(entity, "TModule"); + const isType = (entity: Entity): boolean => hasTrait(entity, "TType") && !isModule(entity); + const isNamed = (entity: Entity): boolean => entityName(entity) !== undefined; + const moduleOf = (id: EntityId): EntityId | undefined => folder.containingModule(id); + + /** Ancestors strictly between the entity and its module, nearest first. */ + const ancestorsBelowModule = (id: EntityId): EntityId[] => { + const out: EntityId[] = []; + const self = graph.entity(id); + if (self === undefined || isModule(self)) return out; + const seen = new Set([id]); + let cursor = graph.parentOf(id); + while (cursor !== undefined && !seen.has(cursor)) { + seen.add(cursor); + const entity = graph.entity(cursor); + if (entity === undefined || isModule(entity)) break; + out.push(cursor); + cursor = graph.parentOf(cursor); + } + return out; + }; + /** True when a nameless type encloses the entity: what it holds folds or is dropped, never lowered. */ + const underAnonymousType = (id: EntityId): boolean => + ancestorsBelowModule(id).some((ancestor) => { + const entity = graph.entity(ancestor); + return entity !== undefined && isType(entity) && !isNamed(entity); + }); + + // Scope: which corpus modules are lowered. + const corpusModules = graph + .ids() + .map((id) => graph.entity(id)) + .filter((entity): entity is Entity => entity !== undefined && isModule(entity) && !isStubEntity(entity)); + const scoped = new Set(); + if (options.scope === undefined) { + for (const module of corpusModules) scoped.add(module.id); + } else { + const scope = options.scope; + for (const module of corpusModules) if (scope.matches(module.id)) scoped.add(module.id); + for (const id of graph.ids()) { + if (!scope.matches(id)) continue; + const module = moduleOf(id); + if (module !== undefined && corpusModules.some((candidate) => candidate.id === module)) scoped.add(module); + } + } + if (scoped.size === 0) { + throw new DataOpError( + corpusModules.length === 0 ? "the model declares no corpus module: nothing to lower" : "the scope selects no module: nothing to lower", + ); + } + const lowered = (id: EntityId): boolean => { + const module = moduleOf(id); + return module !== undefined && scoped.has(module); + }; + + // ------------------------------------------------------------------ + // What each entity becomes. + // ------------------------------------------------------------------ + /** A named corpus type outside any nameless type: a struct wherever its module is (lowered or external). */ + const isStructEntity = (entity: Entity): boolean => + isType(entity) && isNamed(entity) && !isStubEntity(entity) && moduleOf(entity.id) !== undefined && !underAnonymousType(entity.id); + + const structPathCache = new Map(); + /** A type's path below its module, one segment: `Basket.Line`, or the name itself where the profile qualifies it. */ + const structPath = (id: EntityId): string => { + const cached = structPathCache.get(id); + if (cached !== undefined) return cached; + const entity = graph.entity(id); + const own = entity === undefined ? "" : (entityName(entity) ?? ""); + let path = own; + if (entity !== undefined && qualifierOf(entity) === undefined) { + const names = ancestorsBelowModule(id) + .map((ancestor) => graph.entity(ancestor)) + .map((ancestor) => (ancestor === undefined ? undefined : entityName(ancestor))) + .filter((ancestorName): ancestorName is string => ancestorName !== undefined) + .reverse(); + path = [...names, own].join("."); + } + structPathCache.set(id, path); + return path; + }; + + const isConstructor = (entity: Entity): boolean => { + if (!hasTrait(entity, "TInvocable") || isNamed(entity)) return false; + if (!tableOf(entity.id).constructorKinds.includes(entity.kind)) return false; + const parent = graph.parentOf(entity.id); + const parentEntity = parent === undefined ? undefined : graph.entity(parent); + return parentEntity !== undefined && isStructEntity(parentEntity); + }; + /** Lowered as an `operation`: named, or a constructor; a delegate (also a type) is a struct. */ + const isOperationEntity = (entity: Entity): boolean => + hasTrait(entity, "TInvocable") && + !isType(entity) && + !isModule(entity) && + !isStubEntity(entity) && + (isNamed(entity) || isConstructor(entity)) && + moduleOf(entity.id) !== undefined && + !underAnonymousType(entity.id); + + /** The nearest self-or-ancestor lowered as an operation, below the module. */ + const operationAbove = (id: EntityId): EntityId | undefined => { + const self = graph.entity(id); + if (self !== undefined && isOperationEntity(self)) return id; + for (const ancestor of ancestorsBelowModule(id)) { + const entity = graph.entity(ancestor); + if (entity !== undefined && isOperationEntity(entity)) return ancestor; + } + return undefined; + }; + + /** The nearest ancestor that is a struct, if any, below the module. */ + const structAbove = (id: EntityId): EntityId | undefined => { + for (const ancestor of ancestorsBelowModule(id)) { + const entity = graph.entity(ancestor); + if (entity !== undefined && isStructEntity(entity)) return ancestor; + } + return undefined; + }; + + /** A member's path below its container (struct or module): named intermediates, then its own name. */ + const memberPath = (entity: Entity, container: EntityId | undefined): string => { + const own = entityName(entity) ?? ""; + if (qualifierOf(entity) !== undefined) return own; + const names: string[] = []; + for (const ancestor of ancestorsBelowModule(entity.id)) { + if (ancestor === container) break; + const ancestorEntity = graph.entity(ancestor); + const ancestorName = ancestorEntity === undefined ? undefined : entityName(ancestorEntity); + if (ancestorName !== undefined) names.push(ancestorName); + } + return [...names.reverse(), own].join("."); + }; + + /** Whether a structural child of a struct is a schema field (it has a receiver, or the fallback says so). */ + const isSchemaField = (entity: Entity): boolean => (receiverKnown(entity) ? hasTrait(entity, "TWithReceiver") : true); + + type StructuralRole = + | { readonly k: "field"; readonly struct: EntityId } + | { readonly k: "global"; readonly struct: EntityId | undefined; readonly module: EntityId; readonly name: string } + | { readonly k: "local" } + | { readonly k: "none"; readonly reason: string }; + const roleCache = new Map(); + const structuralRole = (entity: Entity): StructuralRole => { + const cached = roleCache.get(entity.id); + if (cached !== undefined) return cached; + let role: StructuralRole; + const module = moduleOf(entity.id); + const parent = graph.parentOf(entity.id); + const parentEntity = parent === undefined ? undefined : graph.entity(parent); + if (!hasTrait(entity, "TStructural")) role = { k: "none", reason: "not a value holder" }; + else if (module === undefined) role = { k: "none", reason: "outside every module" }; + else if (underAnonymousType(entity.id)) role = { k: "none", reason: "a member of a nameless type" }; + else if ( + ancestorsBelowModule(entity.id).some((ancestor) => { + const ancestorEntity = graph.entity(ancestor); + return ancestorEntity !== undefined && hasTrait(ancestorEntity, "TInvocable") && !isType(ancestorEntity); + }) + ) + role = { k: "local" }; + else if (parent !== undefined && parentEntity !== undefined && isStructEntity(parentEntity)) { + role = isSchemaField(entity) + ? { k: "field", struct: parent } + : { k: "global", struct: parent, module, name: entityName(entity) ?? "" }; + } else { + const struct = structAbove(entity.id); + role = { k: "global", struct, module, name: memberPath(entity, struct) }; + } + roleCache.set(entity.id, role); + return role; + }; + + // ------------------------------------------------------------------ + // References, and the external declarations they need. + // ------------------------------------------------------------------ + const externalsByKey = new Map(); + const needExternal = (decl: ExternalDecl, declaredIn: EntityId | undefined): void => { + const key = `${decl.kind}|${qnameKey(decl.name)}`; + if (!externalsByKey.has(key)) externalsByKey.set(key, { decl, module: declaredIn }); + }; + const needExternalModule = (module: EntityId): void => { + needExternal({ kind: "external-module", name: { module: moduleSegments(module), path: [] }, entity: module }, undefined); + }; + + /** A struct reference for a type entity: a struct of the model, or an external struct (declared on demand). */ + const typeRef = (id: EntityId): Ref | undefined => { + const entity = graph.entity(id); + if (entity === undefined || !isType(entity) || !isNamed(entity) || underAnonymousType(id)) return undefined; + const module = moduleOf(id); + const name: QName = { module: module === undefined ? null : moduleSegments(module), path: [structPath(id)] }; + if (!isStubEntity(entity) && module !== undefined && scoped.has(module)) return { kind: "struct", name }; + const decl: ExternalDecl = { kind: "external-struct", name, entity: id }; + if (module !== undefined && scoped.has(module)) needExternal(decl, module); + else { + if (module !== undefined) needExternalModule(module); + needExternal(decl, undefined); + } + return { kind: "external-struct", name }; + }; + /** What a call into something outside the model uses: its type, else its module. */ + const externalRefOf = (id: EntityId): Ref | undefined => { + const entity = graph.entity(id); + if (entity === undefined) return undefined; + if (isModule(entity)) { + needExternalModule(id); + return { kind: "external-module", name: { module: moduleSegments(id), path: [] } }; + } + if (isType(entity)) return typeRef(id); + const type = folder.containingType(id); + if (type !== undefined && type !== id) { + const ref = typeRef(type); + if (ref !== undefined) return ref; + } + const module = moduleOf(id); + if (module === undefined) return undefined; + needExternalModule(module); + return { kind: "external-module", name: { module: moduleSegments(module), path: [] } }; + }; + + // ------------------------------------------------------------------ + // Types (§26.4, "Types"). + // ------------------------------------------------------------------ + /** A library type's meaning in the type table, matched on its name and its parent module's name. */ + function stubMeaning(id: EntityId): Scalar | "sequence" | "optional" | undefined { + const entity = graph.entity(id); + if (entity === undefined || !isStubEntity(entity)) return undefined; + const stubName = entityName(entity); + const parent = graph.parentOf(id); + const parentEntity = parent === undefined ? undefined : graph.entity(parent); + const moduleName = parentEntity !== undefined && isModule(parentEntity) ? entityName(parentEntity) : undefined; + if (stubName === undefined || moduleName === undefined) return undefined; + return tableOf(id).stubs.find((row) => row.name === stubName && row.module === moduleName)?.as; + } + const isScalar = (meaning: string | undefined): meaning is Scalar => + meaning === "string" || meaning === "number" || meaning === "boolean"; + + /** The written text of a type expression, for `opaque "…"`: heads by module and path names, never an id. */ + const renderTypeExpr = (expr: TypeExpr): string => { + switch (expr.k) { + case "named": { + const entity = graph.entity(expr.type); + let head = "?"; + if (entity !== undefined) { + const module = moduleOf(expr.type); + const moduleEntity = module === undefined ? undefined : graph.entity(module); + const qualified = moduleEntity !== undefined && qualifierOf(moduleEntity) === "."; + const path = isType(entity) ? structPath(expr.type) : (entityName(entity) ?? "?"); + head = + qualified && module !== undefined && module !== expr.type ? `${moduleSegments(module).join(".")}.${path}` : path; + } + return expr.args === undefined ? head : `${head}<${expr.args.map(renderTypeExpr).join(", ")}>`; + } + case "primitive": + return expr.name; + case "array": + return `${renderTypeExpr(expr.of)}[]`; + case "nullable": + return `${renderTypeExpr(expr.of)}?`; + case "function": + return `(${expr.params.map(renderTypeExpr).join(", ")}) -> ${expr.returns === undefined ? "void" : renderTypeExpr(expr.returns)}`; + case "union": + return expr.of.map(renderTypeExpr).join(" | "); + case "variable": + return expr.name; + case "unevaluated": + return expr.source; + } + }; + const opaque = (text: string): DataOpType => ({ k: "opaque", text: isOneLine(text) ? text : "?" }); + const nullable = (of: DataOpType): DataOpType => + of.k === "nullable" ? of : of.k === "function" ? opaque(`${typeKey(of)}?`) : { k: "nullable", of }; + + const lowerTypeExpr = (expr: TypeExpr, lang: string): DataOpType => { + switch (expr.k) { + case "primitive": { + const scalar = typeTableOf(lang).primitives[expr.name]; + return scalar === undefined ? opaque(expr.name) : { k: "scalar", name: scalar }; + } + case "named": { + const meaning = stubMeaning(expr.type); + const args = expr.args ?? []; + if (isScalar(meaning) && args.length === 0) return { k: "scalar", name: meaning }; + const only = args.length === 1 ? args[0] : undefined; + if (meaning === "sequence" && only !== undefined) return { k: "array", of: lowerTypeExpr(only, lang) }; + if (meaning === "optional" && only !== undefined) return nullable(lowerTypeExpr(only, lang)); + if (args.length === 0) { + const ref = typeRef(expr.type); + if (ref !== undefined) return { k: "ref", ref }; + } + return opaque(renderTypeExpr(expr)); + } + case "array": + return { k: "array", of: lowerTypeExpr(expr.of, lang) }; + case "nullable": + return nullable(lowerTypeExpr(expr.of, lang)); + case "function": + return { + k: "function", + params: expr.params.map((param) => lowerTypeExpr(param, lang)), + returns: expr.returns === undefined ? undefined : lowerTypeExpr(expr.returns, lang), + }; + default: + return opaque(renderTypeExpr(expr)); + } + }; + + /** A typed entity's type: its expression, else its declared head, else `opaque "?"`. */ + const typeOf = (entity: Entity): DataOpType => { + const expr = keyOf(entity, "typeExpr"); + if (expr !== undefined) return lowerTypeExpr(expr, langOf(entity.id)); + const declared = keyOf(entity, "declaredType"); + if (declared !== undefined) { + const meaning = stubMeaning(declared); + if (isScalar(meaning)) return { k: "scalar", name: meaning }; + const ref = typeRef(declared); + if (ref !== undefined) return { k: "ref", ref }; + } + return opaque("?"); + }; + + /** A literal as JSON, when it is one; `undefined` for an enum, a type, an annotation, a non-finite number. */ + const jsonOf = (value: Literal): string | undefined => { + switch (value.k) { + case "string": + return isOneLine(value.v) ? `"${value.v.replace(/[\\"]/gu, (char) => `\\${char}`)}"` : undefined; + case "number": + return /^-?\d/u.test(value.v) ? value.v : undefined; + case "boolean": + return value.v ? "true" : "false"; + case "null": + return "null"; + case "array": { + const items = value.items.map(jsonOf); + return items.every((item): item is string => item !== undefined) ? `[${items.join(", ")}]` : undefined; + } + default: + return undefined; + } + }; + const initialValueOf = (entity: Entity): InitialValue => { + const value = keyOf(entity, "value"); + if (value === undefined) return { k: "opaque", text: undefined }; + if (value.k === "unevaluated") return { k: "opaque", text: isOneLine(value.source) ? value.source : undefined }; + const json = jsonOf(value); + return json === undefined ? { k: "opaque", text: undefined } : { k: "json", text: json }; + }; + + // ------------------------------------------------------------------ + // Collect the declarations. + // ------------------------------------------------------------------ + const skipped: Record = {}; + const skip = (reason: string): void => { + skipped[reason] = (skipped[reason] ?? 0) + 1; + }; + + interface StructDraft { + readonly entity: Entity; + readonly module: EntityId; + readonly own: Entity[]; + readonly globals: GlobalDecl[]; + readonly operations: EntityId[]; + } + interface ModuleDraft { + readonly entity: Entity; + readonly structs: EntityId[]; + readonly globals: GlobalDecl[]; + readonly operations: EntityId[]; + } + const moduleDrafts = new Map(); + for (const id of scoped) { + const entity = graph.entity(id); + if (entity !== undefined) moduleDrafts.set(id, { entity, structs: [], globals: [], operations: [] }); + } + const structDrafts = new Map(); + const operationIds: EntityId[] = []; + const folded = new Map(); + let unplaced = 0; + + const globalOf = (entity: Entity, name: string): GlobalDecl => ({ + name, + type: typeOf(entity), + value: initialValueOf(entity), + entity: entity.id, + anchor: anchorOf(entity), + }); + + // Pass 1: structs (their drafts must exist before members are placed). + for (const id of graph.ids()) { + const entity = graph.entity(id); + if (entity === undefined || isStubEntity(entity) || !lowered(id) || isModule(entity)) continue; + if (isType(entity)) { + if (!isNamed(entity)) continue; // its invocables fold, below + if (underAnonymousType(id)) { + skip("a type inside a nameless type"); + continue; + } + const module = moduleOf(id) as EntityId; + structDrafts.set(id, { entity, module, own: [], globals: [], operations: [] }); + moduleDrafts.get(module)?.structs.push(id); + if (hasTrait(entity, "TInvocable")) skip("an invocable type, lowered as a struct only"); + } + } + // Pass 2: members. + for (const id of graph.ids()) { + const entity = graph.entity(id); + if (entity === undefined || isStubEntity(entity) || !lowered(id) || isModule(entity) || isType(entity)) continue; + if (hasTrait(entity, "TInvocable")) { + if (isOperationEntity(entity)) { + operationIds.push(id); + continue; + } + const target = operationAbove(graph.parentOf(id) ?? id); + if (target === undefined || target === id) { + unplaced += 1; + continue; + } + const list = folded.get(target); + if (list === undefined) folded.set(target, [id]); + else list.push(id); + continue; + } + if (!hasTrait(entity, "TStructural")) continue; + const role = structuralRole(entity); + if (role.k === "field") structDrafts.get(role.struct)?.own.push(entity); + else if (role.k === "global") { + const decl = globalOf(entity, role.name); + if (role.struct !== undefined) structDrafts.get(role.struct)?.globals.push(decl); + else moduleDrafts.get(role.module)?.globals.push(decl); + } else if (role.k === "none") skip(role.reason); + } + + // ------------------------------------------------------------------ + // Schemas: own fields, then the corpus supertypes' (inheritance, embedding). + // ------------------------------------------------------------------ + const ownFieldsOf = (struct: EntityId): readonly Entity[] => { + const draft = structDrafts.get(struct); + if (draft !== undefined) return draft.own; + // A supertype outside the scope: its fields are facts all the same. + return graph + .childrenOf(struct) + .map((child) => graph.entity(child)) + .filter((child): child is Entity => child !== undefined && hasTrait(child, "TStructural") && structuralRole(child).k === "field"); + }; + const supertypesOf = (struct: EntityId): { corpus: EntityId[]; external: EntityId[] } => { + const corpus: EntityId[] = []; + const external: EntityId[] = []; + const seen = new Set([struct]); + let frontier = [struct]; + while (frontier.length > 0) { + const next: EntityId[] = []; + for (const id of frontier) { + const targets = graph + .outgoing(id) + .filter((edge) => edge.edge === "inheritance" || edge.edge === "embedding") + .map((edge) => edge.to) + .filter((to) => !seen.has(to)) + .sort((a, b) => compareText(structPath(a), structPath(b)) || compareText(moduleKey(a), moduleKey(b))); + for (const to of targets) { + if (seen.has(to)) continue; + seen.add(to); + const entity = graph.entity(to); + if (entity === undefined) continue; + if (isStructEntity(entity)) { + corpus.push(to); + next.push(to); + } else if (isType(entity)) external.push(to); + } + } + frontier = next; + } + return { corpus, external }; + }; + function moduleKey(id: EntityId): string { + const module = moduleOf(id); + return module === undefined ? "" : moduleSegments(module).join("."); + } + + interface Schema { + readonly fields: FieldDecl[]; + /** Field name → field entity, own and flattened: what `_.name` may name. */ + readonly byEntity: Set; + readonly flattened: QName[]; + readonly external: QName[]; + shadowed: number; + } + const schemaCache = new Map(); + const qnameOfStruct = (id: EntityId): QName => { + const module = moduleOf(id); + return { module: module === undefined ? null : moduleSegments(module), path: [structPath(id)] }; + }; + const fieldDecl = (entity: Entity, inheritedFrom: QName | undefined): FieldDecl => ({ + name: entityName(entity) ?? "", + type: typeOf(entity), + entity: entity.id, + anchor: anchorOf(entity), + inheritedFrom, + }); + const schemaOf = (struct: EntityId): Schema => { + const cached = schemaCache.get(struct); + if (cached !== undefined) return cached; + const schema: Schema = { fields: [], byEntity: new Set(), flattened: [], external: [], shadowed: 0 }; + const names = new Set(); + const add = (entity: Entity, from: QName | undefined): void => { + const fieldName = entityName(entity) ?? ""; + if (names.has(fieldName)) { + schema.shadowed += 1; + return; + } + names.add(fieldName); + schema.fields.push(fieldDecl(entity, from)); + schema.byEntity.add(entity.id); + }; + const own = [...ownFieldsOf(struct)].sort((a, b) => compareText(entityName(a) ?? "", entityName(b) ?? "")); + for (const entity of own) add(entity, undefined); + const supertypes = supertypesOf(struct); + for (const supertype of supertypes.corpus) { + const from = qnameOfStruct(supertype); + schema.flattened.push(from); + const inherited = [...ownFieldsOf(supertype)].sort((a, b) => compareText(entityName(a) ?? "", entityName(b) ?? "")); + for (const entity of inherited) add(entity, from); + } + for (const external of supertypes.external) { + const ref = typeRef(external); + if (ref !== undefined) schema.external.push(ref.name); + } + schemaCache.set(struct, schema); + return schema; + }; + + // ------------------------------------------------------------------ + // Operations: placement, signature, attachment. + // ------------------------------------------------------------------ + interface OperationDraft { + readonly entity: Entity; + readonly name: string; + readonly module: EntityId; + readonly container: EntityId | undefined; + readonly params: Param[]; + readonly returns: DataOpType | undefined; + readonly on: "module" | QName | undefined; + /** The struct whose instance `_` is: the attachment, when it is a struct of the model. */ + readonly receiver: EntityId | undefined; + readonly constructor: boolean; + readonly paramTypes: string; + } + const operationDrafts = new Map(); + const attachmentOf = (entity: Entity): EntityId | undefined => { + if (receiverKnown(entity) && !hasTrait(entity, "TWithReceiver")) return undefined; + const attachedTo = keyOf(entity, "attachedTo"); + if (attachedTo !== undefined) return attachedTo; + const parent = graph.parentOf(entity.id); + const parentEntity = parent === undefined ? undefined : graph.entity(parent); + return parent !== undefined && parentEntity !== undefined && isStructEntity(parentEntity) ? parent : undefined; + }; + const paramsOf = (entity: Entity): Param[] => + (keyOf(entity, "parameters") ?? []).map((paramId, index) => { + const param = graph.entity(paramId); + return { + name: (param === undefined ? undefined : entityName(param)) ?? `#${index + 1}`, + type: param === undefined ? opaque("?") : typeOf(param), + entity: paramId, + }; + }); + for (const id of operationIds) { + const entity = graph.entity(id) as Entity; + const module = moduleOf(id) as EntityId; + const container = structAbove(id); + const constructor = isConstructor(entity); + const params = paramsOf(entity); + let returns: DataOpType | undefined; + if (constructor) returns = { k: "ref", ref: { kind: "struct", name: qnameOfStruct(container as EntityId) } }; + else { + const expr = keyOf(entity, "typeExpr"); + const declared = keyOf(entity, "declaredType"); + if (expr === undefined && declared === undefined && typedModel(id) && tableOf(id).returnAlwaysWritten) returns = undefined; + else returns = typeOf(entity); + } + const attached = constructor ? undefined : attachmentOf(entity); + const attachedEntity = attached === undefined ? undefined : graph.entity(attached); + const attachedStruct = attachedEntity !== undefined && isStructEntity(attachedEntity) && lowered(attached as EntityId) ? attached : undefined; + if (attached !== undefined && attachedStruct === undefined) skip("an attachment to a struct outside the model"); + if (!constructor && attached === undefined && receiverKnown(entity) && hasTrait(entity, "TWithReceiver")) { + skip("a receiver that is no struct of the model (written on module)"); + } + let on: "module" | QName | undefined; + if (container !== undefined) { + if (attachedStruct === undefined) on = "module"; + else if (attachedStruct !== container) on = qnameOfStruct(attachedStruct); + } else if (attachedStruct !== undefined) on = qnameOfStruct(attachedStruct); + operationDrafts.set(id, { + entity, + name: constructor ? "new" : memberPath(entity, container), + module, + container, + params, + returns, + on, + receiver: attachedStruct, + constructor, + paramTypes: params.map((param) => typeKey(param.type)).join(","), + }); + if (container !== undefined) structDrafts.get(container)?.operations.push(id); + else moduleDrafts.get(module)?.operations.push(id); + } + // Overloads: operations of one container sharing a name. + const byContainerName = new Map(); + for (const [id, draft] of operationDrafts) { + const key = `${draft.container ?? `module:${draft.module}`}\u0000${draft.name}`; + const list = byContainerName.get(key); + if (list === undefined) byContainerName.set(key, [id]); + else list.push(id); + } + const overloaded = new Set(); + let ambiguousOverloads = 0; + for (const ids of byContainerName.values()) { + if (ids.length < 2) continue; + for (const id of ids) overloaded.add(id); + const seen = new Set(); + for (const id of ids) { + const types = operationDrafts.get(id)?.paramTypes ?? ""; + if (seen.has(types)) ambiguousOverloads += 1; + seen.add(types); + } + } + const operationRef = (id: EntityId): QName => { + const draft = operationDrafts.get(id) as OperationDraft; + return { + module: moduleSegments(draft.module), + path: draft.container === undefined ? [draft.name] : [structPath(draft.container), draft.name], + }; + }; + const globalRef = (entity: Entity): QName | undefined => { + const role = structuralRole(entity); + if (role.k !== "global") return undefined; + return { + module: moduleSegments(role.module), + path: role.struct === undefined ? [role.name] : [structPath(role.struct), role.name], + }; + }; + + // ------------------------------------------------------------------ + // Clauses: one pass over the edges, every one of the three kinds accounted for. + // ------------------------------------------------------------------ + interface Clauses { + errors: Map; + dependsOn: Map; + uses: Map; + reads: Map; + writes: Map; + blindSpots: Map; + } + const clauses = new Map(); + const clausesOf = (id: EntityId): Clauses => { + let found = clauses.get(id); + if (found === undefined) { + found = { errors: new Map(), dependsOn: new Map(), uses: new Map(), reads: new Map(), writes: new Map(), blindSpots: new Map() }; + clauses.set(id, found); + } + return found; + }; + const ledger: LedgerEntry[] = []; + const CLAUSE_KINDS = new Set(["invocation", "access", "throws"]); + + const addCandidateAware = (map: Map, key: string, item: T): void => { + const existing = map.get(key); + if (existing === undefined || (existing.candidate && !item.candidate)) map.set(key, item); + }; + const blindSpot = (operation: EntityId, text: string): void => { + clausesOf(operation).blindSpots.set(text, { code: "blind-spot", text }); + }; + const describeTarget = (id: EntityId): string => { + const entity = graph.entity(id); + if (entity === undefined) return "an unknown target"; + const own = entityName(entity) ?? "a nameless entity"; + const type = folder.containingType(id); + return type !== undefined && type !== id ? `${structPath(type)}.${own}` : own; + }; + + /** One invocation target → a clause item, or why none. */ + const invocationItem = ( + operation: EntityId, + target: EntityId, + candidate: boolean, + ): { clause: EdgeClause } | { reason: NotDeclaredReason } => { + const entity = graph.entity(target); + if (entity === undefined) return { reason: "target unknown" }; + const inside = !isStubEntity(entity) && lowered(target); + if (inside) { + if (isOperationEntity(entity)) { + const ref = operationRef(target); + const draft = operationDrafts.get(target) as OperationDraft; + const disambiguator = overloaded.has(target) ? draft.params.map((param) => param.type) : undefined; + const item: DependencyItem = { ref, disambiguator, candidate, target }; + addCandidateAware(clausesOf(operation).dependsOn, `${qnameKey(ref)}(${disambiguator?.map(typeKey).join(",") ?? ""})`, item); + return { clause: "depends on" }; + } + if (hasTrait(entity, "TInvocable") && !isType(entity)) return { reason: "target is a nameless invocable" }; + return { reason: "target is not an operation" }; + } + const ref = externalRefOf(target); + if (ref === undefined) return { reason: "target unknown" }; + addCandidateAware(clausesOf(operation).uses, refKey(ref), { ref, candidate }); + return { clause: "uses" }; + }; + + /** One access → its read and write items, or why none; an undeclared write is a blind spot. */ + const accessItems = ( + operation: EntityId, + edge: Extract, + ): LedgerEntry["outcome"] => { + const draft = operationDrafts.get(operation) as OperationDraft; + const declared: EdgeClause[] = []; + let reason: NotDeclaredReason | undefined; + const target = graph.entity(edge.to); + const fail = (why: NotDeclaredReason): void => { + reason ??= why; + if (edge.isWrite && why !== "the instance a constructor builds" && why !== "target is a local or a parameter") { + blindSpot(operation, `writes ${describeTarget(edge.to)}: ${why}`); + } + }; + const put = (item: AccessItem, key: string): void => { + const own = clausesOf(operation); + if (edge.isRead && item.k !== "param") { + own.reads.set(key, item); + declared.push("reads"); + } + if (edge.isWrite) { + own.writes.set(key, item); + declared.push("writes"); + } + }; + if (target === undefined) fail("target unknown"); + else if (edge.provenance === "dynamic-candidate") fail("candidate access"); + else if (isStubEntity(target) || isType(target) || isModule(target)) fail(isStubEntity(target) ? "target is external" : "target is not a value holder"); + else { + const role = structuralRole(target); + if (role.k === "local") fail("target is a local or a parameter"); + else if (role.k === "none") fail("target is not a value holder"); + else if (!lowered(edge.to)) fail("target outside the scope"); + else if (role.k === "global") { + const ref = globalRef(target) as QName; + put({ k: "global", ref, target: edge.to }, `g|${qnameKey(ref)}`); + } else { + const receiverSchema = draft.receiver === undefined ? undefined : schemaOf(draft.receiver); + const inReceiver = receiverSchema !== undefined && receiverSchema.byEntity.has(edge.to); + const receiver = edge.receiver ?? (inReceiver ? "self" : "other"); + const fieldName = entityName(target) ?? ""; + // A constructor has no `_`: what it reaches of the instance it builds is not declared (§26.4). + const ownInstance = + draft.constructor && + draft.container !== undefined && + (edge.receiver === "self" || (edge.receiver === undefined && schemaOf(draft.container).byEntity.has(edge.to))); + if (ownInstance) fail("the instance a constructor builds"); + else if (receiver === "self") { + if (inReceiver) put({ k: "self", field: fieldName, target: edge.to }, `s|${fieldName}`); + else fail("self access outside the receiver's schema"); + } else { + // Through another instance: a read is not declared; a write goes through the one parameter typed by its owner. + if (edge.isRead && !edge.isWrite) reason = "read through another instance"; + if (edge.isWrite) { + const holders = draft.params.filter((param) => { + const struct = param.type.k === "ref" && param.type.ref.kind === "struct" ? structOfQName(param.type.ref.name) : undefined; + return struct !== undefined && schemaOf(struct).byEntity.has(edge.to); + }); + if (holders.length === 1) { + const param = (holders[0] as Param).name; + clausesOf(operation).writes.set(`p|${param}|${fieldName}`, { k: "param", param, field: fieldName, target: edge.to }); + declared.push("writes"); + if (edge.isRead) reason = "read through another instance"; + } else { + blindSpot( + operation, + `writes ${describeTarget(edge.to)} through another instance: ${holders.length === 0 ? "no parameter" : `${holders.length} parameters`} typed by its owner`, + ); + reason ??= "write not attributable"; + } + } + } + } + } + if (declared.length > 0) return { declared }; + return { notDeclared: reason ?? "target is not a value holder", clause: edge.isWrite ? "writes" : "reads" }; + }; + // A struct of the model by its QName: the reverse of `qnameOfStruct`, over the drafts only. + const structByKey = new Map(); + for (const id of structDrafts.keys()) structByKey.set(qnameKey(qnameOfStruct(id)), id); + function structOfQName(name: QName): EntityId | undefined { + return structByKey.get(qnameKey(name)); + } + + graph.edges.forEach((edge) => { + if (!CLAUSE_KINDS.has(edge.edge)) return; + const source = graph.entity(edge.from); + if (source === undefined || isStubEntity(source)) return; + const module = moduleOf(edge.from); + if (module === undefined) { + ledger.push({ edge, operation: undefined, outcome: { notDeclared: "source outside every module", clause: undefined } }); + return; + } + if (!scoped.has(module)) return; + const operation = operationAbove(edge.from); + if (operation === undefined) { + ledger.push({ edge, operation: undefined, outcome: { notDeclared: "no enclosing operation", clause: undefined } }); + return; + } + if (edge.edge === "throws") { + const ref = typeRef(edge.to); + if (ref === undefined) { + ledger.push({ edge, operation, outcome: { notDeclared: "target is not a type", clause: "errors" } }); + return; + } + const errorName = ref.name.path[ref.name.path.length - 1] ?? ""; + clausesOf(operation).errors.set(refKey(ref), { name: errorName, payload: ref }); + ledger.push({ edge, operation, outcome: { declared: ["errors"] } }); + return; + } + if (edge.edge === "invocation") { + const candidate = edge.provenance === "dynamic-candidate"; + const targets: { id: EntityId; candidate: boolean }[] = [{ id: edge.to, candidate }]; + for (const extra of edge.candidates ?? []) if (extra !== edge.to) targets.push({ id: extra, candidate: true }); + const outcomes = targets.map((target) => invocationItem(operation, target.id, target.candidate)); + const declared = outcomes.filter((outcome): outcome is { clause: EdgeClause } => "clause" in outcome).map((outcome) => outcome.clause); + if (declared.length > 0) ledger.push({ edge, operation, outcome: { declared: [...new Set(declared)] } }); + else { + const first = outcomes[0] as { reason: NotDeclaredReason }; + ledger.push({ edge, operation, outcome: { notDeclared: first.reason, clause: undefined } }); + } + return; + } + ledger.push({ edge, operation, outcome: accessItems(operation, edge as Extract) }); + }); + + // ------------------------------------------------------------------ + // Assemble, in canonical order (names, never ids). + // ------------------------------------------------------------------ + const entries = new Set(options.entries ?? []); + const candidateEntries = new Set(options.candidateEntries ?? []); + const sortedValues = (map: Map): T[] => [...map.entries()].sort(([a], [b]) => compareText(a, b)).map(([, v]) => v); + + const operationDecl = (id: EntityId): OperationDecl => { + const draft = operationDrafts.get(id) as OperationDraft; + const own = clauses.get(id); + const findings: Finding[] = []; + const cyclomatic = keyOf>(draft.entity, "metrics")?.["cyclomatic"]; + if (cyclomatic !== undefined && cyclomatic > 1) findings.push({ code: "branching", text: `cyclomatic ${cyclomatic}` }); + if (own !== undefined) findings.push(...sortedValues(own.blindSpots)); + const foldedHere = folded.get(id) ?? []; + return { + name: draft.name, + params: draft.params, + returns: draft.returns, + on: draft.on, + entry: entries.has(id) ? "firm" : candidateEntries.has(id) ? "candidate" : undefined, + constructor: draft.constructor, + entity: id, + sources: [id, ...foldedHere], + anchor: anchorOf(draft.entity), + errors: own === undefined ? [] : sortedValues(own.errors), + dependsOn: own === undefined ? [] : sortedValues(own.dependsOn), + uses: own === undefined ? [] : sortedValues(own.uses), + reads: own === undefined ? [] : sortedValues(own.reads), + writes: own === undefined ? [] : sortedValues(own.writes), + findings, + overloaded: overloaded.has(id), + }; + }; + const compareOperations = (a: OperationDecl, b: OperationDecl): number => + compareText(a.name, b.name) || + compareText(a.params.map((param) => typeKey(param.type)).join(","), b.params.map((param) => typeKey(param.type)).join(",")) || + compareAnchors(a.anchor, b.anchor); + const compareGlobals = (a: GlobalDecl, b: GlobalDecl): number => compareText(a.name, b.name) || compareAnchors(a.anchor, b.anchor); + + const structDecl = (id: EntityId): StructDecl => { + const draft = structDrafts.get(id) as StructDraft; + const schema = schemaOf(id); + return { + name: structPath(id), + entity: id, + anchor: anchorOf(draft.entity), + fields: schema.fields, + flattened: schema.flattened, + externalSupertypes: [...schema.external].sort((a, b) => compareText(qnameKey(a), qnameKey(b))), + globals: [...draft.globals].sort(compareGlobals), + operations: draft.operations.map(operationDecl).sort(compareOperations), + }; + }; + + // Structs and operations first: they declare the externals the module lists. + const modulesBuilt = [...moduleDrafts.values()].map((draft) => { + const structs = draft.structs.map(structDecl).sort((a, b) => compareText(a.name, b.name) || compareAnchors(a.anchor, b.anchor)); + const operations = draft.operations.map(operationDecl).sort(compareOperations); + return { draft, structs, operations }; + }); + const externalsIn = (module: EntityId | undefined): ExternalDecl[] => + [...externalsByKey.values()] + .filter((entry) => entry.module === module) + .map((entry) => entry.decl) + .sort( + (a, b) => + compareText(a.kind, b.kind) || + compareText([...(a.name.module ?? []), ...a.name.path].join("."), [...(b.name.module ?? []), ...b.name.path].join(".")) || + compareText(qnameKey(a.name), qnameKey(b.name)), + ); + const modules: ModuleDecl[] = modulesBuilt + .map(({ draft, structs, operations }) => ({ + segments: moduleSegments(draft.entity.id), + entity: draft.entity.id, + anchor: anchorOf(draft.entity), + externals: externalsIn(draft.entity.id), + structs, + globals: [...draft.globals].sort(compareGlobals), + operations, + })) + .sort((a, b) => compareText(a.segments.join("."), b.segments.join(".")) || compareAnchors(a.anchor, b.anchor)); + + const languages: LanguageNote[] = []; + const noteKeys = new Set(); + models.forEach((model, index) => { + const receiverKinds = receiverKindsOf(model.lang); + const contractOk = atLeast(model.schemaVersion, CONTRACT_WITH_RECEIVER); + const note: LanguageNote = { + lang: model.lang, + schemaVersion: model.schemaVersion, + receiverKinds: contractOk ? receiverKinds : [], + fallback: receiverKinds.length === 0 ? "licence" : contractOk ? undefined : "contract", + emptyTypeTable: isEmptyTable(typeTableOf(model.lang)), + writesTypeExprs: writesTypeExprs[index] ?? false, + }; + const key = JSON.stringify(note); + if (noteKeys.has(key)) return; + noteKeys.add(key); + languages.push(note); + }); + languages.sort((a, b) => compareText(a.lang, b.lang) || compareText(a.schemaVersion, b.schemaVersion)); + + const shadowedFields = [...structDrafts.keys()].reduce((total, id) => total + schemaOf(id).shadowed, 0); + const model: Omit = { + name, + languages, + externals: externalsIn(undefined), + modules, + ledger, + }; + return { + ...model, + summary: summarize(model, { + foldedInvocables: [...folded.values()].reduce((total, list) => total + list.length, 0), + unplacedInvocables: unplaced, + skipped, + shadowedFields, + ambiguousOverloads, + }), + }; +} + +/** The kinds a language's profile licenses `TWithReceiver` on, sorted; none without a profile. */ +export function receiverKinds(lang: string): readonly string[] { + const profile = getProfile(lang); + if (profile === undefined) return []; + return Object.entries(profile.kinds) + .filter(([, spec]) => spec.required.includes("TWithReceiver") || spec.optional.includes("TWithReceiver")) + .map(([kind]) => kind) + .sort(compareText); +} + +function compareAnchors(a: SourceAnchor | undefined, b: SourceAnchor | undefined): number { + if (a === undefined || b === undefined) return a === b ? 0 : a === undefined ? -1 : 1; + return compareText(a.file, b.file) || a.span[0] - b.span[0] || a.span[1] - b.span[1]; +} diff --git a/packages/dataop/src/model.ts b/packages/dataop/src/model.ts new file mode 100644 index 00000000..2573b538 --- /dev/null +++ b/packages/dataop/src/model.ts @@ -0,0 +1,246 @@ +import type { Edge, EntityId, SourceAnchor } from "@codegraph/core"; + +/** + * THE VALUE BETWEEN `lower` AND `print` (PLAN.md §26.4): a Data & Operation + * model as data. Every name is held RAW — as the code spells it — and quoted + * by the printer alone; every reference is a {@link QName}, never a string an + * id was cut into. Each declaration keeps the entity it came from and its + * anchor, so the three properties of §26.6 read this value, not the text. + */ + +/** + * A reference as the model writes it: the module's segments (null for a + * declaration at model level), then the path below the module. Printed + * relative to the module it is written in — the module is dropped inside it. + */ +export interface QName { + readonly module: readonly string[] | null; + readonly path: readonly string[]; +} + +/** What a reference points at, for closure (Specy's rule 9). */ +export type RefKind = "struct" | "external-struct" | "external-module" | "operation" | "global"; + +export interface Ref { + readonly kind: RefKind; + readonly name: QName; +} + +/** The seven constructors of `.dataop`'s type language (no map: the lowering writes none). */ +export type DataOpType = + | { readonly k: "scalar"; readonly name: "string" | "number" | "boolean" } + | { readonly k: "array"; readonly of: DataOpType } + | { readonly k: "nullable"; readonly of: DataOpType } + | { readonly k: "ref"; readonly ref: Ref } + | { readonly k: "function"; readonly params: readonly DataOpType[]; readonly returns: DataOpType | undefined } + | { readonly k: "opaque"; readonly text: string }; + +/** A global's initial value: JSON text, `opaque "…"`, or bare `opaque`. */ +export type InitialValue = + | { readonly k: "json"; readonly text: string } + | { readonly k: "opaque"; readonly text: string | undefined }; + +/** The two testimonies of rule 29 the lowering writes; recomputable findings are a validator's. */ +export type FindingCode = "branching" | "blind-spot"; + +export interface Finding { + readonly code: FindingCode; + readonly text: string; +} + +export interface ExternalDecl { + readonly kind: "external-struct" | "external-module"; + readonly name: QName; + /** The entity it stands for: a stub, or a corpus declaration outside `--scope`. */ + readonly entity: EntityId; +} + +export interface FieldDecl { + readonly name: string; + readonly type: DataOpType; + readonly entity: EntityId; + readonly anchor: SourceAnchor | undefined; + /** The corpus supertype it is flattened from; absent for the struct's own field. */ + readonly inheritedFrom: QName | undefined; +} + +export interface GlobalDecl { + readonly name: string; + readonly type: DataOpType; + readonly value: InitialValue; + readonly entity: EntityId; + readonly anchor: SourceAnchor | undefined; +} + +export interface Param { + /** Absent when the model names no parameter (a pattern); printed by position. */ + readonly name: string; + readonly type: DataOpType; + readonly entity: EntityId; +} + +export interface DependencyItem { + readonly ref: QName; + /** The parameter types written after the name: present when the target is overloaded. */ + readonly disambiguator: readonly DataOpType[] | undefined; + readonly candidate: boolean; + readonly target: EntityId; +} + +export interface UseItem { + readonly ref: Ref; + readonly candidate: boolean; +} + +export interface ErrorItem { + /** The error's name: the exception type's own name (one segment). */ + readonly name: string; + /** The payload, `of` the exception type. */ + readonly payload: Ref; +} + +export type AccessItem = + | { readonly k: "global"; readonly ref: QName; readonly target: EntityId } + | { readonly k: "self"; readonly field: string; readonly target: EntityId } + | { readonly k: "param"; readonly param: string; readonly field: string; readonly target: EntityId }; + +export interface OperationDecl { + readonly name: string; + readonly params: readonly Param[]; + /** Absent: the operation returns nothing (only where the model says so). */ + readonly returns: DataOpType | undefined; + /** `on module`, `on Struct`, or nothing (attached to the enclosing struct, or at module level). */ + readonly on: "module" | QName | undefined; + /** `entry` (firm: a rule at the declaration), `entry?` (a candidate: an inference), or none. */ + readonly entry: "firm" | "candidate" | undefined; + /** True for `new`, the lowering of a constructor. */ + readonly constructor: boolean; + readonly entity: EntityId; + /** The operation, then every nameless invocable folded into it, sorted. */ + readonly sources: readonly EntityId[]; + readonly anchor: SourceAnchor | undefined; + readonly errors: readonly ErrorItem[]; + readonly dependsOn: readonly DependencyItem[]; + readonly uses: readonly UseItem[]; + readonly reads: readonly AccessItem[]; + readonly writes: readonly AccessItem[]; + readonly findings: readonly Finding[]; + /** True when another operation of its container shares its name: references carry the parameter types. */ + readonly overloaded: boolean; +} + +export interface StructDecl { + /** The type's path below its module, one segment (`Basket.Line`). */ + readonly name: string; + readonly entity: EntityId; + readonly anchor: SourceAnchor | undefined; + readonly fields: readonly FieldDecl[]; + /** Corpus supertypes whose fields are flattened in, for the `// NOTE:`. */ + readonly flattened: readonly QName[]; + /** Supertypes outside the model: their fields are not known. */ + readonly externalSupertypes: readonly QName[]; + readonly globals: readonly GlobalDecl[]; + readonly operations: readonly OperationDecl[]; +} + +export interface ModuleDecl { + readonly segments: readonly string[]; + readonly entity: EntityId; + readonly anchor: SourceAnchor | undefined; + /** Stubs whose parent is this module. */ + readonly externals: readonly ExternalDecl[]; + readonly structs: readonly StructDecl[]; + readonly globals: readonly GlobalDecl[]; + readonly operations: readonly OperationDecl[]; +} + +/** Where an `invocation`, `access` or `throws` edge went: a clause, or a reason it did not. */ +export type EdgeClause = "errors" | "depends on" | "uses" | "reads" | "writes"; + +/** Why an edge is not declared — the closed list the summary counts. */ +export const NOT_DECLARED_REASONS = [ + "no enclosing operation", + "source outside every module", + "target unknown", + "target is not an operation", + "target is a nameless invocable", + "target is not a type", + "target is a local or a parameter", + "target is not a value holder", + "target is external", + "target outside the scope", + "read through another instance", + "self access outside the receiver's schema", + "the instance a constructor builds", + "candidate access", + "write not attributable", +] as const; +export type NotDeclaredReason = (typeof NOT_DECLARED_REASONS)[number]; + +/** + * One edge the clauses are made of, and what became of it. The agreement + * property (§26.6) reads this: every edge of the three kinds leaving a lowered + * declaration has exactly one entry, declared or counted. + */ +export interface LedgerEntry { + readonly edge: Edge; + /** The operation it was charged to; absent when there was none. */ + readonly operation: EntityId | undefined; + /** What it declared, or why it declared nothing. One edge may declare two items (a read and a write). */ + readonly outcome: + | { readonly declared: readonly EdgeClause[] } + | { readonly notDeclared: NotDeclaredReason; readonly clause: EdgeClause | undefined }; +} + +/** Per language: what the output's header says about receivers and types. */ +export interface LanguageNote { + readonly lang: string; + readonly schemaVersion: string; + /** Kinds whose `TWithReceiver` is read as a fact; every other kind takes the fallback. */ + readonly receiverKinds: readonly string[]; + /** Why the fallback applies, when it does on some kind. */ + readonly fallback: "contract" | "licence" | undefined; + readonly emptyTypeTable: boolean; + /** The model carries `typeExpr`: an absent one means an unwritten type. */ + readonly writesTypeExprs: boolean; +} + +export interface LoweringSummary { + readonly modules: number; + readonly structs: number; + readonly fields: number; + readonly flattenedFields: number; + readonly shadowedFields: number; + readonly globals: number; + readonly operations: number; + readonly constructors: number; + readonly entries: number; + readonly candidateEntries: number; + readonly externalModules: number; + readonly externalStructs: number; + /** `opaque` types printed (each occurrence), of which `opaque "?"`. */ + readonly opaqueTypes: number; + readonly unknownTypes: number; + readonly opaqueValues: number; + readonly foldedInvocables: number; + /** Nameless invocables with no operation above them: their edges are counted, not declared. */ + readonly unplacedInvocables: number; + /** Declarations not lowered, by why (a field of a nameless type, a delegate…). */ + readonly skipped: Readonly>; + readonly edgesDeclared: number; + readonly edgesNotDeclared: Readonly>>; + readonly blindSpots: number; + readonly branching: number; + /** Overloads whose parameter types print the same: their references cannot be told apart. */ + readonly ambiguousOverloads: number; +} + +export interface DataOpModel { + readonly name: string; + readonly languages: readonly LanguageNote[]; + /** Model-level externals: stub modules, their types, parentless stubs, out-of-scope corpus. */ + readonly externals: readonly ExternalDecl[]; + readonly modules: readonly ModuleDecl[]; + readonly ledger: readonly LedgerEntry[]; + readonly summary: LoweringSummary; +} diff --git a/packages/dataop/src/names.ts b/packages/dataop/src/names.ts new file mode 100644 index 00000000..fdef2a4a --- /dev/null +++ b/packages/dataop/src/names.ts @@ -0,0 +1,131 @@ +/** + * The name and string rules of Specy's `.dataop` grammar + * (`src/grammars/data-operation.ebnf`, "Names and literals", rule 25). + * + * A name is BARE — ASCII letters, digits and `_`, not starting with a digit, + * `_` alone excluded — or QUOTED, `@"…"`. A quoted name is one segment + * whatever it holds and is never a keyword, so every name the code spells is + * printable: it is quoted when it is not bare or when it is a keyword. + */ + +/** + * Every word the grammar writes as a terminal, in the EBNF's spelling. `entry` + * is a keyword in front of `operation` only; it is quoted everywhere anyway — + * a quoted name is the same name as its bare spelling, so quoting costs nothing + * and a reader never has to know the position rule. + */ +export const DATAOP_KEYWORDS = [ + "and", + "array", + "boolean", + "corresponds", + "depends", + "derives", + "else", + "ensures", + "entry", + "errors", + "external", + "false", + "flow", + "from", + "global", + "implements", + "in", + "is", + "meta", + "model", + "module", + "not", + "null", + "number", + "observed", + "of", + "old", + "on", + "opaque", + "operation", + "or", + "raise", + "reads", + "represents", + "requires", + "result", + "return", + "schema", + "state", + "strict", + "string", + "struct", + "to", + "true", + "uses", + "via", + "void", + "when", + "write", + "writes", +] as const; + +const KEYWORDS: ReadonlySet = new Set(DATAOP_KEYWORDS); + +/** `identifier` of the EBNF: `letter {identChar}` | `"_" identChar {identChar}`, ASCII letters only. */ +const IDENTIFIER = /^(?:[A-Za-z][A-Za-z0-9_]*|_[A-Za-z0-9_]+)$/u; + +export function isKeyword(name: string): boolean { + return KEYWORDS.has(name); +} + +/** A name the grammar accepts unquoted. */ +export function isBareName(name: string): boolean { + return IDENTIFIER.test(name) && !KEYWORDS.has(name); +} + +/** + * A string literal: `\"` and `\\` are the only escapes and a line break is not + * representable, so CR and LF are written as spaces. The lowering never hands + * a text with a line break to a position where it would change meaning + * (`opaque` texts and values are checked first); a NAME with one is the only + * caller, and no extractor writes such a name. + */ +export function printString(text: string): string { + const escaped = text.replace(/[\\"]/gu, (char) => `\\${char}`).replace(/[\r\n]/gu, " "); + return `"${escaped}"`; +} + +/** Whether a text can be carried verbatim by a string literal. */ +export function isOneLine(text: string): boolean { + return !/[\r\n]/u.test(text); +} + +/** One name, quoted when it must be. */ +export function printName(name: string): string { + return isBareName(name) ? name : `@${printString(name)}`; +} + +/** `a.b.c`, each segment a name. */ +export function printQualified(segments: readonly string[]): string { + return segments.map(printName).join("."); +} + +/** + * A model name (`modelName` of the EBNF): kebab-case words, each starting with + * a lowercase ASCII letter. Undefined when the text yields none. + */ +export function kebabModelName(text: string): string | undefined { + const words = text + .replace(/([a-z0-9])([A-Z])/gu, "$1-$2") + .toLowerCase() + .split(/[^a-z0-9]+/u) + .filter((word) => word.length > 0); + if (words.length === 0) return undefined; + const name = words.join("-"); + return isModelName(name) ? name : undefined; +} + +const MODEL_NAME = /^[a-z][A-Za-z0-9]*(?:-[a-z][A-Za-z0-9]*)*$/u; + +/** `modelName = modelWord {"-" modelWord}`, `modelWord = lowerLetter {letter | digit}`. */ +export function isModelName(name: string): boolean { + return MODEL_NAME.test(name); +} diff --git a/packages/dataop/src/print.ts b/packages/dataop/src/print.ts new file mode 100644 index 00000000..d724d6f7 --- /dev/null +++ b/packages/dataop/src/print.ts @@ -0,0 +1,215 @@ +import type { SourceAnchor } from "@codegraph/core"; +import type { + AccessItem, + DataOpModel, + DataOpType, + ExternalDecl, + FieldDecl, + GlobalDecl, + LanguageNote, + ModuleDecl, + OperationDecl, + QName, + StructDecl, +} from "./model.js"; +import { printName, printQualified, printString } from "./names.js"; + +/** + * THE PRINTER: a {@link DataOpModel} → `.dataop` text, in the grammar's clause + * order (`operationDef`: errors, depends on, uses, reads, writes). It decides + * nothing the lowering did not: it quotes names, writes references relative to + * the module they sit in, and lays out comments where the grammar allows them + * (between any two tokens). Pure, and deterministic to the byte. + */ + +/** Said once, in the header, wherever a language takes the fallback of §26.4. */ +export const RECEIVER_FALLBACK = + "every field of a type is a schema field and every method is attached; an access to a field of the " + + "operation's own struct or of a flattened supertype reads as `_`"; + +/** The header line on receivers for one language: which kinds the marker is read on, and why the fallback holds elsewhere. */ +export function receiverSentence(note: LanguageNote): string { + const at = `receivers (${note.lang}, contract ${note.schemaVersion}): `; + switch (note.fallback) { + case "licence": + return `${at}the profile licenses TWithReceiver on no kind, so nothing in the model says which member needs an instance. Fallback: ${RECEIVER_FALLBACK}.`; + case "contract": + return `${at}the model states a contract before 1.2.0, where TWithReceiver says nothing. Fallback: ${RECEIVER_FALLBACK}.`; + case undefined: + return `${at}TWithReceiver is read as a fact on ${note.receiverKinds.join(", ")}, and its absence as no receiver; every other kind takes the fallback: ${RECEIVER_FALLBACK}.`; + } +} + +export function typeSentence(note: LanguageNote): string { + const table = note.emptyTypeTable + ? `the type table is empty: a primitive prints as opaque and a library type as an external struct` + : `scalars, sequences and optionals from the type table`; + const exprs = note.writesTypeExprs + ? `types from typeExpr` + : `the model writes no typeExpr: a type is its declared head (an erased struct reference), or opaque "?" where none is declared`; + return `types (${note.lang}): ${table}; ${exprs}.`; +} + +interface Scope { + /** The module the text sits in: references into it drop the module. */ + readonly module: readonly string[] | null; + /** Names a first segment would resolve to before the module (parameters, the struct's members). */ + readonly shadow: ReadonlySet; +} + +const NO_SHADOW: ReadonlySet = new Set(); + +function sameModule(a: readonly string[] | null, b: readonly string[] | null): boolean { + return a !== null && b !== null && a.length === b.length && a.every((segment, i) => segment === b[i]); +} + +function reference(name: QName, scope: Scope): string { + if (name.module === null) return printQualified(name.path); + const first = name.path[0]; + const local = sameModule(name.module, scope.module) && name.path.length > 0 && (first === undefined || !scope.shadow.has(first)); + return printQualified(local ? name.path : [...name.module, ...name.path]); +} + +export function printType(type: DataOpType, scope: Scope): string { + switch (type.k) { + case "scalar": + return type.name; + case "array": + return `array<${printType(type.of, scope)}>`; + case "nullable": + return `${printType(type.of, scope)}?`; + case "ref": + return reference(type.ref.name, scope); + case "function": + return `(${type.params.map((param) => printType(param, scope)).join(", ")}) -> ${type.returns === undefined ? "void" : printType(type.returns, scope)}`; + case "opaque": + return `opaque ${printString(type.text)}`; + } +} + +function source(anchor: SourceAnchor | undefined): string[] { + return anchor === undefined ? [] : [`// source: ${anchor.file}:${anchor.span[0]}-${anchor.span[1]}`]; +} + +const indent = (lines: readonly string[], by = " "): string[] => lines.map((line) => (line === "" ? "" : `${by}${line}`)); + +function external(decl: ExternalDecl, scope: Scope): string { + return decl.kind === "external-module" + ? `external module ${printQualified(decl.name.module ?? [])}` + : `external struct ${reference(decl.name, scope)}`; +} + +function field(decl: FieldDecl, scope: Scope): string[] { + return [`${printName(decl.name)}: ${printType(decl.type, scope)}`, ...indent(source(decl.anchor))]; +} + +function global(decl: GlobalDecl, scope: Scope): string[] { + const value = decl.value.k === "json" ? decl.value.text : decl.value.text === undefined ? "opaque" : `opaque ${printString(decl.value.text)}`; + return [`global ${printName(decl.name)}: ${printType(decl.type, scope)} = ${value}`, ...indent(source(decl.anchor))]; +} + +function access(item: AccessItem, scope: Scope): string { + switch (item.k) { + case "global": + return reference(item.ref, scope); + case "self": + return `_.${printName(item.field)}`; + case "param": + return `${printName(item.param)}.${printName(item.field)}`; + } +} + +function clause(keyword: string, items: readonly string[]): string[] { + return items.length === 0 ? [] : [`${keyword} { ${items.join(", ")} }`]; +} + +function operation(decl: OperationDecl, outer: Scope, members: ReadonlySet): string[] { + const shadow = new Set([...members, ...decl.params.map((param) => param.name)]); + const scope: Scope = { module: outer.module, shadow }; + const params = decl.params.map((param) => `${printName(param.name)}: ${printType(param.type, outer)}`).join(", "); + const returns = decl.returns === undefined ? "" : `: ${printType(decl.returns, outer)}`; + const on = decl.on === undefined ? "" : decl.on === "module" ? " on module" : ` on ${reference(decl.on, outer)}`; + const mark = decl.entry === "firm" ? "entry " : decl.entry === "candidate" ? "entry? " : ""; + const header = `${mark}operation ${printName(decl.name)}(${params})${returns}${on}`; + const body = [ + ...source(decl.anchor), + ...decl.findings.map((finding) => `// FINDING: ${finding.code}: ${finding.text.replace(/[\r\n]/gu, " ")}`), + ...clause( + "errors", + decl.errors.map((error) => `${printName(error.name)} of ${reference(error.payload.name, outer)}`), + ), + ...clause( + "depends on", + decl.dependsOn.map( + (item) => + `${reference(item.ref, scope)}${item.disambiguator === undefined ? "" : `(${item.disambiguator.map((type) => printType(type, outer)).join(", ")})`}${item.candidate ? "?" : ""}`, + ), + ), + ...clause( + "uses", + decl.uses.map((item) => `${reference(item.ref.name, scope)}${item.candidate ? "?" : ""}`), + ), + ...clause("reads", decl.reads.map((item) => access(item, scope))), + ...clause("writes", decl.writes.map((item) => access(item, scope))), + ]; + return [header, ...indent(body)]; +} + +function struct(decl: StructDecl, outer: Scope): string[] { + const members = new Set([ + ...decl.fields.map((item) => item.name), + ...decl.globals.map((item) => item.name), + ...decl.operations.map((item) => item.name), + ]); + const notes: string[] = []; + if (decl.flattened.length > 0) { + notes.push(`// NOTE: the schema flattens the fields of ${decl.flattened.map((name) => reference(name, outer)).join(", ")}: Specy has no inheritance`); + } + if (decl.externalSupertypes.length > 0) { + notes.push(`// NOTE: supertypes outside the model, their fields unknown: ${decl.externalSupertypes.map((name) => reference(name, outer)).join(", ")}`); + } + const schema = ["schema {", ...indent(decl.fields.flatMap((item) => field(item, outer))), "}"]; + const rest = [ + ...decl.globals.map((item) => global(item, outer)), + ...decl.operations.map((item) => operation(item, outer, members)), + ]; + return [ + `struct ${printName(decl.name)} {`, + ...indent([...source(decl.anchor), ...notes, ...schema, ...rest.flatMap((block) => ["", ...block])]), + "}", + ]; +} + +function moduleBlock(decl: ModuleDecl): string[] { + const scope: Scope = { module: decl.segments, shadow: NO_SHADOW }; + const blocks: string[][] = []; + if (decl.externals.length > 0) blocks.push(decl.externals.map((item) => external(item, scope))); + for (const item of decl.structs) blocks.push(struct(item, scope)); + for (const item of decl.globals) blocks.push(global(item, scope)); + for (const item of decl.operations) blocks.push(operation(item, scope, NO_SHADOW)); + const body = [...source(decl.anchor), ...blocks.flatMap((block, i) => (i === 0 && decl.anchor === undefined ? block : ["", ...block]))]; + return [`module ${printQualified(decl.segments)} {`, ...indent(body), "}"]; +} + +/** The header comment: what the lowering is, and what each language's model lets it say. */ +export function headerLines(model: DataOpModel): string[] { + return [ + "// A Data & Operation model lowered by codegraph from a code graph (observed): what the graph holds and", + "// nothing else. Not lowered: states, contracts, flows, descriptions, lineage, domain links.", + ...model.languages.flatMap((note) => [`// ${receiverSentence(note)}`, `// ${typeSentence(note)}`]), + ]; +} + +export function print(model: DataOpModel): string { + const top: Scope = { module: null, shadow: NO_SHADOW }; + const blocks: string[][] = []; + if (model.externals.length > 0) blocks.push(model.externals.map((item) => external(item, top))); + for (const module of model.modules) blocks.push(moduleBlock(module)); + const lines = [ + ...headerLines(model), + `model ${model.name} observed {`, + ...indent(blocks.flatMap((block) => ["", ...block])), + "}", + ]; + return `${lines.join("\n")}\n`; +} diff --git a/packages/dataop/src/summary.ts b/packages/dataop/src/summary.ts new file mode 100644 index 00000000..bfd820d8 --- /dev/null +++ b/packages/dataop/src/summary.ts @@ -0,0 +1,136 @@ +import type { + DataOpModel, + DataOpType, + LoweringSummary, + NotDeclaredReason, + OperationDecl, +} from "./model.js"; +import { NOT_DECLARED_REASONS } from "./model.js"; + +/** + * What was lowered and what was not, counted from the model itself — so the + * summary on stderr and the text on stdout cannot disagree. + */ + +export interface LoweringTally { + readonly foldedInvocables: number; + readonly unplacedInvocables: number; + readonly skipped: Readonly>; + readonly shadowedFields: number; + readonly ambiguousOverloads: number; +} + +function opaqueIn(type: DataOpType | undefined): { opaque: number; unknown: number } { + if (type === undefined) return { opaque: 0, unknown: 0 }; + switch (type.k) { + case "opaque": + return { opaque: 1, unknown: type.text === "?" ? 1 : 0 }; + case "array": + case "nullable": + return opaqueIn(type.of); + case "function": { + const all = [...type.params, ...(type.returns === undefined ? [] : [type.returns])].map(opaqueIn); + return all.reduce((sum, one) => ({ opaque: sum.opaque + one.opaque, unknown: sum.unknown + one.unknown }), { opaque: 0, unknown: 0 }); + } + default: + return { opaque: 0, unknown: 0 }; + } +} + +export function summarize(model: Omit, tally: LoweringTally): LoweringSummary { + const operations: OperationDecl[] = []; + let structs = 0; + let fields = 0; + let flattenedFields = 0; + let globals = 0; + const types: (DataOpType | undefined)[] = []; + let opaqueValues = 0; + for (const module of model.modules) { + operations.push(...module.operations); + globals += module.globals.length; + for (const global of module.globals) { + types.push(global.type); + if (global.value.k === "opaque") opaqueValues += 1; + } + for (const struct of module.structs) { + structs += 1; + fields += struct.fields.length; + flattenedFields += struct.fields.filter((field) => field.inheritedFrom !== undefined).length; + types.push(...struct.fields.map((field) => field.type)); + globals += struct.globals.length; + for (const global of struct.globals) { + types.push(global.type); + if (global.value.k === "opaque") opaqueValues += 1; + } + operations.push(...struct.operations); + } + } + for (const operation of operations) { + types.push(...operation.params.map((param) => param.type)); + if (!operation.constructor) types.push(operation.returns); + } + const opaque = types.map(opaqueIn).reduce((sum, one) => ({ opaque: sum.opaque + one.opaque, unknown: sum.unknown + one.unknown }), { opaque: 0, unknown: 0 }); + + const edgesNotDeclared: Partial> = {}; + let edgesDeclared = 0; + for (const entry of model.ledger) { + if ("declared" in entry.outcome) edgesDeclared += 1; + else edgesNotDeclared[entry.outcome.notDeclared] = (edgesNotDeclared[entry.outcome.notDeclared] ?? 0) + 1; + } + const allExternals = [...model.externals, ...model.modules.flatMap((module) => module.externals)]; + return { + modules: model.modules.length, + structs, + fields, + flattenedFields, + shadowedFields: tally.shadowedFields, + globals, + operations: operations.length, + constructors: operations.filter((operation) => operation.constructor).length, + entries: operations.filter((operation) => operation.entry === "firm").length, + candidateEntries: operations.filter((operation) => operation.entry === "candidate").length, + externalModules: allExternals.filter((decl) => decl.kind === "external-module").length, + externalStructs: allExternals.filter((decl) => decl.kind === "external-struct").length, + opaqueTypes: opaque.opaque, + unknownTypes: opaque.unknown, + opaqueValues, + foldedInvocables: tally.foldedInvocables, + unplacedInvocables: tally.unplacedInvocables, + skipped: tally.skipped, + edgesDeclared, + edgesNotDeclared, + blindSpots: operations.reduce((total, operation) => total + operation.findings.filter((finding) => finding.code === "blind-spot").length, 0), + branching: operations.reduce((total, operation) => total + operation.findings.filter((finding) => finding.code === "branching").length, 0), + ambiguousOverloads: tally.ambiguousOverloads, + }; +} + +const plural = (count: number, noun: string, many = `${noun}s`): string => `${count} ${count === 1 ? noun : many}`; + +/** The summary as the lines `codegraph dataop` writes on stderr. */ +export function formatSummary(summary: LoweringSummary): string[] { + const lines = [ + `lowered: ${plural(summary.modules, "module")}, ${plural(summary.structs, "struct")} ` + + `(${plural(summary.fields, "field")}, ${summary.flattenedFields} flattened from supertypes), ` + + `${plural(summary.globals, "global")}, ${plural(summary.operations, "operation")} ` + + `(${plural(summary.constructors, "constructor")}, ${plural(summary.entries, "entry", "entries")}, ${summary.candidateEntries} entry?), ` + + `${plural(summary.externalModules, "external module")}, ${plural(summary.externalStructs, "external struct")}.`, + `types: ${summary.opaqueTypes} opaque, of which ${summary.unknownTypes} unknown (opaque "?"); ${plural(summary.opaqueValues, "opaque initial value")}.`, + `invocables: ${summary.foldedInvocables} nameless folded into their operation, ${summary.unplacedInvocables} with no operation above them.`, + `edges (invocation, access, throws): ${summary.edgesDeclared} declared, ` + + `${Object.values(summary.edgesNotDeclared).reduce((total, count) => total + (count ?? 0), 0)} not declared.`, + ]; + for (const reason of NOT_DECLARED_REASONS) { + const count = summary.edgesNotDeclared[reason]; + if (count !== undefined && count > 0) lines.push(` not declared — ${reason}: ${count}`); + } + lines.push(`findings written: ${summary.branching} branching, ${summary.blindSpots} blind-spot.`); + if (summary.shadowedFields > 0) lines.push(`fields shadowed by a subtype's field of the same name, not flattened: ${summary.shadowedFields}.`); + if (summary.ambiguousOverloads > 0) { + lines.push(`overloads whose parameter types print alike (references cannot tell them apart): ${summary.ambiguousOverloads}.`); + } + for (const [reason, count] of Object.entries(summary.skipped).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) { + lines.push(`not lowered — ${reason}: ${count}`); + } + return lines; +} diff --git a/packages/dataop/src/type-tables.ts b/packages/dataop/src/type-tables.ts new file mode 100644 index 00000000..46697ebf --- /dev/null +++ b/packages/dataop/src/type-tables.ts @@ -0,0 +1,118 @@ +/** + * THE TYPE TABLES (PLAN.md §26.4, "Types"): per language, which written types + * the closed type language of `.dataop` can say exactly. Data, not code: a + * language gains a row here, never a branch in the lowering. + * + * A library type is matched on the stub's `name` plus its parent module's + * `name` — what the model holds — and never on an id. + */ + +export type Scalar = "string" | "number" | "boolean"; + +/** What a matched library type lowers to. */ +export type StubMeaning = Scalar | "sequence" | "optional"; + +export interface StubRow { + /** The parent module's `name`, as the model writes it. */ + readonly module: string; + /** The stub type's own `name`. */ + readonly name: string; + /** `sequence` and `optional` apply to a written use with exactly one type argument. */ + readonly as: StubMeaning; +} + +export interface TypeTable { + readonly lang: string; + /** A `primitive` type expression's name → the scalar it is. */ + readonly primitives: Readonly>; + readonly stubs: readonly StubRow[]; + /** + * Kinds whose nameless invocables are constructors, lowered as + * `operation new(…): Struct on module`. Without the row a nameless invocable + * folds like a lambda: a lambda written in a field initializer is parented to + * the type too, so "nameless, parent is a type" alone does not say constructor. + */ + readonly constructorKinds: readonly string[]; + /** + * The language writes every return type, `void` included, so an invocable + * whose type expression is absent in a model that writes them returns + * nothing. False where an unwritten return is unknown (an unannotated + * function), which then prints `opaque "?"`. + */ + readonly returnAlwaysWritten: boolean; +} + +const NUMBER: Scalar = "number"; + +export const JAVA_TYPE_TABLE: TypeTable = { + lang: "java", + primitives: { + byte: NUMBER, + short: NUMBER, + int: NUMBER, + long: NUMBER, + float: NUMBER, + double: NUMBER, + boolean: "boolean", + char: "string", + }, + stubs: [ + { module: "java.lang", name: "String", as: "string" }, + { module: "java.lang", name: "CharSequence", as: "string" }, + { module: "java.lang", name: "Character", as: "string" }, + { module: "java.lang", name: "Byte", as: NUMBER }, + { module: "java.lang", name: "Short", as: NUMBER }, + { module: "java.lang", name: "Integer", as: NUMBER }, + { module: "java.lang", name: "Long", as: NUMBER }, + { module: "java.lang", name: "Float", as: NUMBER }, + { module: "java.lang", name: "Double", as: NUMBER }, + { module: "java.lang", name: "Number", as: NUMBER }, + { module: "java.math", name: "BigDecimal", as: NUMBER }, + { module: "java.math", name: "BigInteger", as: NUMBER }, + { module: "java.lang", name: "Boolean", as: "boolean" }, + { module: "java.util", name: "List", as: "sequence" }, + { module: "java.util", name: "Set", as: "sequence" }, + { module: "java.util", name: "Collection", as: "sequence" }, + { module: "java.lang", name: "Iterable", as: "sequence" }, + { module: "java.util", name: "Optional", as: "optional" }, + ], + constructorKinds: ["constructor"], + returnAlwaysWritten: true, +}; + +/** + * The other languages' tables are EMPTY on purpose (§26.8, M25c): their + * extractors write no `typeExpr` yet, so a table would only rename stubs. The + * constructor kinds are kept, since they decide `new` and not a type. + */ +const empty = (lang: string, constructorKinds: readonly string[] = []): TypeTable => ({ + lang, + primitives: {}, + stubs: [], + constructorKinds, + returnAlwaysWritten: false, +}); + +export const TYPE_TABLES: Readonly> = { + java: JAVA_TYPE_TABLE, + csharp: empty("csharp", ["constructor"]), + ts: empty("ts", ["constructor"]), + js: empty("js"), + python: empty("python"), + rb: empty("rb"), + ex: empty("ex"), + clj: empty("clj"), + go: empty("go"), + php: empty("php"), + rust: empty("rust"), +}; + +/** The table of a language; an unknown one gets an empty table. */ +export function typeTableOf(lang: string): TypeTable { + return TYPE_TABLES[lang] ?? empty(lang); +} + +/** Whether a table says nothing about types (primitives and library types). */ +export function isEmptyTable(table: TypeTable): boolean { + return Object.keys(table.primitives).length === 0 && table.stubs.length === 0; +} diff --git a/packages/dataop/test/boundary.test.ts b/packages/dataop/test/boundary.test.ts new file mode 100644 index 00000000..dd64937f --- /dev/null +++ b/packages/dataop/test/boundary.test.ts @@ -0,0 +1,46 @@ +import { readFileSync, readdirSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; + +/** + * A MODEL PACKAGE (CLAUDE.md, hard boundaries): pure computation over the + * analyzer's graph. It imports no frontend (react, three, cytoscape), no model + * provider (the OpenRouter SDK, @codegraph/llm), no other codegraph package but + * core and the analyzer, and nothing of Node's that does I/O. + */ + +const SRC = fileURLToPath(new URL("../src/", import.meta.url)); +const PACKAGE = fileURLToPath(new URL("../package.json", import.meta.url)); + +const ALLOWED = ["@codegraph/core", "@codegraph/analyzer"]; + +function specifiers(text: string): string[] { + return [...text.matchAll(/(?:from\s+|import\s*\(\s*|import\s+)["']([^"']+)["']/gu)].map((match) => match[1] ?? ""); +} + +const files = readdirSync(SRC).filter((file) => file.endsWith(".ts")); + +describe("the dataop package's boundary", () => { + it("has source files to check", () => { + expect(files).toEqual(expect.arrayContaining(["lower.ts", "print.ts", "index.ts"])); + }); + + it.each(files)("%s imports only core, the analyzer and its own modules", (file) => { + const foreign = specifiers(readFileSync(`${SRC}${file}`, "utf8")).filter( + (specifier) => !specifier.startsWith("./") && !ALLOWED.includes(specifier), + ); + expect(foreign).toEqual([]); + }); + + it("depends on core and the analyzer alone", () => { + const manifest = JSON.parse(readFileSync(PACKAGE, "utf8")) as { dependencies?: Record }; + expect(Object.keys(manifest.dependencies ?? {}).sort()).toEqual([...ALLOWED].sort()); + }); + + it("sees what it forbids", () => { + expect(specifiers('import * as THREE from "three";\nimport { x } from "./x.js";')).toEqual(["three", "./x.js"]); + // Spelled in two halves: the provider SDK's own boundary test scans every file of the workspace for it. + const sdk = ["@openrouter", "sdk"].join("/"); + expect(specifiers(`const m = await import("${sdk}");`)).toEqual([sdk]); + }); +}); diff --git a/packages/dataop/test/clauses.test.ts b/packages/dataop/test/clauses.test.ts new file mode 100644 index 00000000..6a7a2604 --- /dev/null +++ b/packages/dataop/test/clauses.test.ts @@ -0,0 +1,230 @@ +import { describe, expect, it } from "vitest"; +import { lower } from "../src/index.js"; +import { edge, field, graphOf, javaStubs, lowered, method, param, pkg, type } from "./toy.js"; + +/** + * §26.4, "Clauses", "Entries", "Evidence and findings", "Order": one test per + * row, on hand-built graphs. + */ + +const M = "java:com.acme.order"; +const Order = `${M}/Order`; +const Line = `${M}/Line`; +const lineType = { k: "named", type: Line } as const; + +const base = [ + pkg(M, "com.acme.order"), + ...javaStubs(), + type(Order, "Order", M), + type(Line, "Line", M), + field(`${Order}.lines`, "lines", Order, { receiver: true }), + field(`${Order}.MAX`, "MAX", Order, { value: { k: "number", v: "3" } }), + field(`${Line}.qty`, "qty", Line, { receiver: true }), + type(`${M}/Problem`, "Problem", M), +]; + +describe("errors", () => { + it("is the throws edges: the operation's own raise sites, named by the exception type", () => { + const { text } = lowered({ + entities: [ + ...base, + method(`${Order}.check()`, "check", Order, { receiver: true }), + type("java:java.lang/IllegalStateException", "IllegalStateException", "java:java.lang", { stub: true }), + ], + edges: [edge("throws", `${Order}.check()`, `${M}/Problem`), edge("throws", `${Order}.check()`, "java:java.lang/IllegalStateException")], + }); + expect(text).toContain("errors { IllegalStateException of java.lang.IllegalStateException, Problem of Problem }"); + }); +}); + +describe("depends on", () => { + const entities = [ + ...base, + method(`${Order}.total()`, "total", Order, { receiver: true }), + method(`${Order}.price()`, "price", Order, { receiver: true }), + method(`${Line}.render()`, "render", Line, { receiver: true }), + method(`${Line}.renderHtml()`, "renderHtml", Line, { receiver: true }), + ]; + + it("is an invocation to a corpus invocable", () => { + const { text } = lowered({ entities, edges: [edge("invocation", `${Order}.total()`, `${Order}.price()`)] }); + expect(text).toContain("depends on { Order.price }"); + }); + + it("writes a dynamic-candidate and every candidates entry with `?`", () => { + const { text } = lowered({ + entities, + edges: [ + edge("invocation", `${Order}.total()`, `${Line}.render()`, { + provenance: "dynamic-candidate", + candidates: [`${Line}.render()`, `${Line}.renderHtml()`], + }), + ], + }); + expect(text).toContain("depends on { Line.render?, Line.renderHtml? }"); + }); + + it("keeps a target firm when one edge declares it and another only suggests it", () => { + const { text } = lowered({ + entities, + edges: [ + edge("invocation", `${Order}.total()`, `${Line}.render()`, { provenance: "dynamic-candidate" }), + edge("invocation", `${Order}.total()`, `${Line}.render()`), + ], + }); + expect(text).toContain("depends on { Line.render }"); + }); +}); + +describe("uses", () => { + it("is an invocation to a stub: the external struct, or the external module when the stub is one", () => { + const { text } = lowered({ + entities: [...base, method(`${Order}.total()`, "total", Order, { receiver: true })], + edges: [ + edge("invocation", `${Order}.total()`, "java:java.util/List", { member: "size" }), + edge("invocation", `${Order}.total()`, "java:java.util", { member: "helper" }), + ], + }); + expect(text).toContain("uses { java.util, java.util.List }"); + expect(text).toContain("external module java.util\n"); + }); +}); + +describe("reads, writes", () => { + const total = `${Order}.total(${Line})`; + const entities = [ + ...base, + method(total, "total", Order, { receiver: true, params: [`${total}#line`] }), + param(`${total}#line`, "line", total, { typeExpr: lineType }), + ]; + + it("a global by its path", () => { + const { text } = lowered({ entities, edges: [edge("access", total, `${Order}.MAX`)] }); + expect(text).toContain("reads { Order.MAX }"); + }); + + it("`_.field` for receiver: self, read and written", () => { + const { text } = lowered({ entities, edges: [edge("access", total, `${Order}.lines`, { isRead: true, isWrite: true, receiver: "self" })] }); + expect(text).toContain("reads { _.lines }"); + expect(text).toContain("writes { _.lines }"); + }); + + it("`param.field` in writes for receiver: other when exactly one parameter is typed by the field's owner", () => { + const { text } = lowered({ entities, edges: [edge("access", total, `${Line}.qty`, { isRead: false, isWrite: true, receiver: "other" })] }); + expect(text).toContain("writes { line.qty }"); + }); + + it("a blind-spot finding when no parameter, or several, is typed by the owner", () => { + const two = `${Order}.merge(${Line},${Line})`; + const { text } = lowered({ + entities: [ + ...base, + method(two, "merge", Order, { receiver: true, params: [`${two}#a`, `${two}#b`] }), + param(`${two}#a`, "a", two, { typeExpr: lineType }), + param(`${two}#b`, "b", two, { typeExpr: lineType }), + method(`${Order}.reset()`, "reset", Order, { receiver: true }), + ], + edges: [ + edge("access", two, `${Line}.qty`, { isRead: false, isWrite: true, receiver: "other" }), + edge("access", `${Order}.reset()`, `${Line}.qty`, { isRead: false, isWrite: true, receiver: "other" }), + ], + }); + expect(text).toContain("// FINDING: blind-spot: writes Line.qty through another instance: 2 parameters typed by its owner"); + expect(text).toContain("// FINDING: blind-spot: writes Line.qty through another instance: no parameter typed by its owner"); + expect(text).not.toContain("writes {"); + }); + + it("a read through other is not declared, and counted", () => { + const { model, text } = lowered({ entities, edges: [edge("access", total, `${Line}.qty`, { receiver: "other" })] }); + expect(text).not.toContain("reads {"); + expect(model.summary.edgesNotDeclared["read through another instance"]).toBe(1); + }); + + it("without receiver on the edge, a field of the operation's own struct or a flattened supertype reads as self, any other as other", () => { + const Base = `${M}/Base`; + const { model, text } = lowered({ + entities: [...entities, type(Base, "Base", M), field(`${Base}.id`, "id", Base, { receiver: true })], + edges: [ + edge("inheritance", Order, Base), + edge("access", total, `${Order}.lines`), + edge("access", total, `${Base}.id`), + edge("access", total, `${Line}.qty`), + ], + }); + expect(text).toContain("reads { _.id, _.lines }"); + expect(model.summary.edgesNotDeclared["read through another instance"]).toBe(1); + }); +}); + +describe("entries", () => { + it("marks `entry` on every operation the boundary rules put in the inventory, and none without rules", () => { + const entities = [...base, method(`${Order}.submit()`, "submit", Order, { receiver: true })]; + expect(lowered({ entities }, { entries: [`${Order}.submit()`] }).text).toContain(' entry operation submit(): opaque "?"\n'); + expect(lowered({ entities }).text).not.toContain("entry operation"); + }); + + it("marks `entry?` on an entry the inventory inferred, never `entry`", () => { + const entities = [...base, method(`${Order}.submit()`, "submit", Order, { receiver: true })]; + const { model, text } = lowered({ entities }, { candidateEntries: [`${Order}.submit()`] }); + expect(text).toContain(' entry? operation submit(): opaque "?"\n'); + expect(model.summary.candidateEntries).toBe(1); + expect(model.summary.entries).toBe(0); + }); +}); + +describe("evidence and findings", () => { + it("writes `// source: file:start-end` on every declaration that has an anchor", () => { + const { text } = lowered({ entities: [...base, method(`${Order}.total()`, "total", Order, { receiver: true, line: 12, file: "Order.java" })] }); + expect(text).toContain(' operation total(): opaque "?"\n // source: Order.java:12-12\n'); + }); + + it("writes `// FINDING: branching: cyclomatic N` above 1, and nothing at 1", () => { + const { text } = lowered({ + entities: [ + ...base, + method(`${Order}.total()`, "total", Order, { receiver: true, cyclomatic: 3 }), + method(`${Order}.size()`, "size", Order, { receiver: true, cyclomatic: 1 }), + ], + }); + expect(text).toContain("// FINDING: branching: cyclomatic 3"); + expect(text).not.toContain("cyclomatic 1"); + }); +}); + +describe("order", () => { + it("is canonical: two runs print the same bytes, and declarations sort by name", () => { + const toy = { + entities: [ + ...base, + method(`${Order}.zeta()`, "zeta", Order, { receiver: true }), + method(`${Order}.alpha()`, "alpha", Order, { receiver: true }), + ], + }; + const one = lowered(toy).text; + expect(lowered(toy).text).toBe(one); + expect(one.indexOf("operation alpha")).toBeLessThan(one.indexOf("operation zeta")); + expect(one.indexOf("struct Line")).toBeLessThan(one.indexOf("struct Order")); + }); + + it("restricts the modules lowered to --scope; what falls outside becomes external", () => { + const B = "java:com.acme.billing"; + const graph = graphOf({ + entities: [ + ...base, + pkg(B, "com.acme.billing"), + type(`${B}/Invoice`, "Invoice", B), + method(`${B}/Invoice.issue()`, "issue", `${B}/Invoice`, { receiver: true }), + method(`${Order}.bill()`, "bill", Order, { receiver: true, typeExpr: { k: "named", type: `${B}/Invoice` } }), + ], + edges: [edge("invocation", `${Order}.bill()`, `${B}/Invoice.issue()`)], + }); + const model = lower(graph, { scope: { matches: (id) => id === M } }); + expect(model.modules.map((module) => module.segments.join("."))).toEqual(["com.acme.order"]); + const bill = model.modules[0]?.structs.find((struct) => struct.name === "Order")?.operations[0]; + expect(bill?.uses.map((use) => use.ref.name.path.join("."))).toEqual(["Invoice"]); + expect(model.externals.map((decl) => `${decl.kind} ${[...(decl.name.module ?? []), ...decl.name.path].join(".")}`)).toEqual([ + "external-module com.acme.billing", + "external-struct com.acme.billing.Invoice", + ]); + }); +}); diff --git a/packages/dataop/test/declarations.test.ts b/packages/dataop/test/declarations.test.ts new file mode 100644 index 00000000..93b6eb66 --- /dev/null +++ b/packages/dataop/test/declarations.test.ts @@ -0,0 +1,275 @@ +import { describe, expect, it } from "vitest"; +import { lower, print, DataOpError } from "../src/index.js"; +import { edge, field, graphOf, javaStubs, lambda, lowered, method, param, pkg, type } from "./toy.js"; + +/** + * §26.4, "Declarations": one test per row of the table, on hand-built graphs. + * The models state contract 1.2.0 in Java, so `TWithReceiver` is read as a fact + * (the fallback has its own tests in hazards.test.ts). + */ + +const M = "java:com.acme.order"; +const string = { k: "named", type: "java:java.lang/String" } as const; + +describe("a non-stub TModule → module", () => { + it("is named by its name, segment by segment where the profile qualifies with a dot", () => { + const { text } = lowered({ entities: [pkg(M, "com.acme.order")] }); + expect(text).toContain(" module com.acme.order {\n"); + }); + + it("is one quoted segment where the profile qualifies with a slash (a file path)", () => { + const { text } = lowered({ + lang: "python", + entities: [pkg("python:src/acme/order.py", "src/acme/order.py", { kind: "module" })], + }); + expect(text).toContain(' module @"src/acme/order.py" {\n'); + }); + + it("refuses a graph with no corpus module: nothing to lower", () => { + expect(() => lower(graphOf({ entities: [pkg("java:java.util", "java.util", { stub: true })] }))).toThrow(DataOpError); + }); +}); + +describe("a stub TModule, a stub TType → external module, external struct", () => { + const entities = [ + pkg(M, "com.acme.order"), + ...javaStubs(), + type(`${M}/Order`, "Order", M), + field(`${M}/Order.meta`, "meta", `${M}/Order`, { receiver: true, typeExpr: { k: "named", type: "java:java.util/Map" } }), + type("java:/Ghost", "Ghost", undefined, { stub: true }), + field(`${M}/Order.ghost`, "ghost", `${M}/Order`, { receiver: true, declaredType: "java:/Ghost" }), + ]; + + it("declares only the stubs the text references, at model level, before the modules", () => { + const { text } = lowered({ entities }); + expect(text).toContain(" external module java.util\n"); + expect(text).toContain(" external struct java.util.Map\n"); + expect(text).not.toContain("java.util.List"); + expect(text).not.toContain("external module java.lang"); + expect(text.indexOf("external struct java.util.Map")).toBeLessThan(text.indexOf("module com.acme.order {")); + }); + + it("declares a parentless stub at model level, unqualified", () => { + const { text } = lowered({ entities }); + expect(text).toContain(" external struct Ghost\n"); + expect(text).toContain("ghost: Ghost\n"); + }); + + it("declares a stub whose parent is a lowered module inside that module", () => { + const { text } = lowered({ + entities: [ + pkg(M, "com.acme.order"), + type(`${M}/Invoice`, "Invoice", M, { stub: true }), + type(`${M}/Order`, "Order", M), + field(`${M}/Order.invoice`, "invoice", `${M}/Order`, { receiver: true, declaredType: `${M}/Invoice` }), + ], + }); + expect(text).toContain(" module com.acme.order {\n external struct Invoice\n"); + }); +}); + +describe("a named non-stub TType → struct", () => { + it("is named by its name, with a mandatory schema block", () => { + const { text } = lowered({ entities: [pkg(M, "com.acme.order"), type(`${M}/Order`, "Order", M, { line: 4 })] }); + expect(text).toContain(" struct Order {\n // source: T.java:4-4\n schema {\n }\n }\n"); + }); + + it("keeps a nested type's path as one quoted name, written at module level", () => { + const { text } = lowered({ + entities: [pkg(M, "com.acme.order"), type(`${M}/Basket`, "Basket", M), type(`${M}/Basket.Line`, "Line", `${M}/Basket`)], + }); + expect(text).toContain(' struct @"Basket.Line" {\n'); + }); +}); + +describe("a nameless TType → nothing", () => { + it("is not declared, and its invocables fold into the nearest named operation", () => { + const run = `${M}/Batch.run()`; + const anon = `${M}/Batch#anon`; + const { model, text } = lowered({ + entities: [ + pkg(M, "com.acme.order"), + type(`${M}/Batch`, "Batch", M), + method(run, "run", `${M}/Batch`, { receiver: true }), + type(anon, undefined, run), + method(`${anon}.price()`, "price", anon, { receiver: true }), + method(`${M}/Batch.size()`, "size", `${M}/Batch`, { receiver: true }), + ], + edges: [edge("invocation", `${anon}.price()`, `${M}/Batch.size()`)], + }); + expect(text).not.toContain("price"); + expect(text).toMatch(/operation run\(\)[^]*depends on \{ Batch\.size \}/u); + const runOp = model.modules[0]?.structs[0]?.operations.find((op) => op.name === "run"); + expect(runOp?.sources).toContain(`${anon}.price()`); + }); +}); + +describe("a TStructural child of a type", () => { + const Order = `${M}/Order`; + const Base = `${M}/AbstractOrder`; + const entities = [ + pkg(M, "com.acme.order"), + ...javaStubs(), + type(Base, "AbstractOrder", M, { file: "AbstractOrder.java" }), + field(`${Base}.reference`, "reference", Base, { receiver: true, typeExpr: string, file: "AbstractOrder.java", line: 8 }), + type(Order, "Order", M, { file: "Order.java" }), + field(`${Order}.channel`, "channel", Order, { receiver: true, typeExpr: string, file: "Order.java", line: 14 }), + field(`${Order}.MAX_LINES`, "MAX_LINES", Order, { + typeExpr: { k: "primitive", name: "int" }, + value: { k: "number", v: "100" }, + file: "Order.java", + line: 9, + }), + field(`${Order}.TAG`, "TAG", Order, { typeExpr: string, value: { k: "unevaluated", source: "Tags.of(1)" } }), + field(`${Order}.CHANNEL`, "CHANNEL", Order, { typeExpr: string, value: { k: "enum", type: Order, name: "WEB" } }), + field(`${Order}.LOG`, "LOG", Order, { typeExpr: string }), + ]; + const edges = [edge("inheritance", Order, Base)]; + + it("with a receiver: a schema field", () => { + const { text } = lowered({ entities, edges }); + expect(text).toContain(" channel: string\n // source: Order.java:14-14\n"); + }); + + it("flattens the fields of corpus supertypes, each with its own anchor, and names them in a NOTE", () => { + const { text } = lowered({ entities, edges }); + expect(text).toContain(" reference: string\n // source: AbstractOrder.java:8-8\n"); + expect(text).toContain(" // NOTE: the schema flattens the fields of AbstractOrder: Specy has no inheritance\n"); + }); + + it("without a receiver: a global in the struct, its initial value JSON, opaque \"…\" or bare opaque", () => { + const { text } = lowered({ entities, edges }); + expect(text).toContain(" global MAX_LINES: number = 100\n // source: Order.java:9-9\n"); + expect(text).toContain(' global TAG: string = opaque "Tags.of(1)"\n'); + expect(text).toContain(" global CHANNEL: string = opaque\n"); + expect(text).toContain(" global LOG: string = opaque\n"); + expect(text).not.toMatch(/schema \{[^}]*MAX_LINES/u); + }); +}); + +describe("a TStructural child of a module → a global at module level", () => { + it("is a module-level global", () => { + const { text } = lowered({ + lang: "python", + entities: [ + pkg("python:src/acme.py", "src/acme.py", { kind: "module" }), + { ...field("python:src/acme.py/VERSION", "VERSION", "python:src/acme.py", { kind: "variable", value: { k: "string", v: 'a "1"' } }) }, + ], + }); + expect(text).toContain(' global VERSION: opaque "?" = "a \\"1\\""\n'); + }); +}); + +describe("a named TInvocable → operation", () => { + const Order = `${M}/Order`; + const Line = `${M}/Line`; + const entities = [ + pkg(M, "com.acme.order"), + type(Order, "Order", M), + type(Line, "Line", M), + method(`${Order}.total()`, "total", Order, { receiver: true, typeExpr: { k: "primitive", name: "long" } }), + method(`${Order}.create()`, "create", Order, { typeExpr: { k: "named", type: Order } }), + method(`${Order}.render()`, "render", Order, { receiver: true, attachedTo: Line }), + ]; + + it("nested where it is written, attached to its struct with a receiver", () => { + expect(lowered({ entities }).text).toContain(" operation total(): number\n"); + }); + + it("written `on module` without a receiver", () => { + expect(lowered({ entities }).text).toContain(" operation create(): Order on module\n"); + }); + + it("written `on Struct` when attachedTo differs from parent", () => { + expect(lowered({ entities }).text).toContain(" operation render() on Line\n"); + }); + + it("returns nothing when the language writes every return type and none is written", () => { + expect(lowered({ entities }).text).toMatch(/operation render\(\) on Line\n/u); + }); +}); + +describe("a constructor → operation new(…): Struct on module", () => { + const Order = `${M}/Order`; + const one = `${Order}.(java.lang.String)`; + const two = `${Order}.(java.lang.String,int)`; + const entities = [ + pkg(M, "com.acme.order"), + ...javaStubs(), + type(Order, "Order", M), + field(`${Order}.reference`, "reference", Order, { receiver: true, typeExpr: string }), + method(one, undefined, Order, { receiver: true, params: [`${one}#p`] }), + param(`${one}#p`, "reference", one, { typeExpr: string }), + method(two, undefined, Order, { receiver: true, params: [`${two}#p`, `${two}#q`] }), + param(`${two}#p`, "reference", two, { typeExpr: string }), + param(`${two}#q`, "lines", two, { typeExpr: { k: "primitive", name: "int" } }), + ]; + const edges = [edge("invocation", one, two), edge("access", two, `${Order}.reference`, { isRead: false, isWrite: true, receiver: "self" })]; + + it("is `new`, typed by its struct, on module", () => { + const { text } = lowered({ entities, edges }); + expect(text).toContain(" operation new(reference: string): Order on module\n"); + expect(text).toContain(" operation new(reference: string, lines: number): Order on module\n"); + }); + + it("is told apart from its overloads by its parameter types where it is referenced", () => { + expect(lowered({ entities, edges }).text).toContain("depends on { Order.new(string, number) }"); + }); + + it("does not declare its writes to the instance it builds, and counts them", () => { + const { model, text } = lowered({ entities, edges }); + expect(text).not.toContain("writes {"); + expect(text).not.toContain("blind-spot"); + expect(model.summary.edgesNotDeclared["the instance a constructor builds"]).toBe(1); + }); +}); + +describe("any other nameless invocable → nothing", () => { + it("folds its outgoing edges into the nearest named enclosing operation", () => { + const Order = `${M}/Order`; + const { model, text } = lowered({ + entities: [ + pkg(M, "com.acme.order"), + type(Order, "Order", M), + method(`${Order}.total()`, "total", Order, { receiver: true }), + lambda(`${Order}#lambda`, `${Order}.total()`), + method(`${Order}.price()`, "price", Order, { receiver: true }), + ], + edges: [edge("invocation", `${Order}#lambda`, `${Order}.price()`)], + }); + expect(text).toMatch(/operation total\(\)[^\n]*\n[^]*depends on \{ Order\.price \}/u); + expect(model.summary.foldedInvocables).toBe(1); + }); + + it("with no operation above it, its edges are counted, not declared", () => { + const Order = `${M}/Order`; + const { model } = lowered({ + entities: [ + pkg(M, "com.acme.order"), + type(Order, "Order", M), + lambda(`${Order}#init`, Order), + method(`${Order}.price()`, "price", Order, { receiver: true }), + ], + edges: [edge("invocation", `${Order}#init`, `${Order}.price()`)], + }); + expect(model.summary.unplacedInvocables).toBe(1); + expect(model.summary.edgesNotDeclared["no enclosing operation"]).toBe(1); + }); + + it("is not mistaken for a constructor when written in a type (a field initializer's lambda)", () => { + const Order = `${M}/Order`; + const { text } = lowered({ entities: [pkg(M, "com.acme.order"), type(Order, "Order", M), lambda(`${Order}#init`, Order)] }); + expect(text).not.toContain("operation new"); + }); +}); + +describe("the model header", () => { + it("names the model from its root, kebab-case, and states the level", () => { + expect(lowered({ root: "corpora/OrderService", entities: [pkg(M, "com.acme.order")] }).text).toContain("\nmodel order-service observed {\n"); + }); + + it("takes a given name, and refuses one the grammar does not accept", () => { + expect(print(lower(graphOf({ entities: [pkg(M, "com.acme.order")] }), { name: "billing" }))).toContain("model billing observed {"); + expect(() => lower(graphOf({ entities: [pkg(M, "com.acme.order")] }), { name: "Billing" })).toThrow(DataOpError); + }); +}); diff --git a/packages/dataop/test/fixtures.test.ts b/packages/dataop/test/fixtures.test.ts new file mode 100644 index 00000000..d998bab9 --- /dev/null +++ b/packages/dataop/test/fixtures.test.ts @@ -0,0 +1,95 @@ +import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { readModelFileSync, type Model } from "@codegraph/core"; +import { buildGraph, loadModels, type CodeGraph } from "@codegraph/analyzer"; +import { describe, expect, it } from "vitest"; +import { lower, print } from "../src/index.js"; +import { agreementViolations, closureViolations, lexicalViolations } from "./properties.js"; + +/** + * The three properties of §26.6 on EVERY committed fixture model, plus the + * scrambled-ids hazard of §26.9. The fixtures exercise the fallback paths in + * six languages. Nothing here pins a count: `fixtures/java` is regenerated by + * another step (M25b), and a property is what survives that. + */ + +const FIXTURES_DIR = fileURLToPath(new URL("../../../fixtures/", import.meta.url)); +const FIXTURES = readdirSync(FIXTURES_DIR) + .filter((name) => existsSync(`${FIXTURES_DIR}${name}/expected/model.jsonl`)) + .sort(); + +const modelOf = (fixture: string): Model => readModelFileSync(`${FIXTURES_DIR}${fixture}/expected/model.jsonl`); +const graphOf = (model: Model): CodeGraph => buildGraph(loadModels(model, { sources: ["fixture"] }).union); + +/** + * The same model with every id replaced by a meaningless one, consistently: + * entity ids and every reference to one (parent, attachedTo, declaredType, + * parameters, ids inside type expressions and values, edge endpoints and + * candidates). Names, kinds and anchors are untouched. + */ +function scrambled(model: Model): Model { + const ids = new Map(); + // A permutation that reverses the sorted order, so every id-ordered walk changes order. + const sorted = model.entities.map((entity) => entity.id).sort(); + sorted.forEach((id, index) => ids.set(id, `${model.lang}:scrambled/${String(sorted.length - index).padStart(6, "0")}`)); + const remap = (value: unknown, keyName: string | undefined): unknown => { + if (typeof value === "string") return keyName === "name" ? value : (ids.get(value) ?? value); + if (Array.isArray(value)) return value.map((item) => remap(item, keyName)); + if (typeof value === "object" && value !== null) { + return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, k === "anchor" || k === "comments" || k === "signature" ? v : remap(v, k)])); + } + return value; + }; + return remap(model, undefined) as Model; +} + +/** + * `fixtures/java/expected/model.dataop`, byte for byte (PLAN.md §26.8 step 4): the one fixture whose extractor + * writes type expressions and receivers, so the one where the lowering is read as a whole rather than through + * its properties. A change to the lowering shows in review as the lines it moved. + * `CODEGRAPH_UPDATE_SNAPSHOTS=1` rewrites it; read the diff before committing. + */ +it("fixtures/java lowers to its committed snapshot", () => { + const snapshot = `${FIXTURES_DIR}java/expected/model.dataop`; + const text = print(lower(graphOf(modelOf("java")))); + if (process.env["CODEGRAPH_UPDATE_SNAPSHOTS"] !== undefined) writeFileSync(snapshot, text); + expect(existsSync(snapshot), "write it: CODEGRAPH_UPDATE_SNAPSHOTS=1 pnpm --filter @codegraph/dataop test fixtures").toBe(true); + expect(text).toBe(readFileSync(snapshot, "utf8")); +}); + +it("finds the fixture models", () => { + expect(FIXTURES).toEqual(expect.arrayContaining(["csharp", "elixir", "java", "python", "ruby", "typescript"])); +}); + +describe.each(FIXTURES)("fixtures/%s", (fixture) => { + const model = modelOf(fixture); + const graph = graphOf(model); + const lowered = lower(graph); + const text = print(lowered); + + it("lowers", () => { + expect(lowered.modules.length).toBeGreaterThan(0); + }); + + it("lexical: every token lexes, braces balance, the text parses with no keyword or non-bare name printed bare", () => { + expect(lexicalViolations(text)).toEqual([]); + }); + + it("closure: every reference resolves to a declaration or a printed external", () => { + expect(closureViolations(lowered)).toEqual([]); + }); + + it("agreement: every clause item backed by an edge, every edge declared or counted, once", () => { + expect(agreementViolations(graph, lowered)).toEqual([]); + }); + + it("is deterministic: two runs print the same bytes", () => { + expect(print(lower(graphOf(modelOf(fixture))))).toBe(text); + }); + + it("names come from names, never ids: a model whose ids are scrambled prints the same text", () => { + const other = scrambled(model); + expect(other.entities.some((entity) => entity.id.includes("scrambled"))).toBe(true); + expect(print(lower(graphOf(other)))).toBe(text); + }); +}); diff --git a/packages/dataop/test/grammar.ts b/packages/dataop/test/grammar.ts new file mode 100644 index 00000000..304a02d4 --- /dev/null +++ b/packages/dataop/test/grammar.ts @@ -0,0 +1,399 @@ +/** + * A TEST-SIDE reader of `.dataop`, written from Specy's EBNF + * (`src/grammars/data-operation.ebnf`) and NOT from the printer: no parser of + * the language exists (§26.6), so this one stands in, for the subset the + * lowering prints. The lexer takes the token rules literally (an `identifier` + * is ASCII; a string has `\"` and `\\` and no line break; a keyword is a + * keyword wherever it stands), and the parser follows `operationDef`'s clause + * order. A keyword where a name is expected is a parse error — which is how a + * keyword printed bare is caught. + */ + +import { DATAOP_KEYWORDS } from "../src/names.js"; + +export type TokenKind = "keyword" | "identifier" | "quoted" | "string" | "number" | "punct" | "receiver"; + +export interface Token { + readonly kind: TokenKind; + /** The token's text; for `quoted` and `string`, the unescaped content. */ + readonly text: string; + readonly line: number; +} + +export class GrammarError extends Error {} + +const KEYWORDS: ReadonlySet = new Set(DATAOP_KEYWORDS); +const PUNCT = ["->", "::", "!=", ">=", "<=", "{", "}", "(", ")", "<", ">", ",", ":", ".", "?", "=", "-", "[", "]"]; + +/** `stringLiteral`: one line, `\"` and `\\` the only escapes. Returns the unescaped text and the index after it. */ +function readString(text: string, start: number, line: number): [string, number] { + let i = start + 1; + let out = ""; + for (;;) { + const char = text[i]; + if (char === undefined || char === "\n" || char === "\r") throw new GrammarError(`line ${line}: unterminated string`); + if (char === '"') return [out, i + 1]; + if (char === "\\") { + const next = text[i + 1]; + if (next !== '"' && next !== "\\") throw new GrammarError(`line ${line}: escape \\${next ?? ""} is not in the grammar`); + out += next; + i += 2; + continue; + } + out += char; + i += 1; + } +} + +/** Every token of the text, comments dropped; throws on any character the token rules do not accept. */ +export function lex(text: string): Token[] { + const tokens: Token[] = []; + let i = 0; + let line = 1; + while (i < text.length) { + const char = text[i] as string; + if (char === "\n") { + line += 1; + i += 1; + continue; + } + if (char === " " || char === "\t") { + i += 1; + continue; + } + if (text.startsWith("//", i)) { + const end = text.indexOf("\n", i); + i = end === -1 ? text.length : end; + continue; + } + if (char === '"') { + const [value, next] = readString(text, i, line); + tokens.push({ kind: "string", text: value, line }); + i = next; + continue; + } + if (char === "@") { + if (text[i + 1] !== '"') throw new GrammarError(`line ${line}: @ must open a quoted name`); + const [value, next] = readString(text, i + 1, line); + if (value.length === 0) throw new GrammarError(`line ${line}: a quoted name is empty (rule 25)`); + tokens.push({ kind: "quoted", text: value, line }); + i = next; + continue; + } + const number = /^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/u.exec(text.slice(i)); + if (number !== null && (/\d/u.test(char) || (char === "-" && /\d/u.test(text[i + 1] ?? "")))) { + tokens.push({ kind: "number", text: number[0], line }); + i += number[0].length; + continue; + } + const word = /^[A-Za-z_][A-Za-z0-9_]*/u.exec(text.slice(i)); + if (word !== null) { + const value = word[0]; + if (value === "_") tokens.push({ kind: "receiver", text: value, line }); + else if (/^_[A-Za-z0-9_]+$|^[A-Za-z][A-Za-z0-9_]*$/u.test(value)) { + tokens.push({ kind: KEYWORDS.has(value) ? "keyword" : "identifier", text: value, line }); + } else throw new GrammarError(`line ${line}: "${value}" is not an identifier`); + i += value.length; + continue; + } + const punct = PUNCT.find((candidate) => text.startsWith(candidate, i)); + if (punct !== undefined) { + tokens.push({ kind: "punct", text: punct, line }); + i += punct.length; + continue; + } + throw new GrammarError(`line ${line}: character ${JSON.stringify(char)} is in no token of the grammar`); + } + return tokens; +} + +/** What the parser hands back: every declared and every referenced qualified name, as segments. */ +export interface Parsed { + modelName: string; + readonly modules: string[][]; + readonly references: string[][]; + operations: number; + structs: number; +} + +/** + * The subset of `dataOpFile` the lowering prints: `modelDef` with + * `externalDecl`, `moduleDef`, `structDef` (schema, globals, operations), + * `globalDef`, `operationDef` (errors, depends on, uses, reads, writes, in + * that order), types and JSON values. Anything else is an error here. + */ +export function parse(text: string): Parsed { + const tokens = lex(text); + let at = 0; + const parsed: Parsed = { modelName: "", modules: [], references: [], operations: 0, structs: 0 }; + + const peek = (offset = 0): Token | undefined => tokens[at + offset]; + const fail = (what: string): never => { + const token = peek(); + throw new GrammarError(`line ${token?.line ?? "EOF"}: expected ${what}, found ${token === undefined ? "end of text" : `${token.kind} ${JSON.stringify(token.text)}`}`); + }; + const isKeyword = (word: string, offset = 0): boolean => peek(offset)?.kind === "keyword" && peek(offset)?.text === word; + const isPunct = (symbol: string, offset = 0): boolean => peek(offset)?.kind === "punct" && peek(offset)?.text === symbol; + const keyword = (word: string): void => { + if (!isKeyword(word)) fail(`keyword ${word}`); + at += 1; + }; + const punct = (symbol: string): void => { + if (!isPunct(symbol)) fail(`"${symbol}"`); + at += 1; + }; + const name = (): string => { + const token = peek(); + if (token === undefined || (token.kind !== "identifier" && token.kind !== "quoted")) return fail("a name (an identifier or @\"…\")"); + at += 1; + return token.text; + }; + const qualified = (): string[] => { + const segments = [name()]; + while (isPunct(".") && (peek(1)?.kind === "identifier" || peek(1)?.kind === "quoted")) { + at += 1; + segments.push(name()); + } + return segments; + }; + const reference = (): string[] => { + const segments = qualified(); + parsed.references.push(segments); + return segments; + }; + + const type = (): void => { + const token = peek(); + if (token?.kind === "keyword" && ["string", "number", "boolean"].includes(token.text)) at += 1; + else if (isKeyword("array")) { + at += 1; + punct("<"); + type(); + punct(">"); + } else if (isKeyword("opaque")) { + at += 1; + if (peek()?.kind !== "string") fail("the opaque type's string"); + at += 1; + } else if (isPunct("(")) { + at += 1; + if (!isPunct(")")) { + type(); + while (isPunct(",")) { + at += 1; + type(); + } + } + punct(")"); + punct("->"); + if (isKeyword("void")) at += 1; + else type(); + } else reference(); + if (isPunct("?")) at += 1; + }; + + const json = (): void => { + const token = peek(); + if (token?.kind === "string" || token?.kind === "number") at += 1; + else if (isKeyword("true") || isKeyword("false") || isKeyword("null")) at += 1; + else if (isPunct("[")) { + at += 1; + if (!isPunct("]")) { + json(); + while (isPunct(",")) { + at += 1; + json(); + } + } + punct("]"); + } else fail("a JSON value"); + }; + + const external = (): void => { + keyword("external"); + if (isKeyword("struct") || isKeyword("module")) at += 1; + else fail("struct or module"); + qualified(); + }; + + const global = (): void => { + keyword("global"); + name(); + punct(":"); + type(); + punct("="); + if (isKeyword("opaque")) { + at += 1; + if (peek()?.kind === "string") at += 1; + } else json(); + }; + + const accessTarget = (): void => { + if (peek()?.kind === "receiver") { + at += 1; + punct("."); + name(); + while (isPunct(".")) { + at += 1; + name(); + } + } else reference(); + }; + const list = (item: () => void): void => { + punct("{"); + item(); + while (isPunct(",")) { + at += 1; + item(); + } + punct("}"); + }; + + const operation = (): void => { + if (isKeyword("entry")) { + at += 1; + if (isPunct("?")) at += 1; + } + keyword("operation"); + parsed.operations += 1; + name(); + punct("("); + if (!isPunct(")")) { + const param = (): void => { + name(); + punct(":"); + type(); + }; + param(); + while (isPunct(",")) { + at += 1; + param(); + } + } + punct(")"); + if (isPunct(":")) { + at += 1; + type(); + } + if (isKeyword("on")) { + at += 1; + if (isKeyword("module")) at += 1; + else reference(); + } + // Clause order of `operationDef`: a clause out of order is not consumed, and the caller then fails on it. + if (isKeyword("errors")) { + at += 1; + punct("{"); + while (!isPunct("}")) { + name(); + if (isKeyword("of")) { + at += 1; + reference(); + } + if (isPunct(",")) at += 1; + } + punct("}"); + } + if (isKeyword("depends")) { + at += 1; + keyword("on"); + list(() => { + reference(); + if (isPunct("(")) { + at += 1; + if (!isPunct(")")) { + type(); + while (isPunct(",")) { + at += 1; + type(); + } + } + punct(")"); + } + if (isPunct("?")) at += 1; + }); + } + if (isKeyword("uses")) { + at += 1; + list(() => { + reference(); + if (isPunct("?")) at += 1; + }); + } + if (isKeyword("reads")) { + at += 1; + list(accessTarget); + } + if (isKeyword("writes")) { + at += 1; + list(accessTarget); + } + }; + + const struct = (): void => { + keyword("struct"); + parsed.structs += 1; + name(); + punct("{"); + keyword("schema"); + punct("{"); + while (!isPunct("}")) { + name(); + punct(":"); + type(); + } + punct("}"); + while (!isPunct("}")) { + if (isKeyword("global")) global(); + else if (isKeyword("operation") || isKeyword("entry")) operation(); + else fail("global or operation"); + } + punct("}"); + }; + + const module = (): void => { + keyword("module"); + parsed.modules.push(qualified()); + punct("{"); + while (!isPunct("}")) { + if (isKeyword("external")) external(); + else if (isKeyword("struct")) struct(); + else if (isKeyword("global")) global(); + else if (isKeyword("operation") || isKeyword("entry")) operation(); + else fail("a declaration"); + } + punct("}"); + }; + + keyword("model"); + const words = [name()]; + while (isPunct("-")) { + at += 1; + words.push(name()); + } + if (!words.every((word) => /^[a-z][A-Za-z0-9]*$/u.test(word))) fail("a kebab-case model name"); + parsed.modelName = words.join("-"); + keyword("observed"); + punct("{"); + while (isKeyword("external")) external(); + module(); + while (!isPunct("}")) { + if (isKeyword("module")) module(); + else if (isKeyword("external")) external(); + else fail("a module or an external declaration"); + } + punct("}"); + if (at !== tokens.length) fail("the end of the text"); + return parsed; +} + +/** `{` and `}`, `(` and `)` balance, in order. */ +export function balanced(tokens: readonly Token[]): boolean { + const stack: string[] = []; + const pairs: Record = { "}": "{", ")": "(" }; + for (const token of tokens) { + if (token.kind !== "punct") continue; + if (token.text === "{" || token.text === "(") stack.push(token.text); + else if (token.text === "}" || token.text === ")") if (stack.pop() !== pairs[token.text]) return false; + } + return stack.length === 0; +} diff --git a/packages/dataop/test/hazards.test.ts b/packages/dataop/test/hazards.test.ts new file mode 100644 index 00000000..51d86b2f --- /dev/null +++ b/packages/dataop/test/hazards.test.ts @@ -0,0 +1,192 @@ +import { getProfile } from "@codegraph/core"; +import { describe, expect, it } from "vitest"; +import { + DATAOP_KEYWORDS, + RECEIVER_FALLBACK, + isBareName, + lower, + print, + printName, + receiverKinds, + type DataOpModel, +} from "../src/index.js"; +import { lex, parse } from "./grammar.js"; +import { agreementViolations, closureViolations, lexicalViolations } from "./properties.js"; +import { edge, field, graphOf, lowered, method, param, pkg, type } from "./toy.js"; + +/** + * §26.9: each hazard with the test that pins it (the scrambled-ids one runs on + * every fixture, in fixtures.test.ts), and the properties shown to bite. + */ + +const M = "java:com.acme.order"; + +describe("a quoted name printed bare, or a keyword", () => { + it.each(DATAOP_KEYWORDS)("the keyword %s, as every kind of name, is quoted and the text parses", (word) => { + const S = `${M}/${word}`; + const op = `${S}.${word}(x)`; + const { text } = lowered({ + entities: [ + pkg(M, word), + type(S, word, M), + field(`${S}.f`, word, S, { receiver: true }), + field(`${S}.g`, `${word}G`, S, { value: { k: "boolean", v: true } }), + method(op, word, S, { receiver: true, params: [`${op}#p`] }), + param(`${op}#p`, word, op), + method(`${S}.other()`, "other", S, { receiver: true }), + ], + edges: [edge("invocation", `${S}.other()`, op), edge("access", `${S}.other()`, `${S}.f`, { receiver: "self" })], + }); + expect(lexicalViolations(text)).toEqual([]); + expect(text).toContain(`module @"${word}" {`); + expect(text).toContain(`struct @"${word}" {`); + expect(text).toContain(`operation @"${word}"(@"${word}": `); + expect(text).toContain(`reads { _.@"${word}" }`); + }); + + it("the grammar's keyword list is the EBNF's: every terminal word of two letters or more", () => { + // Restated from data-operation.ebnf; a word the grammar gains must be quoted too. + expect([...DATAOP_KEYWORDS].sort()).toEqual( + [ + "and", "array", "boolean", "corresponds", "depends", "derives", "else", "ensures", "entry", "errors", "external", + "false", "flow", "from", "global", "implements", "in", "is", "meta", "model", "module", "not", "null", "number", + "observed", "of", "old", "on", "opaque", "operation", "or", "raise", "reads", "represents", "requires", "result", + "return", "schema", "state", "strict", "string", "struct", "to", "true", "uses", "via", "void", "when", "write", "writes", + ].sort(), + ); + }); + + it.each(["valid?", "@cents", "Größe", "_", "2fa", "a b", 'say "hi"', "back\\slash", "src/order.ts", "<=>"])( + "a non-bare name %j is quoted and lexes back to itself", + (name) => { + expect(isBareName(name)).toBe(false); + const tokens = lex(printName(name)); + expect(tokens).toEqual([{ kind: "quoted", text: name, line: 1 }]); + }, + ); + + it("the lexical property sees what it forbids", () => { + const ok = 'model m observed {\n module a {\n }\n}\n'; + expect(lexicalViolations(ok)).toEqual([]); + expect(lexicalViolations(ok.replace("module a", "module model"))).not.toEqual([]); + expect(lexicalViolations(ok.replace("module a", "module Größe"))).not.toEqual([]); + expect(lexicalViolations(ok.replace(" }\n}", " }\n"))).not.toEqual([]); + expect(lexicalViolations(ok.replace("module a {\n }", 'module a {\n struct S {\n schema {\n }\n operation f()\n writes { _.x }\n reads { _.y }\n }\n }'))).not.toEqual([]); + expect(() => parse(ok)).not.toThrow(); + }); +}); + +describe("the fallback without TWithReceiver taken for a fact", () => { + const python = { + lang: "python", + entities: [ + pkg("python:src/a.py", "src/a.py", { kind: "module" }), + type("python:src/a.py/A", "A", "python:src/a.py"), + field("python:src/a.py/A.n", "n", "python:src/a.py/A", { value: { k: "number", v: "1" } }), + method("python:src/a.py/A.make", "make", "python:src/a.py/A"), + ], + }; + + it("is stated in the header, pinned to the profile's licence", () => { + // Python's profile licenses TWithReceiver on no kind: the header says so and the fallback holds. + expect(receiverKinds("python")).toEqual([]); + const { text } = lowered(python); + expect(text).toContain(`// receivers (python, contract 1.2.0): the profile licenses TWithReceiver on no kind`); + expect(text).toContain(`Fallback: ${RECEIVER_FALLBACK}.`); + // ...so a field with a value is a schema field, and a method with no marker is attached. + expect(text).toContain(" n: opaque"); + expect(text).toContain(" operation make(): opaque \"?\"\n"); + }); + + it("is not taken where the profile licenses the marker and the contract is 1.2.0", () => { + const licensed = getProfile("java")?.kinds; + expect(receiverKinds("java")).toEqual( + Object.entries(licensed ?? {}) + .filter(([, spec]) => spec.optional.includes("TWithReceiver") || spec.required.includes("TWithReceiver")) + .map(([kind]) => kind) + .sort(), + ); + const { text } = lowered({ + entities: [pkg(M, "com.acme.order"), type(`${M}/A`, "A", M), field(`${M}/A.n`, "n", `${M}/A`), method(`${M}/A.make()`, "make", `${M}/A`)], + }); + expect(text).toContain(`// receivers (java, contract 1.2.0): TWithReceiver is read as a fact on ${receiverKinds("java").join(", ")}`); + expect(text).toContain(" global n: opaque \"?\" = opaque\n"); + expect(text).toContain("operation make(): opaque \"?\" on module"); + }); + + it("is taken for a Java model stating a contract before 1.2.0, and the header says why", () => { + const { text } = lowered({ + schemaVersion: "1.1.0", + entities: [pkg(M, "com.acme.order"), type(`${M}/A`, "A", M), field(`${M}/A.n`, "n", `${M}/A`), method(`${M}/A.make()`, "make", `${M}/A`)], + }); + expect(text).toContain("// receivers (java, contract 1.1.0): the model states a contract before 1.2.0"); + expect(text).toContain(" n: opaque \"?\"\n"); + expect(text).toContain(" operation make(): opaque \"?\"\n"); + }); +}); + +describe("a flattened field anchored on the subtype", () => { + it("keeps the // source: of its declaring type's file", () => { + const Base = `${M}/Base`; + const Sub = `${M}/Sub`; + const { model, text } = lowered({ + entities: [ + pkg(M, "com.acme.order"), + type(Base, "Base", M, { file: "Base.java" }), + field(`${Base}.id`, "id", Base, { receiver: true, file: "Base.java", line: 3 }), + type(Sub, "Sub", M, { file: "Sub.java" }), + ], + edges: [edge("inheritance", Sub, Base)], + }); + const sub = model.modules[0]?.structs.find((struct) => struct.name === "Sub"); + expect(sub?.fields[0]?.anchor?.file).toBe("Base.java"); + expect(text).toMatch(/struct Sub \{\n {6}\/\/ source: Sub\.java:1-1\n[^]*id: opaque "\?"\n {10}\/\/ source: Base\.java:3-3\n/u); + }); +}); + +describe("a fold losing an edge: the agreement and closure properties bite", () => { + const O = `${M}/Order`; + const toy = { + entities: [ + pkg(M, "com.acme.order"), + pkg("java:java.util", "java.util", { stub: true }), + type("java:java.util/List", "List", "java:java.util", { stub: true }), + type(O, "Order", M), + field(`${O}.lines`, "lines", O, { receiver: true }), + method(`${O}.add()`, "add", O, { receiver: true }), + method(`${O}.size()`, "size", O, { receiver: true }), + ], + edges: [ + edge("invocation", `${O}.add()`, `${O}.size()`), + edge("invocation", `${O}.add()`, "java:java.util/List"), + edge("access", `${O}.add()`, `${O}.lines`, { receiver: "self" }), + ], + }; + + it("holds on the honest model", () => { + const graph = graphOf(toy); + const model = lower(graph); + expect(agreementViolations(graph, model)).toEqual([]); + expect(closureViolations(model)).toEqual([]); + }); + + it("finds an edge the ledger dropped, an item no edge backs, and a reference nothing declares", () => { + const graph = graphOf(toy); + const model = lower(graph); + const dropped: DataOpModel = { ...model, ledger: model.ledger.slice(1) }; + expect(agreementViolations(graph, dropped)).not.toEqual([]); + + const struct = model.modules[0]?.structs[0]; + const add = struct?.operations.find((op) => op.name === "add"); + if (struct === undefined || add === undefined) throw new Error("no Order.add"); + const invented = { ...add, reads: [...add.reads, { k: "self" as const, field: "lines", target: `${O}.size()` }] }; + const withInvented: DataOpModel = { + ...model, + modules: [{ ...model.modules[0]!, structs: [{ ...struct, operations: struct.operations.map((op) => (op === add ? invented : op)) }] }], + }; + expect(agreementViolations(graph, withInvented)).not.toEqual([]); + + expect(closureViolations({ ...model, externals: [] })).not.toEqual([]); + expect(print({ ...model, externals: [] })).not.toContain("external"); + }); +}); diff --git a/packages/dataop/test/properties.ts b/packages/dataop/test/properties.ts new file mode 100644 index 00000000..aada0609 --- /dev/null +++ b/packages/dataop/test/properties.ts @@ -0,0 +1,221 @@ +import type { Edge, EntityId } from "@codegraph/core"; +import { containingModule, type CodeGraph } from "@codegraph/analyzer"; +import type { DataOpModel, DataOpType, EdgeClause, OperationDecl, QName, StructDecl } from "../src/index.js"; +import { balanced, lex, parse } from "./grammar.js"; + +/** + * The three properties that stand in for a parser (PLAN.md §26.6), as + * functions returning the violations they find — empty means the property + * holds. They read the graph and the model value; none of them reuses the + * lowering's own code paths. + */ + +/** Lexical: every token lexes, braces balance, and the text parses — so no name a keyword or non-bare is printed bare. */ +export function lexicalViolations(text: string): string[] { + try { + const tokens = lex(text); + if (!balanced(tokens)) return ["braces or parentheses do not balance"]; + parse(text); + return []; + } catch (error) { + return [error instanceof Error ? error.message : String(error)]; + } +} + +const key = (segments: readonly string[]): string => segments.join("\u0000"); +const abs = (name: QName): string => key([...(name.module ?? []), ...name.path]); + +/** Closure (Specy's rule 9): every reference resolves to a declaration or a printed external. */ +export function closureViolations(model: DataOpModel): string[] { + const structs = new Map(); + const externalStructs = new Set(); + const externalModules = new Set(); + const modules = new Set(); + const operations = new Map(); + const globals = new Set(); + const addOperation = (path: readonly string[], op: OperationDecl): void => { + const list = operations.get(key(path)); + if (list === undefined) operations.set(key(path), [op]); + else list.push(op); + }; + for (const decl of model.externals) (decl.kind === "external-module" ? externalModules : externalStructs).add(abs(decl.name)); + for (const module of model.modules) { + modules.add(key(module.segments)); + for (const decl of module.externals) (decl.kind === "external-module" ? externalModules : externalStructs).add(abs(decl.name)); + for (const global of module.globals) globals.add(key([...module.segments, global.name])); + for (const op of module.operations) addOperation([...module.segments, op.name], op); + for (const struct of module.structs) { + structs.set(key([...module.segments, struct.name]), struct); + for (const global of struct.globals) globals.add(key([...module.segments, struct.name, global.name])); + for (const op of struct.operations) addOperation([...module.segments, struct.name, op.name], op); + } + } + + const out: string[] = []; + const where = (at: string, what: string): void => { + out.push(`${at}: ${what}`); + }; + const checkType = (type: DataOpType | undefined, at: string): void => { + if (type === undefined) return; + switch (type.k) { + case "ref": { + const name = abs(type.ref.name); + const known = type.ref.kind === "struct" ? structs.has(name) : type.ref.kind === "external-struct" ? externalStructs.has(name) : false; + if (!known) where(at, `type ${name.replaceAll("\u0000", ".")} (${type.ref.kind}) is not declared`); + return; + } + case "array": + case "nullable": + checkType(type.of, at); + return; + case "function": + type.params.forEach((param) => checkType(param, at)); + checkType(type.returns, at); + return; + default: + return; + } + }; + + for (const decl of [...model.externals, ...model.modules.flatMap((module) => module.externals)]) { + if (decl.kind === "external-struct" && decl.name.module !== null) { + const module = key(decl.name.module); + if (!externalModules.has(module) && !modules.has(module)) where(`external struct ${abs(decl.name)}`, "its module is not declared"); + } + } + + const checkOperation = (op: OperationDecl, at: string, enclosing: StructDecl | undefined): void => { + op.params.forEach((param) => checkType(param.type, `${at}(${param.name})`)); + checkType(op.returns, at); + if (op.on !== undefined && op.on !== "module" && !structs.has(abs(op.on))) where(at, `on ${abs(op.on)}: not a struct of the model (rule 14)`); + if (op.on === "module" && enclosing === undefined) where(at, "on module at module level (rule 14)"); + const receiver = op.on === undefined ? enclosing : op.on === "module" ? undefined : structs.get(abs(op.on)); + for (const error of op.errors) { + const name = abs(error.payload.name); + if (!structs.has(name) && !externalStructs.has(name)) where(at, `error payload ${name} is not declared`); + } + for (const item of op.dependsOn) { + const targets = operations.get(abs(item.ref)); + if (targets === undefined) where(at, `depends on ${abs(item.ref)}: no such operation`); + else if (targets.length > 1 && item.disambiguator === undefined) where(at, `depends on ${abs(item.ref)}: overloaded, no disambiguator (rule 8)`); + item.disambiguator?.forEach((type) => checkType(type, at)); + } + for (const item of op.uses) { + const name = abs(item.ref.name); + if (!(item.ref.kind === "external-struct" ? externalStructs : externalModules).has(name)) where(at, `uses ${name}: not an external declaration (rule 26)`); + } + for (const item of [...op.reads, ...op.writes]) { + if (item.k === "global" && !globals.has(abs(item.ref))) where(at, `access ${abs(item.ref)}: no such global`); + if (item.k === "self") { + if (receiver === undefined) where(at, `_.${item.field} in an operation attached to nothing (rule 14)`); + else if (!receiver.fields.some((field) => field.name === item.field)) where(at, `_.${item.field}: not a field of ${receiver.name}`); + } + if (item.k === "param") { + const param = op.params.find((candidate) => candidate.name === item.param); + const type = param?.type; + const struct = type?.k === "ref" && type.ref.kind === "struct" ? structs.get(abs(type.ref.name)) : undefined; + if (struct === undefined) where(at, `${item.param}.${item.field}: the parameter is not typed by a struct of the model (rule 27)`); + else if (!struct.fields.some((field) => field.name === item.field)) where(at, `${item.param}.${item.field}: not a field of ${struct.name}`); + } + } + }; + + for (const module of model.modules) { + const at = module.segments.join("."); + module.globals.forEach((global) => checkType(global.type, `${at}.${global.name}`)); + module.operations.forEach((op) => checkOperation(op, `${at}.${op.name}`, undefined)); + for (const struct of module.structs) { + struct.fields.forEach((field) => checkType(field.type, `${at}.${struct.name}.${field.name}`)); + struct.globals.forEach((global) => checkType(global.type, `${at}.${struct.name}.${global.name}`)); + struct.operations.forEach((op) => checkOperation(op, `${at}.${struct.name}.${op.name}`, struct)); + } + } + return out; +} + +const CLAUSE_EDGE: Readonly> = { + errors: "throws", + "depends on": "invocation", + uses: "invocation", + reads: "access", + writes: "access", +}; + +/** + * Agreement with the graph: every clause item is backed by an edge of the + * right kind from the operation or something folded into it, and every edge of + * the three kinds leaving a lowered declaration is declared or counted — once. + */ +export function agreementViolations(graph: CodeGraph, model: DataOpModel): string[] { + const out: string[] = []; + const operations = new Map(); + for (const module of model.modules) { + for (const op of module.operations) operations.set(op.entity, op); + for (const struct of module.structs) for (const op of struct.operations) operations.set(op.entity, op); + } + const loweredModules = new Set(model.modules.map((module) => module.entity)); + + // Both ways: the edges the model must account for, computed here from the graph alone. + const expected = graph.edges.filter((edge) => { + if (edge.edge !== "invocation" && edge.edge !== "access" && edge.edge !== "throws") return false; + const from = graph.entity(edge.from); + if (from === undefined || graph.isStub(edge.from)) return false; + const module = containingModule(graph, edge.from); + return module === undefined || loweredModules.has(module); + }); + const seen = new Map(); + for (const entry of model.ledger) seen.set(entry.edge, (seen.get(entry.edge) ?? 0) + 1); + for (const edge of expected) { + const count = seen.get(edge) ?? 0; + if (count !== 1) out.push(`${edge.edge} ${edge.from} -> ${edge.to}: in the ledger ${count} times`); + } + if (model.ledger.length !== expected.length) out.push(`ledger holds ${model.ledger.length} edges, the graph ${expected.length}`); + const counted = Object.values(model.summary.edgesNotDeclared).reduce((total, count) => total + (count ?? 0), 0); + if (model.summary.edgesDeclared + counted !== expected.length) { + out.push(`summary counts ${model.summary.edgesDeclared} + ${counted}, the graph ${expected.length}`); + } + + const within = (id: EntityId, op: OperationDecl): boolean => { + if (op.sources.includes(id)) return true; + const seenIds = new Set(); + for (let cursor = graph.parentOf(id); cursor !== undefined && !seenIds.has(cursor); cursor = graph.parentOf(cursor)) { + seenIds.add(cursor); + if (op.sources.includes(cursor)) return true; + } + return false; + }; + for (const entry of model.ledger) { + if (!("declared" in entry.outcome)) continue; + const op = entry.operation === undefined ? undefined : operations.get(entry.operation); + if (op === undefined) out.push(`declared edge ${entry.edge.from} -> ${entry.edge.to} is charged to no operation of the model`); + else if (!within(entry.edge.from, op)) out.push(`edge from ${entry.edge.from} charged to ${op.name}, which neither is nor folds it`); + for (const clause of entry.outcome.declared) if (CLAUSE_EDGE[clause] !== entry.edge.edge) out.push(`a ${entry.edge.edge} edge declared a ${clause} item`); + } + + for (const op of operations.values()) { + const backing = (clause: EdgeClause): Edge[] => + model.ledger + .filter((entry) => entry.operation === op.entity && "declared" in entry.outcome && entry.outcome.declared.includes(clause)) + .map((entry) => entry.edge); + const clauses: [EdgeClause, readonly unknown[]][] = [ + ["errors", op.errors], + ["depends on", op.dependsOn], + ["uses", op.uses], + ["reads", op.reads], + ["writes", op.writes], + ]; + for (const [clause, items] of clauses) { + if (items.length > 0 && backing(clause).length === 0) out.push(`${op.name}: ${clause} has items and no edge behind them`); + } + for (const item of op.dependsOn) { + const ok = backing("depends on").some((edge) => edge.to === item.target || (edge.candidates ?? []).includes(item.target)); + if (!ok) out.push(`${op.name}: depends on ${item.ref.path.join(".")} has no invocation to ${item.target}`); + } + for (const [clause, items] of [["reads", op.reads], ["writes", op.writes]] as const) { + for (const item of items) { + if (!backing(clause).some((edge) => edge.to === item.target)) out.push(`${op.name}: ${clause} item has no access to ${item.target}`); + } + } + } + return out; +} diff --git a/packages/dataop/test/toy.ts b/packages/dataop/test/toy.ts new file mode 100644 index 00000000..55d475ce --- /dev/null +++ b/packages/dataop/test/toy.ts @@ -0,0 +1,188 @@ +import type { Edge, Entity, Literal, Model, TypeExpr } from "@codegraph/core"; +import { buildGraph, loadModels, type CodeGraph } from "@codegraph/analyzer"; +import { lower, print, type DataOpModel, type LowerOptions } from "../src/index.js"; + +/** + * Hand-built graphs, written as an extractor would write them: the lowering is + * developed against these, not against a fixture another step regenerates. + */ + +export interface ToyModel { + readonly lang?: string; + readonly schemaVersion?: string; + readonly root?: string; + readonly entities: readonly Entity[]; + readonly edges?: readonly Edge[]; +} + +export function modelOf(toy: ToyModel): Model { + return { + schemaVersion: toy.schemaVersion ?? "1.2.0", + lang: toy.lang ?? "java", + extractor: { name: "toy", version: "0.0.0" }, + root: toy.root ?? "toy/order-service", + entities: [...toy.entities], + edges: [...(toy.edges ?? [])], + }; +} + +export function graphOf(...toys: readonly ToyModel[]): CodeGraph { + return buildGraph(loadModels(toys.map(modelOf), { sources: toys.map((_, i) => `toy-${i}`) }).union); +} + +/** Lower and print a toy model in one step. */ +export function lowered(toy: ToyModel, options: LowerOptions = {}): { model: DataOpModel; text: string } { + const model = lower(graphOf(toy), options); + return { model, text: print(model) }; +} + +const anchorAt = (line: number, file = "T.java"): { anchor: { file: string; span: [number, number] } } => ({ + anchor: { file, span: [line, line] }, +}); + +interface Common { + readonly stub?: boolean; + readonly kind?: string; + readonly line?: number; + readonly file?: string; +} + +export function pkg(id: string, name: string, options: Common & { readonly parent?: string } = {}): Entity { + return { + id, + kind: options.kind ?? "package", + traits: ["TNamed", "TModule", "TWithChildren", ...(options.parent === undefined ? [] : ["TChildOf"])], + name, + isStub: options.stub ?? false, + definedIn: [], + ...(options.parent === undefined ? {} : { parent: options.parent }), + } as Entity; +} + +export function type(id: string, name: string | undefined, parent: string | undefined, options: Common = {}): Entity { + const traits = ["TType", "TWithChildren"]; + if (name !== undefined) traits.push("TNamed"); + if (parent !== undefined) traits.push("TChildOf"); + if (options.stub !== true) traits.push("TSourceAnchor"); + return { + id, + kind: options.kind ?? "class", + traits, + ...(name === undefined ? {} : { name }), + isStub: options.stub ?? false, + ...(parent === undefined ? {} : { parent }), + ...(options.stub === true ? {} : anchorAt(options.line ?? 1, options.file)), + } as Entity; +} + +interface Typed { + readonly typeExpr?: TypeExpr; + readonly declaredType?: string; +} + +export function field( + id: string, + name: string, + parent: string, + options: Common & Typed & { readonly receiver?: boolean; readonly value?: Literal } = {}, +): Entity { + const traits = ["TNamed", "TStructural", "TChildOf", "TTypedEntity", "TSourceAnchor"]; + if (options.receiver === true) traits.push("TWithReceiver"); + if (options.value !== undefined) traits.push("TWithValue"); + return { + id, + kind: options.kind ?? "attribute", + traits, + name, + parent, + ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }), + ...(options.typeExpr === undefined ? {} : { typeExpr: options.typeExpr }), + ...(options.value === undefined ? {} : { value: options.value }), + ...anchorAt(options.line ?? 1, options.file), + } as Entity; +} + +export function param(id: string, name: string | undefined, parent: string, options: Typed = {}): Entity { + const traits = ["TStructural", "TChildOf", "TTypedEntity"]; + if (name !== undefined) traits.push("TNamed"); + return { + id, + kind: "parameter", + traits, + ...(name === undefined ? {} : { name }), + parent, + ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }), + ...(options.typeExpr === undefined ? {} : { typeExpr: options.typeExpr }), + } as Entity; +} + +export function method( + id: string, + name: string | undefined, + parent: string, + options: Common & + Typed & { + readonly params?: readonly string[]; + readonly receiver?: boolean; + readonly attachedTo?: string; + readonly cyclomatic?: number; + } = {}, +): Entity { + const traits = ["TInvocable", "TWithParameters", "TChildOf", "TSourceAnchor", "TTypedEntity"]; + if (name !== undefined) traits.push("TNamed"); + if (options.receiver === true) traits.push("TWithReceiver"); + if (options.attachedTo !== undefined) traits.push("TAttachedTo"); + if (options.cyclomatic !== undefined) traits.push("TMetrics"); + return { + id, + kind: options.kind ?? (name === undefined ? "constructor" : "method"), + traits, + ...(name === undefined ? {} : { name }), + parent, + signature: `${name ?? ""}()`, + parameters: [...(options.params ?? [])], + ...(options.declaredType === undefined ? {} : { declaredType: options.declaredType }), + ...(options.typeExpr === undefined ? {} : { typeExpr: options.typeExpr }), + ...(options.attachedTo === undefined ? {} : { attachedTo: options.attachedTo }), + ...(options.cyclomatic === undefined ? {} : { metrics: { cyclomatic: options.cyclomatic } }), + ...anchorAt(options.line ?? 1, options.file), + } as Entity; +} + +export function lambda(id: string, parent: string, options: Common = {}): Entity { + return { + id, + kind: options.kind ?? "lambda", + traits: ["TInvocable", "TWithParameters", "TChildOf", "TSourceAnchor"], + parent, + signature: "lambda()", + parameters: [], + ...anchorAt(options.line ?? 1, options.file), + } as Entity; +} + +export function edge( + kind: Edge["edge"], + from: string, + to: string, + extra: Record = {}, +): Edge { + const base = { edge: kind, from, to, provenance: "declared", anchor: { file: "T.java", span: [1, 1] } }; + const access = kind === "access" ? { isRead: true, isWrite: false } : {}; + const annotation = kind === "annotationUse" ? { arguments: [] } : {}; + return { ...base, ...access, ...annotation, ...extra } as Edge; +} + +/** The Java standard library stubs the type table names. */ +export function javaStubs(): Entity[] { + return [ + pkg("java:java.lang", "java.lang", { stub: true }), + pkg("java:java.util", "java.util", { stub: true }), + type("java:java.lang/String", "String", "java:java.lang", { stub: true }), + type("java:java.lang/Integer", "Integer", "java:java.lang", { stub: true }), + type("java:java.lang/Boolean", "Boolean", "java:java.lang", { stub: true }), + type("java:java.util/List", "List", "java:java.util", { stub: true }), + type("java:java.util/Optional", "Optional", "java:java.util", { stub: true }), + type("java:java.util/Map", "Map", "java:java.util", { stub: true }), + ]; +} diff --git a/packages/dataop/test/types.test.ts b/packages/dataop/test/types.test.ts new file mode 100644 index 00000000..209fb33b --- /dev/null +++ b/packages/dataop/test/types.test.ts @@ -0,0 +1,102 @@ +import type { Entity, TypeExpr } from "@codegraph/core"; +import { describe, expect, it } from "vitest"; +import { field, javaStubs, lowered, pkg, type } from "./toy.js"; + +/** + * §26.4, "Types": one test per row, each a field of struct `Holder` typed by + * the row's type expression. The Java table is the data under test; the other + * languages' tables are empty and say so in the header. + */ + +const M = "java:com.acme.order"; +const Holder = `${M}/Holder`; + +function fieldTyped(spec: { typeExpr?: TypeExpr; declaredType?: string }, extra: readonly Entity[] = [], lang = "java"): string { + const { text } = lowered({ + lang, + entities: [ + pkg(M, "com.acme.order"), + ...javaStubs(), + type(Holder, "Holder", M), + type(`${M}/Line`, "Line", M), + pkg("java:com.acme.billing", "com.acme.billing"), + type("java:com.acme.billing/Invoice", "Invoice", "java:com.acme.billing"), + ...extra, + field(`${Holder}.x`, "x", Holder, { receiver: true, ...spec }), + ], + }); + const match = /\n {8}x: ([^\n]*)\n/u.exec(text); + if (match === null) throw new Error(`no field x in:\n${text}`); + return match[1] as string; +} + +const named = (target: string, args?: TypeExpr[]): TypeExpr => + args === undefined ? { k: "named", type: target } : { k: "named", type: target, args }; + +describe("types", () => { + it("primitive, or named on a scalar of the table → string, number, boolean", () => { + expect(fieldTyped({ typeExpr: { k: "primitive", name: "long" } })).toBe("number"); + expect(fieldTyped({ typeExpr: { k: "primitive", name: "boolean" } })).toBe("boolean"); + expect(fieldTyped({ typeExpr: named("java:java.lang/String") })).toBe("string"); + expect(fieldTyped({ typeExpr: named("java:java.lang/Integer") })).toBe("number"); + expect(fieldTyped({ typeExpr: named("java:java.lang/Boolean") })).toBe("boolean"); + }); + + it("named on a sequence of the table with one argument, array → array", () => { + expect(fieldTyped({ typeExpr: named("java:java.util/List", [named(`${M}/Line`)]) })).toBe("array"); + expect(fieldTyped({ typeExpr: { k: "array", of: { k: "primitive", name: "int" } } })).toBe("array"); + }); + + it("named on an optional of the table, nullable → T?", () => { + expect(fieldTyped({ typeExpr: named("java:java.util/Optional", [named("java:java.lang/String")]) })).toBe("string?"); + expect(fieldTyped({ typeExpr: { k: "nullable", of: named(`${M}/Line`) } })).toBe("Line?"); + }); + + it("named with no argument → a struct reference, qualified across modules", () => { + expect(fieldTyped({ typeExpr: named(`${M}/Line`) })).toBe("Line"); + expect(fieldTyped({ typeExpr: named("java:com.acme.billing/Invoice") })).toBe("com.acme.billing.Invoice"); + expect(fieldTyped({ typeExpr: named("java:java.util/Map") })).toBe("java.util.Map"); + }); + + it("function → (T, U) -> R, void when nothing is returned", () => { + expect(fieldTyped({ typeExpr: { k: "function", params: [named(`${M}/Line`), { k: "primitive", name: "int" }], returns: named("java:java.lang/String") } })).toBe( + "(Line, number) -> string", + ); + expect(fieldTyped({ typeExpr: { k: "function", params: [named(`${M}/Line`)] } })).toBe("(Line) -> void"); + }); + + it('anything else → opaque "", heads named by module and path, never by id', () => { + expect(fieldTyped({ typeExpr: named("java:java.util/Map", [named("java:java.lang/String"), named(`${M}/Line`)]) })).toBe( + 'opaque "java.util.Map"', + ); + expect(fieldTyped({ typeExpr: { k: "union", of: [named(`${M}/Line`), { k: "primitive", name: "int" }] } })).toBe('opaque "com.acme.order.Line | int"'); + expect(fieldTyped({ typeExpr: { k: "variable", name: "T" } })).toBe('opaque "T"'); + expect(fieldTyped({ typeExpr: { k: "unevaluated", source: "? extends Line" } })).toBe('opaque "? extends Line"'); + }); + + it("no typeExpr, declaredType present → a struct reference to it (the erased head)", () => { + expect(fieldTyped({ declaredType: "java:java.util/List" })).toBe("java.util.List"); + expect(fieldTyped({ declaredType: `${M}/Line` })).toBe("Line"); + }); + + it("no typeExpr, declaredType a scalar of the table → the scalar (no argument is lost: a scalar has none)", () => { + expect(fieldTyped({ declaredType: "java:java.lang/String" })).toBe("string"); + }); + + it('neither → opaque "?"', () => { + expect(fieldTyped({})).toBe('opaque "?"'); + }); + + it("a language whose table is empty prints a primitive opaque, and its header says the table is empty", () => { + const { text } = lowered({ + lang: "python", + entities: [ + pkg("python:src/a.py", "src/a.py", { kind: "module" }), + type("python:src/a.py/A", "A", "python:src/a.py"), + field("python:src/a.py/A.n", "n", "python:src/a.py/A", { typeExpr: { k: "primitive", name: "int" } }), + ], + }); + expect(text).toContain('n: opaque "int"'); + expect(text).toContain("// types (python): the type table is empty"); + }); +}); diff --git a/packages/dataop/tsconfig.json b/packages/dataop/tsconfig.json new file mode 100644 index 00000000..24b956a8 --- /dev/null +++ b/packages/dataop/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "dist" + }, + "include": ["src", "test"] +} diff --git a/packages/dataop/tsup.config.ts b/packages/dataop/tsup.config.ts new file mode 100644 index 00000000..16f4d3eb --- /dev/null +++ b/packages/dataop/tsup.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from "tsup"; + +export default defineConfig({ + entry: ["src/index.ts"], + format: ["esm"], + dts: true, + clean: true, + sourcemap: true, + target: "node22", +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6c6c13ce..411a6fca 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -143,6 +143,9 @@ importers: '@codegraph/core': specifier: workspace:* version: link:../core + '@codegraph/dataop': + specifier: workspace:* + version: link:../dataop '@codegraph/insights': specifier: workspace:* version: link:../insights @@ -206,6 +209,31 @@ importers: specifier: 'catalog:' version: 3.2.7(@types/node@22.20.1)(tsx@4.23.12) + packages/dataop: + dependencies: + '@codegraph/analyzer': + specifier: workspace:* + version: link:../analyzer + '@codegraph/core': + specifier: workspace:* + version: link:../core + devDependencies: + '@types/node': + specifier: 'catalog:' + version: 22.20.1 + fast-check: + specifier: 'catalog:' + version: 4.9.0 + tsup: + specifier: 'catalog:' + version: 8.5.1(postcss@8.5.26)(tsx@4.23.12)(typescript@5.9.3) + typescript: + specifier: 'catalog:' + version: 5.9.3 + vitest: + specifier: 'catalog:' + version: 3.2.7(@types/node@22.20.1)(tsx@4.23.12) + packages/insights: dependencies: '@codegraph/analyzer': diff --git a/schemas/README.md b/schemas/README.md index 01665797..7a3b728a 100644 --- a/schemas/README.md +++ b/schemas/README.md @@ -1,4 +1,4 @@ -# Codegraph interchange contract (`model.jsonl`, 1.1.0) +# Codegraph interchange contract (`model.jsonl`, 1.2.0) **Generated from `@codegraph/core` — edit the source and re-run `pnpm run gen:schemas`, never these files.** @@ -79,6 +79,14 @@ Every reference to an entity is its surrogate — the integer `i` of its record. | `f`, `o` | every edge record | surrogate | | `candidates` | edge record | array of surrogates | +Two keys hold a TREE rather than a reference, and every id inside the tree is a +surrogate by the same rule: `value` (`TWithValue`, a `$defs/Literal`; its +`enum`, `type` and `annotation` forms name a type) with an edge's +`arguments`, and `typeExpr` (`TTypedEntity`, since 1.2.0, a +`$defs/TypeExpr`; its `named` form names a type in `type`). Closure reaches +inside both: a surrogate in a tree that resolves to no entity is an error like +any other. + Surrogates are **file-scoped and not identity**: they are assigned by canonical order, so they change whenever the model changes, and they must never be stored outside the file that assigned them or compared across files. Joining two models @@ -99,7 +107,7 @@ renumbers an existing file. An index the header does not declare is an error. An entity record carries **exactly** the keys its declared traits contribute: present when the trait is declared, absent when it is not. Optional-valued keys -(`declaredType`) may be absent even when their trait is declared. +(`declaredType`, `typeExpr`) may be absent even when their trait is declared. | trait | keys on the wire | | |---|---|---| @@ -113,13 +121,14 @@ present when the trait is declared, absent when it is not. Optional-valued keys | `TType` | `isStub` | | `TWithInheritances` | — | *(marker)* | `TWithImplements` | — | *(marker)* -| `TTypedEntity` | `declaredType` | +| `TTypedEntity` | `declaredType`, `typeExpr` | | `TInvocable` | `signature` | | `TWithParameters` | `parameters` | | `TWithLocalVariables` | `localVariables` | | `TWithInvocations` | — | *(marker)* | `TStructural` | — | *(marker)* | `TWithAccesses` | — | *(marker)* +| `TWithReceiver` | — | *(marker)* | `TMetrics` | `metrics` | | `TWithValue` | `value` | @@ -151,6 +160,11 @@ A conforming file satisfies all of: an `invocation`, `access` or `reference` edge whose `o` is a stub. A member of a corpus entity is an entity, and the edge points at it. The member is a string, never a reference: no entity is made for it. +- **A receiver only where a member needs an instance** (since 1.2.0) — an + edge's `receiver` (`"self"` through the accessor's own receiver, written or + implied; `"other"` through any other expression) is legal only on an + `access` edge whose `o` is **not** a stub: a stub has no members, so the + model holds nothing a receiver could be about. - **Counts** — `eof.counts` states how many `f`, `e` and `x` records were written. A reader that reaches end-of-input without an `eof`, or whose tallies disagree with it, must reject the file: that is how a truncated or killed run @@ -164,10 +178,13 @@ Entities are sorted by natural key — `lang`, then `module`, then `symbol`, the order **is** the surrogate assignment. Edges follow, sorted by `f`, then `o`, then edge kind, then anchor -(file, start, end), then provenance, then `member` with the absent one first -(UTF-16 code units). Within an edge record the keys are written `t`, `k`, -`f`, `o`, `p`, then `member`, `candidates`, `arguments`, `isRead`, -`isWrite`, `sourceFile`, `anchor` — each optional key only when present. +(file, start, end), then provenance, then `member`, then `receiver` — each of +the last two with the absent one first, then by UTF-16 code units. Within an +edge record the keys are written `t`, `k`, `f`, `o`, `p`, then `member`, +`candidates`, `arguments`, `isRead`, `isWrite`, `receiver`, `sourceFile`, +`anchor` — each optional key only when present. Inside a `typeExpr` the keys +are written `k` first, then the form's own in the order `$defs/TypeExpr` +lists them; nothing inside a tree is sorted, since written order is a fact. File records are sorted by path; dictionary entries are sorted. diff --git a/schemas/e.record.schema.json b/schemas/e.record.schema.json index e9e32608..241548a9 100644 --- a/schemas/e.record.schema.json +++ b/schemas/e.record.schema.json @@ -184,9 +184,164 @@ "value" ], "type": "object" + }, + "TypeExpr": { + "description": "The type a declaration writes (METAMODEL.md §1.7), as a tree, with entity ids as surrogates. Never inferred: a written type the extractor did not structure rides as `unevaluated` with its source text.", + "oneOf": [ + { + "properties": { + "args": { + "items": { + "$ref": "#/$defs/TypeExpr" + }, + "minItems": 1, + "type": "array" + }, + "k": { + "const": "named", + "type": "string" + }, + "type": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "k", + "type" + ], + "type": "object" + }, + { + "properties": { + "k": { + "const": "primitive", + "type": "string" + }, + "name": { + "minLength": 1, + "type": "string" + } + }, + "required": [ + "k", + "name" + ], + "type": "object" + }, + { + "properties": { + "k": { + "const": "array", + "type": "string" + }, + "of": { + "$ref": "#/$defs/TypeExpr" + } + }, + "required": [ + "k", + "of" + ], + "type": "object" + }, + { + "properties": { + "k": { + "const": "nullable", + "type": "string" + }, + "of": { + "$ref": "#/$defs/TypeExpr" + } + }, + "required": [ + "k", + "of" + ], + "type": "object" + }, + { + "properties": { + "k": { + "const": "function", + "type": "string" + }, + "params": { + "items": { + "$ref": "#/$defs/TypeExpr" + }, + "type": "array" + }, + "returns": { + "$ref": "#/$defs/TypeExpr" + } + }, + "required": [ + "k", + "params" + ], + "type": "object" + }, + { + "properties": { + "k": { + "const": "union", + "type": "string" + }, + "of": { + "items": { + "$ref": "#/$defs/TypeExpr" + }, + "minItems": 2, + "type": "array" + } + }, + "required": [ + "k", + "of" + ], + "type": "object" + }, + { + "properties": { + "k": { + "const": "variable", + "type": "string" + }, + "name": { + "minLength": 1, + "type": "string" + } + }, + "required": [ + "k", + "name" + ], + "type": "object" + }, + { + "properties": { + "k": { + "const": "unevaluated", + "type": "string" + }, + "source": { + "minLength": 1, + "type": "string" + } + }, + "required": [ + "k", + "source" + ], + "type": "object" + } + ] } }, - "$id": "https://codegraph.dev/schemas/e.record-1.1.0.schema.json", + "$id": "https://codegraph.dev/schemas/e.record-1.2.0.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": {}, "description": "One entity. `i` is its surrogate and equals its position in the section; `m`/`s`/`d` are the natural key, with `lang` taken from the header — no rendered id appears in the file. A module names ITSELF in `m` and writes its own path in `s`.", @@ -320,6 +475,9 @@ }, "type": "array" }, + "typeExpr": { + "$ref": "#/$defs/TypeExpr" + }, "value": { "$ref": "#/$defs/Literal" } @@ -332,6 +490,6 @@ "m", "s" ], - "title": "Codegraph model.jsonl \"e\" record (interchange contract 1.1.0)", + "title": "Codegraph model.jsonl \"e\" record (interchange contract 1.2.0)", "type": "object" } diff --git a/schemas/eof.record.schema.json b/schemas/eof.record.schema.json index cfa689bb..520688ad 100644 --- a/schemas/eof.record.schema.json +++ b/schemas/eof.record.schema.json @@ -1,5 +1,5 @@ { - "$id": "https://codegraph.dev/schemas/eof.record-1.1.0.schema.json", + "$id": "https://codegraph.dev/schemas/eof.record-1.2.0.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "description": "Trailer. The counts make truncation detectable: a reader that reaches end-of-input without this record, or whose tallies disagree with it, must reject the file.", "properties": { @@ -37,6 +37,6 @@ "t", "counts" ], - "title": "Codegraph model.jsonl \"eof\" record (interchange contract 1.1.0)", + "title": "Codegraph model.jsonl \"eof\" record (interchange contract 1.2.0)", "type": "object" } diff --git a/schemas/f.record.schema.json b/schemas/f.record.schema.json index 1d71ba6b..b11179b5 100644 --- a/schemas/f.record.schema.json +++ b/schemas/f.record.schema.json @@ -1,5 +1,5 @@ { - "$id": "https://codegraph.dev/schemas/f.record-1.1.0.schema.json", + "$id": "https://codegraph.dev/schemas/f.record-1.2.0.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "description": "One interned file path. `i` is its own index: dense, ascending from 0, gap-free. Anchors and `definedIn` reference these.", "properties": { @@ -22,6 +22,6 @@ "i", "path" ], - "title": "Codegraph model.jsonl \"f\" record (interchange contract 1.1.0)", + "title": "Codegraph model.jsonl \"f\" record (interchange contract 1.2.0)", "type": "object" } diff --git a/schemas/header.record.schema.json b/schemas/header.record.schema.json index 73e6e175..9e24f21b 100644 --- a/schemas/header.record.schema.json +++ b/schemas/header.record.schema.json @@ -1,5 +1,5 @@ { - "$id": "https://codegraph.dev/schemas/header.record-1.1.0.schema.json", + "$id": "https://codegraph.dev/schemas/header.record-1.2.0.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "description": "First line of the file. Carries the model's own facts and the dictionaries every other record indexes into. Exactly one per file.", "properties": { @@ -63,6 +63,7 @@ "TWithInvocations", "TStructural", "TWithAccesses", + "TWithReceiver", "TMetrics", "TWithValue" ], @@ -150,6 +151,6 @@ "root", "dict" ], - "title": "Codegraph model.jsonl \"header\" record (interchange contract 1.1.0)", + "title": "Codegraph model.jsonl \"header\" record (interchange contract 1.2.0)", "type": "object" } diff --git a/schemas/x.record.schema.json b/schemas/x.record.schema.json index 1ea6e96d..39fab310 100644 --- a/schemas/x.record.schema.json +++ b/schemas/x.record.schema.json @@ -186,7 +186,7 @@ "type": "object" } }, - "$id": "https://codegraph.dev/schemas/x.record-1.1.0.schema.json", + "$id": "https://codegraph.dev/schemas/x.record-1.2.0.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": {}, "description": "One edge, outgoing direction only. `f`/`o` are entity surrogates, `k` and `p` index the header's edge-kind and provenance dictionaries.", @@ -255,6 +255,13 @@ "minimum": 0, "type": "integer" }, + "receiver": { + "enum": [ + "self", + "other" + ], + "type": "string" + }, "sourceFile": { "maximum": 9007199254740991, "minimum": 0, @@ -273,6 +280,6 @@ "p", "anchor" ], - "title": "Codegraph model.jsonl \"x\" record (interchange contract 1.1.0)", + "title": "Codegraph model.jsonl \"x\" record (interchange contract 1.2.0)", "type": "object" } diff --git a/website/assets/diagrams/edges-metamodel.svg b/website/assets/diagrams/edges-metamodel.svg index 827615b3..98fad2b8 100644 --- a/website/assets/diagrams/edges-metamodel.svg +++ b/website/assets/diagrams/edges-metamodel.svg @@ -1,94 +1,94 @@ - + An edge connects two entities and is stored once, outgoing. Its 11 kinds, in 4 families by what they connect, each with its ends and the attributes it adds; its 4 provenance values, a dashed one an inference. - - + + Codegraph Metamodel Edges - -MODULARITY + +MODULARITY - + TYPES - + BEHAVIOR - -REFERENCES + +REFERENCES - + PROVENANCE - - - - - - - - - + + + + + + + + + -0..1 -1 -0..1 -0..1 -0..1 -from 1 -to 1 -1 -1 +0..1 +1 +0..1 +0..1 +0..1 +from 1 +to 1 +1 +1 - -Edge -edge: EdgeKind -from, to: EntityId -provenance: Provenance -anchor: SourceAnchor -candidates?: EntityId[] -sourceFile?: string + +Edge +edge: EdgeKind +from, to: EntityId +provenance: Provenance +anchor: SourceAnchor +candidates?: EntityId[] +sourceFile?: string - -Entity -from ≠ to, each known or a stub -stored once: outgoing only + +Entity +from ≠ to, each known or a stub +stored once: outgoing only - -Language Profile -licenses, per language, the edge -kinds its extractor emits + +Language Profile +licenses, per language, the edge +kinds its extractor emits - -SourceAnchor -file and span: where it is written + +SourceAnchor +file and span: where it is written - -import -Module → Module - + +import +Module → Module + - -fileInclude -CodeFile → CodeFile + +fileInclude +CodeFile → CodeFile @@ -118,28 +118,29 @@ member?: string, to a stub - -access -Invocable → Structural -isRead, isWrite: boolean -member?: string, to a stub + +access +Invocable → Structural +isRead, isWrite: boolean +receiver?: self | other +member?: string, to a stub - -throws -Invocable → exception type + +throws +Invocable → exception type - -reference -Entity → Type -member?: string, to a stub + +reference +Entity → Type +member?: string, to a stub - -annotationUse -Entity → annotation type -arguments: NamedArgument[] + +annotationUse +Entity → annotation type +arguments: NamedArgument[] @@ -164,16 +165,16 @@ - -import: the first-class layer, -comparable across languages + +import: the first-class layer, +comparable across languages - -fact: the source says so + +fact: the source says so - -inference: every rendering dashes it + +inference: every rendering dashes it - + diff --git a/website/assets/diagrams/traits-metamodel.svg b/website/assets/diagrams/traits-metamodel.svg index 6dae8018..2d8c47af 100644 --- a/website/assets/diagrams/traits-metamodel.svg +++ b/website/assets/diagrams/traits-metamodel.svg @@ -1,73 +1,73 @@ - -An entity composes traits. The 19 traits of the closed vocabulary, in 7 families, each with the attributes it contributes; a dashed box is a marker trait, which contributes none. + +An entity composes traits. The 20 traits of the closed vocabulary, in 7 families, each with the attributes it contributes; a dashed box is a marker trait, which contributes none. - - + + Codegraph Metamodel Traits - + BASE - + CONTAINMENT & ATTACHMENT - - + + STRUCTURE - -MODULARITY + +MODULARITY - -MEASURES + +MEASURES - -TYPES + +TYPES - -BEHAVIOR + +BEHAVIOR - - - - - - - - + + + + + + + + -0..3 -0..3 -0..3 -0..1 -0..1 -0..4 -0..4 -1 +0..3 +0..3 +0..4 +0..1 +0..1 +0..4 +0..4 +1 - -Entity -{ id, kind, traits[], …trait keys } + +Entity +{ id, kind, traits[], …trait keys } - -Language Profile -licenses, per kind, the traits an -entity must and may compose + +Language Profile +licenses, per kind, the traits an +entity must and may compose @@ -116,70 +116,76 @@ TWithValue value: Literal + + +TWithReceiver +needs an instance of its type + - -TModule -definedIn: string[] -isStub: boolean + +TModule +definedIn: string[] +isStub: boolean - -TMetrics -metrics: Record<string, number> -measured, never defaulted + +TMetrics +metrics: Record<string, number> +measured, never defaulted - -TType -isStub: boolean + +TType +isStub: boolean - -TWithInheritances -→ inheritance edges + +TWithInheritances +→ inheritance edges - -TWithImplements -→ interfaceImplementation edges + +TWithImplements +→ interfaceImplementation edges - -TTypedEntity -declaredType?: EntityId + +TTypedEntity +declaredType?: EntityId +typeExpr?: TypeExpr - -TInvocable -signature: string - + +TInvocable +signature: string + - -TWithParameters -parameters: EntityId[] + +TWithParameters +parameters: EntityId[] - -TWithLocalVariables -localVariables: EntityId[] + +TWithLocalVariables +localVariables: EntityId[] - -TWithInvocations -→ invocation edges + +TWithInvocations +→ invocation edges - -contributes attributes to the entity - -marker: contributes no attribute + +contributes attributes to the entity + +marker: contributes no attribute - -example, a Clojure fn-var: -TNamed + TStructural + TInvocable + +example, a Clojure fn-var: +TNamed + TStructural + TInvocable - + diff --git a/website/content/docs/how-to/query-model-db.md b/website/content/docs/how-to/query-model-db.md index bb1f3d3b..9d24499f 100644 --- a/website/content/docs/how-to/query-model-db.md +++ b/website/content/docs/how-to/query-model-db.md @@ -102,7 +102,8 @@ SELECT x.id AS ref, p.name AS provenance, f.path AS file, x.anchor_start AS line, - x.member AS member + x.member AS member, + x.receiver AS receiver FROM edge x JOIN edge_kind ek ON ek.id = x.kind_id JOIN provenance p ON p.id = x.provenance_id @@ -113,8 +114,8 @@ SELECT x.id AS ref, | Table | Holds | |---|---| -| `entity` | one row per entity: `kind_id`, `trait_set_id`, `module_id`, `symbol`, `disambiguator`, `parent_id`, `declared_type_id`, `is_stub`, the anchor | -| `edge` | one row per edge, in the direction the model states: `from_id`, `to_id`, `kind_id`, `provenance_id`, the anchor, and `member`: the member of a stub target the edge reaches, as written (`insert/2`, `save`), `NULL` when it names none | +| `entity` | one row per entity: `kind_id`, `trait_set_id`, `module_id`, `symbol`, `disambiguator`, `parent_id`, `declared_type_id`, `is_stub`, the anchor, and `type_expr`: the type as written, a JSON tree whose ids are surrogates (`NULL` when the extractor wrote none) | +| `edge` | one row per edge, in the direction the model states: `from_id`, `to_id`, `kind_id`, `provenance_id`, the anchor, `member`: the member of a stub target the edge reaches, as written (`insert/2`, `save`), `NULL` when it names none, and `receiver`: on an access, `self` or `other` (`NULL` when not stated) | | `kind`, `trait`, `edge_kind`, `provenance`, `file` | the interned vocabularies; ids are the header dictionary's own indices | | `trait_set`, `trait_set_member` | trait sets, interned — an entity points at a set, not at a list of traits | | `entity_metric` | one row per (entity, measure), the values the extractor measured | diff --git a/website/content/docs/reference/metamodel/edges.md b/website/content/docs/reference/metamodel/edges.md index 3da336bb..20a9035e 100644 --- a/website/content/docs/reference/metamodel/edges.md +++ b/website/content/docs/reference/metamodel/edges.md @@ -42,6 +42,14 @@ An `invocation`, `access` or `reference` edge whose `to` is a [stub](/docs/refer The navigator's dependency rows also say "member" — there it is the corpus entity a row reaches, a different thing. +## The receiver of an access + +An `access` edge may carry `receiver: "self" | "other"` (contract 1.2.0): `self` when the field is reached through the accessor's own receiver, written (`this.lines`) or implied (`lines`); `other` through any other expression (`other.lines`). Absent when the target has no receiver (a static field, a local) or when the extractor does not say. + +- It is legal on `access` only, and only when the target is **not** a stub: a stub has no members, so nothing says the field reached needs an instance. `codegraph validate` reports one that is (rule `receiver`). +- It is part of the edge: `this.lines = other.lines` is a `self` write and an `other` read at one site — two edges, ordered after `member`, absent first. +- In SQL it is `edge.receiver` and the `dep` view's `receiver` column. No extractor writes it yet; the Java extractor is next. + ## Edge kinds Four families, by what an edge connects. *Extra attributes* are the keys a kind adds to the ones every edge carries. @@ -67,7 +75,7 @@ Four families, by what an edge connects. *Extra attributes* are the keys a kind | Kind | From → To | Extra attributes | Notes | |---|---|---|---| | `invocation` | Invocable → Invocable | `candidates`, `member` (to a stub) | uncertain dispatch → `provenance: dynamic-candidate` + candidates list | -| `access` | Invocable → Structural | `isRead: bool`, `isWrite: bool`, `member` (to a stub) | field/variable reads and writes; a compound assignment sets both | +| `access` | Invocable → Structural | `isRead: bool`, `isWrite: bool`, `member` (to a stub), `receiver` (not to a stub) | field/variable reads and writes; a compound assignment sets both | | `throws` | Invocable → Type (exception) | | a written `throw` statement whose static exception type resolved; the anchor is the throw SITE. A declared propagation clause (Java `throws E`) is a plain `reference`, not this | ### References diff --git a/website/content/docs/reference/metamodel/traits.md b/website/content/docs/reference/metamodel/traits.md index b4c12ff0..d9265ebc 100644 --- a/website/content/docs/reference/metamodel/traits.md +++ b/website/content/docs/reference/metamodel/traits.md @@ -46,7 +46,24 @@ A Go method with receiver `(o *Order)` is a *child* of its file/package and *att | `TType` | `isStub: boolean` | any type-like entity: class, interface, struct, enum, protocol, PHP/Rust trait | | `TWithInheritances` | *(marker)* — see `inheritance` edges | multiple inheritance = N edges (Python). Absent from the Go and Rust profiles — that absence is profile information, not a gap | | `TWithImplements` | *(marker)* — see `interfaceImplementation` edges | | -| `TTypedEntity` | `declaredType?: EntityId` | optional even when the trait is present: absent value in JS/Python/Clojure, C# `var`, inferred Go/TS/Rust | +| `TTypedEntity` | `declaredType?: EntityId`, `typeExpr?: TypeExpr` | both optional even when the trait is present: absent value in JS/Python/Clojure, C# `var`, inferred Go/TS/Rust. `declaredType` is the erased head; `typeExpr` (contract 1.2.0) the type as written — see [Type expressions](#type-expressions) | + +### Type expressions + +`typeExpr` is the type a declaration **writes**, as a tree: `List` is a `named` type with one argument, `int[]` an `array` of a `primitive`, `T?` a `nullable`. Eight forms, a closed vocabulary: + +| Form | Shape | Notes | +|---|---|---| +| `named` | `{k: "named", type: EntityId, args?: TypeExpr[]}` | a declared type or a stub, with its written type arguments in order; `args` absent when none is written | +| `primitive` | `{k: "primitive", name: string}` | the language's own word: `int`, `long`, `boolean` | +| `array` | `{k: "array", of: TypeExpr}` | | +| `nullable` | `{k: "nullable", of: TypeExpr}` | only where the language writes it (`T?`, `T \| null`) | +| `function` | `{k: "function", params: TypeExpr[], returns?: TypeExpr}` | `returns` absent = no value | +| `union` | `{k: "union", of: TypeExpr[]}` | at least two, in written order | +| `variable` | `{k: "variable", name: string}` | a type parameter | +| `unevaluated` | `{k: "unevaluated", source: string}` | a written type the extractor did not structure (a wildcard); the text is still a fact | + +It is what is written, never what is inferred: no `typeExpr` on a `var` or a `void` return. The ids inside count for closure, exactly like an edge's ends, and the `reference` edges a written type emits are still emitted. No extractor writes it yet; the Java extractor is next. ## Behavior @@ -64,6 +81,9 @@ A Go method with receiver `(o *Order)` is a *child* of its file/package and *att | `TStructural` | *(marker)* — value holder | attributes, variables, parameters, Clojure vars. Legal target of `access` edges | | `TWithAccesses` | *(marker)* — see `access` edges | outgoing only | | `TWithValue` | `value: Literal` | the entity's declaration-site constant value. Optional wherever licensed — absence means "not constant", never "empty" | +| `TWithReceiver` | *(marker)* | evaluated against an instance of the type it is written in or attached to: an instance field, an instance method, a constructor (contract 1.2.0) | + +`TWithReceiver` tells `Order.channel` from `Order.MAX_LINES`, which Java's `attribute` kind does not. A profile licenses it, optional, on the kinds it can decide it for — Java: `attribute`, `method`, `constructor`. Where it is licensed, absence means "no receiver" (a static member, an enum constant); where it is not, absence means nothing. An `access` edge's [`receiver`](/docs/reference/metamodel/edges/#the-receiver-of-an-access) is its counterpart on the edge. ## Measures @@ -79,8 +99,8 @@ A Clojure var holding a function is simultaneously named, a value holder, and in ## The closed vocabulary -Nineteen names, in the order the header dictionary's enum declares them: +Twenty names, in the order the header dictionary's enum declares them: -`TNamed` · `TSourceAnchor` · `TComment` · `TWithChildren` · `TChildOf` · `TAttachedTo` · `TModule` · `TType` · `TWithInheritances` · `TWithImplements` · `TTypedEntity` · `TInvocable` · `TWithParameters` · `TWithLocalVariables` · `TWithInvocations` · `TStructural` · `TWithAccesses` · `TMetrics` · `TWithValue` +`TNamed` · `TSourceAnchor` · `TComment` · `TWithChildren` · `TChildOf` · `TAttachedTo` · `TModule` · `TType` · `TWithInheritances` · `TWithImplements` · `TTypedEntity` · `TInvocable` · `TWithParameters` · `TWithLocalVariables` · `TWithInvocations` · `TStructural` · `TWithAccesses` · `TWithReceiver` · `TMetrics` · `TWithValue` The keys each contributes on the wire are listed under [`model.jsonl`](/docs/reference/model-jsonl/#e). diff --git a/website/content/docs/reference/model-jsonl.md b/website/content/docs/reference/model-jsonl.md index db64268d..c08d3ee3 100644 --- a/website/content/docs/reference/model-jsonl.md +++ b/website/content/docs/reference/model-jsonl.md @@ -4,7 +4,7 @@ linkTitle: model.jsonl weight: 2 --- -The interchange format: one model, one JSONL file. Contract version **1.1.0** (1.1.0 added the edge `member`; a 1.0.0 file still reads, and each extractor states the version it writes). The canonical source is [`schemas/`](https://github.com/defsquare/codegraph/tree/main/schemas) in the repository — one JSON Schema per record type plus the prose container contract; those files are generated from `@codegraph/core` by `pnpm run gen:schemas`. +The interchange format: one model, one JSONL file. Contract version **1.2.0** (1.1.0 added the edge `member`; 1.2.0 the entity's `typeExpr`, the marker `TWithReceiver` and the access `receiver`; an older file still reads, and each extractor states the version it writes). The canonical source is [`schemas/`](https://github.com/defsquare/codegraph/tree/main/schemas) in the repository — one JSON Schema per record type plus the prose container contract; those files are generated from `@codegraph/core` by `pnpm run gen:schemas`. A model is one **JSONL** file: one JSON object per line, UTF-8, LF-terminated, with the record type in the leading `t` key. Every line validates against the per-record JSON Schema of its type. @@ -62,6 +62,8 @@ Every reference to an entity is its surrogate — the integer `i` of its record. | `f`, `o` | every edge record | surrogate | | `candidates` | edge record | array of surrogates | +Two keys hold a tree rather than a reference, and every id inside the tree is a surrogate by the same rule: `value` (a [Literal](#literal-and-namedargument)) with an edge's `arguments`, and `typeExpr` (a [TypeExpr](#typeexpr)). Closure reaches inside both. + Surrogates are **file-scoped and not identity**: they are assigned by canonical order, so they change whenever the model changes, and they must never be stored outside the file that assigned them or compared across files. Joining two models is done on natural keys. Paths are interned the same way: `anchor` is `[fileRef, startLine, endLine]`, `definedIn` is an array of file references, and an edge's `sourceFile` is one. Line numbers are 1-based and `startLine ≤ endLine`. @@ -133,13 +135,14 @@ Required: `t`, `i`, `k`, `tr`, `m`, `s`. | `definedIn` | surrogate[] | `TModule` | file references | | `isStub` | boolean | `TModule`, `TType` | | | `declaredType` | surrogate | `TTypedEntity` | optional even when the trait is declared | +| `typeExpr` | `TypeExpr` | `TTypedEntity` | since 1.2.0, optional; the type as written, see below | | `signature` | string | `TInvocable` | | | `parameters` | surrogate[] | `TWithParameters` | ordered | | `localVariables` | surrogate[] | `TWithLocalVariables` | | | `metrics` | `Record` | `TMetrics` | non-empty keys, finite numbers | | `value` | `Literal` | `TWithValue` | see below | -`TWithChildren`, `TWithInheritances`, `TWithImplements`, `TWithInvocations`, `TStructural` and `TWithAccesses` are markers: they contribute no key. +`TWithChildren`, `TWithInheritances`, `TWithImplements`, `TWithInvocations`, `TStructural`, `TWithAccesses` and `TWithReceiver` are markers: they contribute no key. ### `x` @@ -159,6 +162,7 @@ Required: `t`, `k`, `f`, `o`, `p`, `anchor`. | `candidates` | surrogate[] | possible targets when dispatch is uncertain | | `isRead` | boolean | `access` edges | | `isWrite` | boolean | `access` edges | +| `receiver` | `"self"` \| `"other"` | since 1.2.0: `access` edges to an entity that is not a stub — reached through the accessor's own receiver, or through another expression | | `arguments` | `NamedArgument[]` | `annotationUse` edges | | `sourceFile` | surrogate | which declaration site produced the edge | @@ -186,9 +190,26 @@ Required: `t`, `counts`. `counts` requires `files`, `entities` and `edges`, all `$defs/NamedArgument` is `{name: string, value: Literal}`; a language-implicit name is normalized explicit. +## TypeExpr + +`$defs/TypeExpr` (since 1.2.0) is a tagged union on `k`, the type a declaration writes; ids inside it are surrogates, exactly like an edge endpoint. Inside a tree the keys are written `k` first, then the form's own in the order below; nothing in it is sorted. + +| `k` | Other fields | Notes | +|---|---|---| +| `named` | `type: surrogate`, `args?: TypeExpr[]` | `args` non-empty when present | +| `primitive` | `name: string` | `int`, `long`, `boolean` | +| `array` | `of: TypeExpr` | | +| `nullable` | `of: TypeExpr` | only where the language writes it | +| `function` | `params: TypeExpr[]`, `returns?: TypeExpr` | `returns` absent = no value | +| `union` | `of: TypeExpr[]` | at least two | +| `variable` | `name: string` | a type parameter | +| `unevaluated` | `source: string` | a written type the extractor did not structure | + +`List` on a field whose `List` is entity 5 and `OrderLine` entity 3: `"typeExpr":{"k":"named","type":5,"args":[{"k":"named","type":3}]}`. + ## Trait keys -An entity record carries **exactly** the keys its declared traits contribute: present when the trait is declared, absent when it is not. Optional-valued keys (`declaredType`) may be absent even when their trait is declared. This is the one rule the per-record schemas cannot state, because deciding it means resolving `tr` through the header. A key no trait contributes is passed through untouched, so an extractor may annotate its output without breaking conformance. +An entity record carries **exactly** the keys its declared traits contribute: present when the trait is declared, absent when it is not. Optional-valued keys (`declaredType`, `typeExpr`) may be absent even when their trait is declared. This is the one rule the per-record schemas cannot state, because deciding it means resolving `tr` through the header. A key no trait contributes is passed through untouched, so an extractor may annotate its output without breaking conformance. ## Integrity @@ -198,11 +219,12 @@ A conforming file satisfies all of: - **No self-reference** — `f ≠ o` on every edge. - **Provenance and anchor on every edge** — a dependency claim with no evidence, or of unknown fact/inference status, is not representable. - **A member only where a stub has none** — `member` is legal only on an `invocation`, `access` or `reference` edge whose `o` is a stub. A member of a corpus entity is an entity, and the edge points at it. The member is a string, never a reference: no entity is made for it. +- **A receiver only where a member needs an instance** — `receiver` is legal only on an `access` edge whose `o` is **not** a stub: a stub has no members. - **Counts** — `eof.counts` states how many `f`, `e` and `x` records were written. ## Canonical order and determinism -Entities are sorted by natural key — `lang`, then `module`, then `symbol`, then `disambiguator` with the absent one first — comparing by UTF-16 code unit. That order **is** the surrogate assignment. Edges follow, sorted by `f`, then `o`, then edge kind, then anchor (file, start, end), then provenance, then `member` with the absent one first. Within an edge record the keys are written `t`, `k`, `f`, `o`, `p`, then `member`, `candidates`, `arguments`, `isRead`, `isWrite`, `sourceFile`, `anchor`, each optional key only when present. File records are sorted by path; dictionary entries are sorted. +Entities are sorted by natural key — `lang`, then `module`, then `symbol`, then `disambiguator` with the absent one first — comparing by UTF-16 code unit. That order **is** the surrogate assignment. Edges follow, sorted by `f`, then `o`, then edge kind, then anchor (file, start, end), then provenance, then `member`, then `receiver`, each of the last two with the absent one first. Within an edge record the keys are written `t`, `k`, `f`, `o`, `p`, then `member`, `candidates`, `arguments`, `isRead`, `isWrite`, `receiver`, `sourceFile`, `anchor`, each optional key only when present. File records are sorted by path; dictionary entries are sorted. Consequence: two runs of one extractor over one unchanged corpus produce byte-identical files. diff --git a/website/content/docs/reference/profiles.md b/website/content/docs/reference/profiles.md index 7af835a8..02423799 100644 --- a/website/content/docs/reference/profiles.md +++ b/website/content/docs/reference/profiles.md @@ -21,17 +21,17 @@ A profile licenses an entity by the rule `required(kind) ⊆ traits ⊆ required | `lang` | Language | Kinds | Edge kinds | Notes | |---|---|---|---|---| -| `clj` | Clojure | 10 | 5 | 13 | -| `csharp` | C# | 15 | 8 | 22 | -| `ex` | Elixir | 9 | 6 | 22 | -| `go` | Go | 10 | 6 | 9 | -| `java` | Java | 12 | 8 | 20 | -| `js` | JavaScript | 8 | 5 | 13 | -| `php` | PHP | 12 | 8 | 10 | -| `python` | Python | 7 | 8 | 21 | -| `rb` | Ruby | 7 | 7 | 28 | -| `rust` | Rust | 13 | 5 | 12 | -| `ts` | TypeScript | 14 | 8 | 29 | +| `clj` | Clojure | 10 | 5 | 14 | +| `csharp` | C# | 15 | 8 | 23 | +| `ex` | Elixir | 9 | 6 | 23 | +| `go` | Go | 10 | 6 | 10 | +| `java` | Java | 12 | 8 | 21 | +| `js` | JavaScript | 8 | 5 | 14 | +| `php` | PHP | 12 | 8 | 11 | +| `python` | Python | 7 | 8 | 22 | +| `rb` | Ruby | 7 | 7 | 29 | +| `rust` | Rust | 13 | 5 | 13 | +| `ts` | TypeScript | 14 | 8 | 30 | A profile that is specified but has no shipped extractor is complete, not deficient: the profile is the contract an extractor is written against. Today `java`, `csharp`, `ts`, `ex`, `rb` and `python` have one: see the [Java](/docs/reference/java-extractor/), [C#](/docs/reference/csharp-extractor/), [TypeScript](/docs/reference/typescript-extractor/), [Elixir](/docs/reference/elixir-extractor/), [Ruby](/docs/reference/ruby-extractor/) and [Python](/docs/reference/python-extractor/) extractor pages. Every shipped extractor's model can then be measured by the [metrics pass](/docs/reference/metrics-pass/). @@ -74,6 +74,7 @@ A profile that is specified but has no shipped extractor is complete, not defici - Higher-order use of vars (`(map inc coll)`, `(partial f x)`) yields `reference` edges to the var, never `invocation` edges — the call happens elsewhere and its site is unknown. - Runtime resolution (`resolve`, `requiring-resolve`, `eval`, `(var-get (ns-resolve ...))`) and dynamically computed `require` are static blind spots: no `import` or `invocation` edge is emitted for them. - `:refer :all` and `:refer` bring vars into scope without qualification; the `import` edge is namespace -> namespace, so the module layer stays exact even when a symbol's origin needs var resolution. +- MM-7 and MM-8 (contract 1.2.0) are not emitted by any extractor of this language (none ships) yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not "no written type", not "no receiver" (PLAN.md §26.10). ## C# — `csharp` @@ -131,6 +132,7 @@ A profile that is specified but has no shipped extractor is complete, not defici - Neither a `.sln` nor a `.csproj` is read: the extractor parses every `*.cs` under the source roots into ONE compilation (no MSBuild, no restore), so a legacy tree with no restorable project graph still extracts, and a missing package is a stub rather than a build failure. Consequences: one preprocessor configuration is parsed (no `--define` yet); source-generated and XAML/Razor code-behind partials are absent unless their output is under the roots; a name declared twice across projects that never see each other collides as one entity. - The metrics pass (`codegraph-metrics`, PLAN.md §18): a property with accessors is joined to its accessor spaces — `{ get; set; }` is two, so it carries the pass's charged keys only (cognitive, exits, ABC). An implicit constructor (anchored on the type's name) and a record's positional members have no space and carry none of its keys. tree-sitter-c-sharp 0.23.5 misparses a C# 14 extension block: its members go unmeasured by the pass, and the enclosing class is joined by containment (charged keys only). tree-sitter does not evaluate `#if`: in a file with conditional blocks big-code-analysis measures EVERY branch, where Roslyn — and so this extractor's `sloc` — keeps the active one; on Humanizer such files are the 37 exact joins whose `sloc` and big-code-analysis's `ploc` disagree. - MM-6 (an edge's `member`, contract 1.1.0): an edge to a stub names the member the site wrote, by its SIMPLE name as written — no parameter types, no type arguments (`Select(…)` → `Select`). A method call on a stub type is an `invocation` naming the method (`builder.Append(x)` → `Append`); so is a static call, with or without its type (`Console.WriteLine(x)` → `WriteLine`, `Round(v)` under `using static System.Math` → `Round`), and so is an extension method call, on the static class that declares it (`xs.Select(…)` → `Select` on `System.Linq/Enumerable`); `d.Invoke(x)` on a delegate names `Invoke`. A field, property or event read or written is an `access` naming it (`DateTime.Today` → `Today`, `b.Length = 0` → `Length`, `AppDomain.CurrentDomain.ProcessExit += h` → `ProcessExit`); a method group used as a value is a `reference` naming the method (`Action w = Console.WriteLine` → `WriteLine`). A receiver Roslyn cannot bind is a `reference` to its stub in `` naming the ONE name written right after it (`JsonConvert.SerializeObject(x)` → `SerializeObject`, `JsonConvert.Settings` → `Settings`, `JsonConvert.Deserialize(s)` → `Deserialize`); a longer chain names only that first name (`A.B.C()` with `A` unbound → `B`), and nothing is invented for what follows. An unbound name carries no symbol, so the extractor cannot tell a type from a namespace prefix or a member inherited from an unresolved base: it names the member on every unbound-receiver reference it already emits. A call in a field initializer is an invocation from the field and names its method alike. Named nowhere: a constructor call (`new T()`, `new()`, `base(…)`, `this(…)` — the edge to the type says all the site wrote), a delegate call (`first()` writes no member of `Action`), an indexer (`xs[0]` writes no name; the access and its read/write flags are the fact), a user-defined operator (`a - b` on `DateTime`), `typeof`, `nameof`, an attribute use, a written type use (an unbound one included: `Unbound x`, `new Unbound()`, `typeof(Unbound)`, `List`), and every edge to a corpus entity — its member is an entity, and the edge points at it; a call to a member Roslyn synthesizes on a corpus record folds to the record and names none. The member is part of the edge (EdgeExtractor's `seen` key): `values.Count == 0 ? null : values[0]` is two accesses of `List` (`Count`, and the indexer naming none) where it was one, `amounts.Select(…).DefaultIfEmpty(0L).Max()` three invocations of `Enumerable`; a read and a write of one member at one site stay two accesses, one per flag pair, as before. Measured on the reference corpus: 17 of 119 edges to stubs named, 292 edges become 295. +- MM-7 and MM-8 (contract 1.2.0) are not emitted by this language's extractor yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not "no written type", not "no receiver" (PLAN.md §26.10). ## Elixir — `ex` @@ -182,6 +184,7 @@ A profile that is specified but has no shipped extractor is complete, not defici - Measures ([TMetrics](/docs/reference/metamodel/traits/#measures), METAMODEL.md §3.8): `sloc` on the file, every module and every invocable — lines of its own span that are neither blank nor comment-only, a comment being what the compiler's own parser reports as one: every non-blank line a heredoc, a sigil or a multi-line string spans is code, a `#` inside one included; `cyclomatic` on invocables: 1 + clause heads beyond the first + `case`/`cond`/`with`/`receive`/`try` clauses beyond the first + `if`/`unless` + `and`/`or`/`&&`/`||` + `rescue`/`catch` clauses. A nested `fn` contributes to its enclosing invocable: an anonymous function is not an entity. - The metrics pass (`codegraph-metrics`, PLAN.md §18): big-code-analysis opens one space per `def` clause, so a function of several clauses is joined by containment and carries the charged keys only (cognitive, exits, ABC) — no `lloc`, Halstead or `mi`, which do not add up over clauses. `defprotocol` and `defimpl` bodies, `defguard` and `defdelegate` have no space and carry none of the pass's keys. The join's witness (`sloc` = big-code-analysis's `ploc`) cannot hold over a heredoc: big-code-analysis leaves a heredoc's text lines out of `ploc`, which METAMODEL's `sloc` counts (Phoenix's `mix_app_path`: `sloc` 19, `ploc` 13). - MM-6 (an edge's `member`, contract 1.1.0, header `schemaVersion` 1.1.0): an `invocation`, `access` or `reference` to a stub names the member its site writes, as `name/arity` with the arity the site really has — arity is identity on the BEAM. A remote call `M.f(a, b)`, a macro `Logger.info(msg)` and an Erlang call `:ets.lookup(t, k)` name `f/2`, `info/1`, `lookup/2`; a pipe counts its left side (`x |> Enum.map(f)` is `map/2`); a capture `&M.f/2` or `&M.f(&1, x)` is a `reference` naming `f/2`; a local call an `import` of the stub provides (`config :app, k: v` under `import Config`) names `config/2`; `use M` is the invocation of `__using__/1`; `defdelegate f(a), to: M, as: :g` names `g/1`; a remote type in a typespec (`String.t()`) is a `reference` naming `t/0`; a `--trace` edge names its call the same way. A field of a stub struct — `%Ecto.Changeset{valid?: v}` in a pattern, `%M{s | k: v}` in an update, `%M{k: v}` in a construction — is one `access` to the stub module per field written, naming the field as written, with no arity (`valid?`): `isRead` in a pattern, `isWrite` otherwise, as for a corpus struct. So `:ets.lookup` and `:ets.insert` on one table are two edges, a read and a write told apart. No member: a module written as a value (`{Registry, keys: :unique}`, `children = [Mod]`), an `import` edge, a `throws` or `interfaceImplementation` edge, and every edge to a corpus entity, which already points at the member. `codegraph validate` on the fixture prints `members named: 37 of 42 edges to stubs` — the 5 are 3 modules written as values and 2 `%Ecto.Changeset{…}` struct references, whose fields are the named accesses. +- MM-7 and MM-8 (contract 1.2.0) are not emitted by this language's extractor yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not "no written type", not "no receiver" (PLAN.md §26.10). ## Go — `go` @@ -217,6 +220,7 @@ A profile that is specified but has no shipped extractor is complete, not defici - Calls through an interface value cannot be resolved statically: they are emitted against the interface method with provenance "dynamic-candidate" and the satisfying implementations as candidates. - Invisible to static extraction: reflect, the plugin package, cgo, go:generate and go:linkname directives, and side effects of init() functions pulled in by blank imports (`import _ "…"`), which are still emitted as ordinary import edges. - Build tags and GOOS/GOARCH constrained files mean a single extraction run sees one build configuration; entities excluded by the active tags are absent from the model. +- MM-7 and MM-8 (contract 1.2.0) are not emitted by any extractor of this language (none ships) yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not "no written type", not "no receiver" (PLAN.md §26.10). ## Java — `java` @@ -227,14 +231,14 @@ A profile that is specified but has no shipped extractor is complete, not defici | Kind | Required traits | Optional traits | |---|---|---| | `annotation` | [`TNamed`](/docs/reference/metamodel/traits/#base), [`TType`](/docs/reference/metamodel/traits/#types), [`TWithChildren`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | [`TComment`](/docs/reference/metamodel/traits/#base), [`TMetrics`](/docs/reference/metamodel/traits/#measures) | -| `attribute` | [`TNamed`](/docs/reference/metamodel/traits/#base), [`TStructural`](/docs/reference/metamodel/traits/#structure), [`TTypedEntity`](/docs/reference/metamodel/traits/#types), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | [`TComment`](/docs/reference/metamodel/traits/#base), [`TWithValue`](/docs/reference/metamodel/traits/#structure) | +| `attribute` | [`TNamed`](/docs/reference/metamodel/traits/#base), [`TStructural`](/docs/reference/metamodel/traits/#structure), [`TTypedEntity`](/docs/reference/metamodel/traits/#types), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | [`TComment`](/docs/reference/metamodel/traits/#base), [`TWithValue`](/docs/reference/metamodel/traits/#structure), [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) | | `class` | [`TNamed`](/docs/reference/metamodel/traits/#base), [`TType`](/docs/reference/metamodel/traits/#types), [`TWithInheritances`](/docs/reference/metamodel/traits/#types), [`TWithImplements`](/docs/reference/metamodel/traits/#types), [`TWithChildren`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | [`TComment`](/docs/reference/metamodel/traits/#base), [`TMetrics`](/docs/reference/metamodel/traits/#measures) | -| `constructor` | [`TInvocable`](/docs/reference/metamodel/traits/#behavior), [`TWithChildren`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TWithParameters`](/docs/reference/metamodel/traits/#behavior), [`TWithLocalVariables`](/docs/reference/metamodel/traits/#behavior), [`TWithInvocations`](/docs/reference/metamodel/traits/#behavior), [`TWithAccesses`](/docs/reference/metamodel/traits/#structure), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | [`TComment`](/docs/reference/metamodel/traits/#base), [`TMetrics`](/docs/reference/metamodel/traits/#measures) | +| `constructor` | [`TInvocable`](/docs/reference/metamodel/traits/#behavior), [`TWithChildren`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TWithParameters`](/docs/reference/metamodel/traits/#behavior), [`TWithLocalVariables`](/docs/reference/metamodel/traits/#behavior), [`TWithInvocations`](/docs/reference/metamodel/traits/#behavior), [`TWithAccesses`](/docs/reference/metamodel/traits/#structure), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | [`TComment`](/docs/reference/metamodel/traits/#base), [`TMetrics`](/docs/reference/metamodel/traits/#measures), [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) | | `enum` | [`TNamed`](/docs/reference/metamodel/traits/#base), [`TType`](/docs/reference/metamodel/traits/#types), [`TWithImplements`](/docs/reference/metamodel/traits/#types), [`TWithChildren`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | [`TComment`](/docs/reference/metamodel/traits/#base), [`TMetrics`](/docs/reference/metamodel/traits/#measures) | | `interface` | [`TNamed`](/docs/reference/metamodel/traits/#base), [`TType`](/docs/reference/metamodel/traits/#types), [`TWithInheritances`](/docs/reference/metamodel/traits/#types), [`TWithChildren`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | [`TComment`](/docs/reference/metamodel/traits/#base), [`TMetrics`](/docs/reference/metamodel/traits/#measures) | | `lambda` | [`TInvocable`](/docs/reference/metamodel/traits/#behavior), [`TWithChildren`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TWithParameters`](/docs/reference/metamodel/traits/#behavior), [`TWithLocalVariables`](/docs/reference/metamodel/traits/#behavior), [`TWithInvocations`](/docs/reference/metamodel/traits/#behavior), [`TWithAccesses`](/docs/reference/metamodel/traits/#structure), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | [`TTypedEntity`](/docs/reference/metamodel/traits/#types), [`TMetrics`](/docs/reference/metamodel/traits/#measures) | | `localVariable` | [`TNamed`](/docs/reference/metamodel/traits/#base), [`TStructural`](/docs/reference/metamodel/traits/#structure), [`TTypedEntity`](/docs/reference/metamodel/traits/#types), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment) | [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | -| `method` | [`TNamed`](/docs/reference/metamodel/traits/#base), [`TInvocable`](/docs/reference/metamodel/traits/#behavior), [`TWithChildren`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TWithParameters`](/docs/reference/metamodel/traits/#behavior), [`TWithLocalVariables`](/docs/reference/metamodel/traits/#behavior), [`TWithInvocations`](/docs/reference/metamodel/traits/#behavior), [`TWithAccesses`](/docs/reference/metamodel/traits/#structure), [`TTypedEntity`](/docs/reference/metamodel/traits/#types), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | [`TComment`](/docs/reference/metamodel/traits/#base), [`TMetrics`](/docs/reference/metamodel/traits/#measures), [`TWithValue`](/docs/reference/metamodel/traits/#structure) | +| `method` | [`TNamed`](/docs/reference/metamodel/traits/#base), [`TInvocable`](/docs/reference/metamodel/traits/#behavior), [`TWithChildren`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TWithParameters`](/docs/reference/metamodel/traits/#behavior), [`TWithLocalVariables`](/docs/reference/metamodel/traits/#behavior), [`TWithInvocations`](/docs/reference/metamodel/traits/#behavior), [`TWithAccesses`](/docs/reference/metamodel/traits/#structure), [`TTypedEntity`](/docs/reference/metamodel/traits/#types), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | [`TComment`](/docs/reference/metamodel/traits/#base), [`TMetrics`](/docs/reference/metamodel/traits/#measures), [`TWithValue`](/docs/reference/metamodel/traits/#structure), [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) | | `package` | [`TNamed`](/docs/reference/metamodel/traits/#base), [`TModule`](/docs/reference/metamodel/traits/#modularity), [`TWithChildren`](/docs/reference/metamodel/traits/#containment-and-attachment) | [`TComment`](/docs/reference/metamodel/traits/#base), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment) | | `parameter` | [`TNamed`](/docs/reference/metamodel/traits/#base), [`TStructural`](/docs/reference/metamodel/traits/#structure), [`TTypedEntity`](/docs/reference/metamodel/traits/#types), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment) | [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | | `record` | [`TNamed`](/docs/reference/metamodel/traits/#base), [`TType`](/docs/reference/metamodel/traits/#types), [`TWithImplements`](/docs/reference/metamodel/traits/#types), [`TWithChildren`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TChildOf`](/docs/reference/metamodel/traits/#containment-and-attachment), [`TSourceAnchor`](/docs/reference/metamodel/traits/#base) | [`TComment`](/docs/reference/metamodel/traits/#base), [`TMetrics`](/docs/reference/metamodel/traits/#measures) | @@ -257,7 +261,7 @@ A profile that is specified but has no shipped extractor is complete, not defici - A `throws` edge is emitted per written `throw` statement whose static exception type resolves, anchored at the throw site — the evidence a guard clause (`if (x) throw new E(...)`) leaves in the model. A method's `throws` CLAUSE stays a plain reference edge: it declares propagation, not a failure exit of this body. A rethrow (`throw e;`) targets the caught variable's static type; a throw whose type Spoon cannot name is dropped and counted, like any unidentifiable target. - Static and on-demand (`import x.y.*`) imports are folded to module-level import edges; the wildcard case names the package, not the individual types it brings in. - Overloads are distinguished by the id's signature disambiguator, so an unresolved parameter type changes the id — a resolution failure shows up as a stub target, never as a merged entity. -- Java generics are erased in the model: type arguments are emitted as reference edges from the declaring entity, and declaredType carries the raw type. +- Java generics are erased in an id and in `declaredType`, which carries the raw type; type arguments are still emitted as reference edges from the declaring entity. What the source WROTE is `typeExpr` (MM-7, contract 1.2.0), on every field, parameter, local variable, method return, record component and explicitly typed lambda parameter: `List` a `named` List with its argument, `int` a `primitive`, `int[]` an `array` of one (a varargs parameter too, nested for `int[][]`), a type parameter `T` a `variable`. A wildcard (`? extends Order`, `?`), an intersection, an outer type's arguments (`Outer.Inner`) and a type Spoon cannot name are `unevaluated`, with their source text (whitespace folded). None on what is not written: `var`, an implicitly typed lambda parameter, a `void` return, a constructor; a record's implicit members carry their component's written type. A `named` target is the same id `declaredType` and the edges use; one that no entity declares — not even a stub, since the type expression never makes one — is kept as `unevaluated` text, never as a fabricated id. Java writes no `nullable` (an annotation is not inferred into one), no `function` and no `union`. - noClasspath resolution rate, measured (M2 audit): 100.0% on apache/commons-lang (263 files, 133478 type references, 0 unresolved) and 77.8% on spring-petclinic (30 files, 2189 references, 487 unresolved, all of them Spring and Jakarta types whose jars are absent). The rate is a property of the corpus's DEPENDENCY SURFACE, not of the extractor: commons-lang is self-contained and depends on nothing but the JDK, which resolves against the runner's own classpath. A jar that is not on the classpath cannot be resolved by any extractor, so a corpus with third-party dependencies has a structural ceiling well below 100% and a single cross-corpus target number is not meaningful. The stub discipline, not the resolution rate, is the property worth asserting. - The resolution rate counts neither type variables nor ``: neither names anything that could have a declaration, so counting them measures the corpus's writing style. This is not cosmetic — ``, Spoon's static type for the `null` literal, was ALL 1466 of commons-lang's originally-reported unresolved references, making the headline number a function of how many `return null;` statements the corpus contains. - In noClasspath Spoon promotes an unresolvable RECEIVER to a type in the enclosing package: `typeHint -> typeHint.with(...)` and `cm.setStatisticsEnabled(...)` produced stub classes named `typeHint` and `cm` inside the corpus's own package on spring-petclinic. They are correctly stubbed (membership is the declared-id whitelist), and they are why the whitelist exists — but the stub set of a real corpus therefore contains a tail of entities named after local variables, and a stub count is not a count of external types. @@ -268,6 +272,7 @@ A profile that is specified but has no shipped extractor is complete, not defici - Spoon materializes the implicit constructor of an anonymous class with synthetic parameters named `$anonymousN`. They are emitted (implicit members are, deliberately, so that `new Foo()` does not dangle), so the model contains a handful of parameter entities nobody wrote, carrying no anchor of their own — 5 of 15338 entities on commons-lang. - The metrics pass (`codegraph-metrics`, PLAN.md §18) joins big-code-analysis spaces to entities on their anchors. Spoon starts a declaration AFTER its annotations and tree-sitter AT them; the pass bridges the two when nothing but annotation lines lies between (a LEADING join — most of a Spring corpus). It measures nothing on a lambda (big-code-analysis opens no space for one and charges its cognitive, exits and ABC to the enclosing method), on an implicit constructor (anchored on its class) or on an annotation element (no body): those carry none of the pass's keys. - MM-6 (an edge's `member`, contract 1.1.0): an edge to a stub names the member the site wrote, by its SIMPLE name — no parameter types, since an external method's erased types need a classpath and the extractor runs noClasspath. A method call on a stub type is an `invocation` naming the method (`lines.add(x)` → `add`, a static call through a static import included: `asList`); a method reference `Integer::parseInt` names `parseInt`; a field read or written is an `access` naming the field (`System.out` → `out`), and a read and a write of one field at one site stay one access with both flags; written outside every invocable (a field initializer, an annotation argument) the call or the field read degrades to a `reference` that keeps the name (`Logger.getLogger(…)` → `getLogger`, `@Retention(RetentionPolicy.RUNTIME)` → `RUNTIME`). Named nowhere: a constructor call or reference (`new ArrayList<>()`, `super(…)`, `ArrayList::new` — the edge to the type says all the site wrote), a class literal (`Foo.class` is no member of Foo), a written type use, a supertype clause, and every edge to a corpus entity — its member is an entity, and the edge points at it. The member is part of the edge: `values.isEmpty() ? null : values.get(0)` is two invocations of `List`, where it was one. Measured on spring-petclinic: 723 of 1 164 edges to stubs named, 2 800 edges become 2 847 (42 sites split). A call to a member a corpus type INHERITS from a library one (`owners.save(owner)` on a Spring Data `JpaRepository`) has no declaring type in noClasspath; where the ancestor rule (the `ancestor-attributed` note) charges it to the one library ancestor, the edge names the member like any other (`save`, `saveAndFlush`): the five repository writes of spring-petclinic. +- MM-7 and MM-8 (contract 1.2.0, emitted since M25b): the profile licenses [`TWithReceiver`](/docs/reference/metamodel/traits/#structure), optional, on `attribute`, `method` and `constructor`. It is carried by an instance field (a record component included), an instance method (abstract and default interface methods included, and an annotation element: it is read on an annotation instance, `audited.value()`) and every constructor; not by a static field or method, an enum constant, an interface or annotation-type field (implicitly static), a lambda or anonymous class, a parameter or a local variable. On those three kinds the absence of [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) means "no receiver", in a model whose header states contract 1.2.0 or later; a model written before carries the marker nowhere, and there its absence says nothing. An `access` to a corpus field with a receiver states `receiver`: `self` when reached through the accessor's own `this` — written, implied (`lines`), through `super.x`, or inherited — where "own" is the innermost type the access is written in, so a lambda's `this.x` is `self` (a lambda has no receiver of its own); `other` through any other expression (`order.lines`), including an inner, local or anonymous class reaching its OUTER instance (`lines` in `Basket.Cursor`, implied `Basket.this.lines`). Absent on an access to a static field or to a stub. A self and an other access at one site are two edges. Measured on spring-petclinic: 460 of 590 typed entities carry a `typeExpr` (400 `named`, 53 `primitive`, 5 `array`, 2 `variable` at the top; 5 `unevaluated` nodes, all `?`), 289 entities [`TWithReceiver`](/docs/reference/metamodel/traits/#structure), and of 371 accesses 183 are `self`, 46 `other` (mostly `@Nested` test classes reading their outer class's fields) and 142 state none. ## JavaScript — `js` @@ -307,6 +312,7 @@ A profile that is specified but has no shipped extractor is complete, not defici - `this` rebinding (`call`/`apply`/`bind`, arrow lexical `this`, extracted methods) breaks receiver-based resolution; edges through a rebound `this` are not reconstructed. - Getters/setters are emitted as `method` entities; reads and writes of the underlying value at call sites are `access` edges, so a property read that runs code is visible as access, not invocation. - Class fields and object literal members share the `property` kind; object literals used as namespaces therefore appear as a `variable` with `property` children. +- MM-7 and MM-8 (contract 1.2.0) are not emitted by any extractor of this language (none ships) yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not "no written type", not "no receiver" (PLAN.md §26.10). ## PHP — `php` @@ -347,6 +353,7 @@ A profile that is specified but has no shipped extractor is complete, not defici - Single inheritance for classes (at most one inheritance edge); interfaces may extend several, so N edges are legal there. - Gradual typing: parameter, property and return type declarations are optional, so [TTypedEntity.declaredType](/docs/reference/metamodel/traits/#types) is often absent. Docblock types (@var, @param) are not authoritative and must not be promoted to declaredType. - Namespaces are 1-N with files: [TModule.definedIn](/docs/reference/metamodel/traits/#modularity) lists every file declaring into the namespace. A file with no `namespace` statement declares into the global namespace. +- MM-7 and MM-8 (contract 1.2.0) are not emitted by any extractor of this language (none ships) yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not "no written type", not "no receiver" (PLAN.md §26.10). ## Python — `python` @@ -395,6 +402,7 @@ A profile that is specified but has no shipped extractor is complete, not defici - Explicitly NOT extracted: members a decorator or a metaclass synthesizes — a dataclass's `__init__`, a Django model's manager; the class's own written fields ARE attributes. Monkey patching (`Order.total = total`): the model shows the original definition site only. Protocol (PEP 544) conformance: structural, so `interfaceImplementation` stays in the profile for a `derived` enrichment of the analyzer, never mixed in, and the extractor writes none — `class X(Protocol)` is a plain inheritance. What a string names (`ForeignKey("orders.Order")`, `INSTALLED_APPS`, an entry point in `pyproject.toml`): framework semantics. `isinstance` narrowing, notebooks and Cython. - Audit (M22c, every model `validate`-clean with the metrics pass applied, nothing installed read, nothing run): psf/requests (37 files, 2 529 entities / 3 593 edges, 0.06 s, 20 MB) resolves 81.6 % of 5 768 sites; Django (2 922 files, 111 593 / 229 360, 2.9 s, 433 MB) 73.4 % of 278 073, 18 816 of them `unbound-dynamic` (its test models, `ConnectionProxy`, `LazySettings`); Zulip (2 125 files, 54 725 / 174 640, 2.0 s, 307 MB) 81.9 % of 228 523, 6 508 `ambiguous-ancestor` (test cases under two Django test classes the extractor cannot order); CPython 3.14.10 `Lib/` (1 876 files, 206 234 / 420 124, 5.1 s, 822 MB) 77.0 % of 623 485; CPython 2.7.18 `Lib/` (1 613 files, 590 of them Python 2 syntax the parser recovers, 141 281 / 217 345, 2.8 s, 478 MB) 78.7 % of 303 632. `untyped-receiver` is the largest remainder everywhere. Keyed where typeshed declares it, no standard-library class has two keys in any of the five models (the same-name pairs left are different classes: `threading.Event` and `asyncio.locks.Event`, `binascii.Error` and `configparser.Error`…); the dotted-module guess keys 66 `` classes over the five, one of them with a Capitalized segment before the last (Zulip's `pika.spec` `Basic.Deliver`, a nested class the guess takes for a module); a corpus class written as a receiver, whatever its member, adds 14 340 `reference`s on Django, 5 780 on Zulip, 1 654 on 2.7, 1 360 on 3.14 and 1 on requests — the sites it names stay dropped where they were: no rate and no drop counter moves. In CPython 3's own `Lib/`, every import of a module that has a file there reaches that file; the 229 modules reached outside it have none (built into the interpreter, or registered at run time: `os.path`, `collections.abc`). Oracles, each in a container with no network: CPython's `ast` (lib2to3 for 2.7) and the model agree on every class, function and method by (file, line, kind, name) once the stated folds are applied (a redefinition, `@overload`, a form-made class) — all of requests, Django and Zulip, 83 413 of 83 415 on 3.14, 43 112 of 43 117 on 2.7, the rest `redefinition-of-another-kind`; grimp 3.20 on Django finds 3 209 of the model's 3 211 module edges (it has 3 214), every difference `from pkg import sub` where `pkg` binds its own submodule: grimp names the submodule, the model the package (the re-export rule); pyright (scip-python 0.6.8), where it resolves a site, agrees with 98.6 % (requests), 98.3 % (Zulip) and 98.8 % (Django) of the `declared` edges, 99.1 % / 98.9 % of `annotation-typed`, 100 % / 96.3 % of `flow-typed`, every `ancestor-attributed` one it resolves — up to the stated folds (a class called is its `__init__`, a library function its module, a library member its class, an attribute its root-most owner, a library name as the site imports it); requests' own tests (615 passed) execute 282 import statements, 262 reaching what the model says and 2 a run-time alias (`os.path` is `posixpath`; `requests.packages.urllib3` is `urllib3`); the other 18 are no statement — imports the interpreter makes inside a call (`warnings.warn`, `time.strptime`, `pickle`) — and one computed `__import__`, counted. - MM-6 (an edge's `member`, contract 1.1.0, header `schemaVersion` 1.1.0): an `invocation`, `access` or `reference` that folds into a stub names the ATTRIBUTE PATH the site writes below it, dotted. Below a module stub, the name in that module: `json.dumps(x)` → `dumps`, `os.path.join` → `join` on `%2Fos.path` (a module of its own), `os.environ.get(k)` → `environ.get` (a value of `os`), a name a `from` import binds called or read directly under the module's own name, not the alias (`from json import loads as parse; parse(s)` → `loads`, `if TYPE_CHECKING:` → `TYPE_CHECKING`). Below a class stub, the attributes after it: a method or attribute of an instance typed as a library class (`r: Response` then `r.json()` → `json`), and the ancestor-attributed edges — a member a corpus class's one library ancestor answers — where it matters most: `self.assertTrue(…)` → `assertTrue`, `super().setUp()` → `setUp`, `Tracked.objects.filter()` → `objects.filter`, so `objects.create` is told from `objects.filter`. A read is a `reference` naming the attribute (`sys.platform` → `platform`), a write an `access` (`sys.path = []` → `path`). No member: a library class called (`Enum(…)`, `TypeVar("T")` — the construction lands on the class itself), a class read as a value (`TestCase = unittest.TestCase`) or caught (`except KeyError`), a type annotation (the stub IS the type, as in Java and TypeScript), a decorator (`annotationUse`), what a call RETURNS — `json.loads(s).get(k)` is an invocation naming `loads` and one naming none, since `get` is no member of `json` — and every edge to a corpus entity, which already points at the member. An instance a library class constructs names its attributes again (`e = Enum(…)` then `e.value` → `value`). The member is part of the edge: `json.dumps(json.loads(s))` is two invocations of `json`, where it was one. On the fixture `codegraph validate` prints `members named: 16 of 25 edges to stubs` — the 9 others are 5 caught builtins, 3 library classes called and one read; no fixture site splits. Measured on pip 24.0's own tree: 5 093 of 8 374 edges to stubs named, 43 457 edges become 43 736 (264 sites split; 96 of them pair a member-less edge — a library class constructed, or a call on a call's result — with a named one). +- MM-7 and MM-8 (contract 1.2.0) are not emitted by this language's extractor yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not "no written type", not "no receiver" (PLAN.md §26.10). ## Ruby — `rb` @@ -450,6 +458,7 @@ A profile that is specified but has no shipped extractor is complete, not defici - `--trace ` merges what `extractors/ruby/trace/codegraph_trace.rb` wrote from INSIDE the running program — the one thing the extractor never does is run corpus code, so the trace is a separate step, the user's, in a project that still boots. It names constants, files and lines, never a key: no entity is added and no edge of the source changes. A mixin the VM holds and no line writes is a `traitUsage` with provenance `generated`, anchored on the declaration of the type that has it. A call the program made at a site the baseline left unresolved is ONE `invocation` with provenance `dynamic-candidate`, `candidates` listing every method that site was seen to reach and `to` the first of them — what ran once, not what must run. A method the VM holds on a line that writes no `def` has no entity and gets none: it is counted. - Audited (M18c) on rake 13.2.1, rubygems 3.6.2, Mastodon 4.3.0 and rails 8.0.2 — 100, 794, 2 541 and 3 334 files, every model `validate`-clean, rails in 4.7 s. Resolution rate 77.8 %, 54.4 %, 31.2 % and 57.0 % of the sites; Mastodon without `spec/` is 62.1 % (55 000 of its unbound calls are RSpec's DSL), rails' own `lib` and `app` 59.4 %. Four fifths of what stays unresolved in application code is `untyped-receiver` — the ceiling of any reader that does not run the code. ORACLES: Packwerk 3.3.1's reference extraction and ConstantResolver over Mastodon's autoload paths resolve 4 335 cross-file constant references in `app/` and `lib/`; the model has the same constant in the same file for 4 289 of them (98.9 %) — the 45 others are a `module Admin` WRAPPER, which Packwerk counts as a reference and the wrapper rule does not, and one an inherited constant Packwerk places by file name. The model names 346 more that Packwerk cannot: declarations outside the autoload paths. Run under its own tests in a container, rake's VM holds a method on the same line for 1 006 of the 1 012 methods the model declares in the 83 files it loaded (the six others: definitions under a platform or capability `if`, a `def` inside a method that never ran, methods of anonymous classes), and 200 methods the model has none for — 199 written by the metaprogramming loops of three files (`class_eval` of a string, `define_method` over a list), one the `else` branch of a platform test. Of the 2 829 calls observed during that run, 1 533 are edges the baseline wrote and 879 land on sites it had left untyped. The core-table misreading, measured on rubygems: 39 corpus bodies of 20 VM types (`Gem` alone 12), and 3 802 of 71 197 edges landing on the VM's stub of a type that corpus itself implements. - MM-6 (an edge's `member`, contract 1.1.0, header `schemaVersion` 1.1.0): an `invocation` of a stub names the METHOD AS WRITTEN at the site, punctuation and all — `find_by`, `save!`, `empty?`, `name=` for `x.name = v`, `[]` for `Dir[…]`. Named: a call on a library or core constant (`Stripe::Charge.create` → `create`, `File.join` → `join`, though `join` is IO's), on a receiver typed as one (`Foo.new(…).x`, a local or an instance variable every assignment of which is `Foo.new`), the method a core class adds to a corpus reopening or subclass of it (`upcase` in a subclass of String), the call attributed to the one library ancestor that could answer (`has_many`, `where` in an ActiveRecord model), a method some library adds to a core class (`Time.zone`), and `super`, which names the enclosing `def`'s name — the method Ruby calls one step up (`def save; super; end` → `save`, `super(…)` in `initialize` → `initialize`). `Foo.new` names `new`: in Ruby it is an ordinary singleton method the site writes (and a class may redefine), and it tells instantiation from `Foo.create` on the same stub; the chain is still searched for `initialize`, so a corpus `initialize` is the corpus edge it always was. No member: a constant read (`Foo`, `Foo::BAR`, `include Comparable` — the stub IS the constant written: a library's `Foo::BAR` is a stub of its own, since a reader cannot tell a nested type from a value), an `import`, `inheritance`, `traitUsage` or `throws` edge, a `--trace` candidate, and every edge to a corpus entity, which already points at the method. The member is part of the edge: `Stripe::Charge.create(Stripe::Charge.retrieve(id))` and `Logger.new(io).info(m)` are two invocations of one stub at one site, where they were one. On the fixture `codegraph validate` prints `members named: 13 of 24 edges to stubs` — the 11 others are constant reads; no fixture site splits. +- MM-7 and MM-8 (contract 1.2.0) are not emitted by this language's extractor yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not "no written type", not "no receiver" (PLAN.md §26.10). ## Rust — `rust` @@ -491,6 +500,7 @@ A profile that is specified but has no shipped extractor is complete, not defici - Enum variants are not reified as a kind of their own: the enum is the type-level unit, variant payload types appear as `reference` edges from it, and named variant fields are `field` children. - `static` items map to the `const` kind. Tuple-struct fields are named by their position ("0", "1", ...). Shadowed `let` bindings produce several localVariable entities disambiguated by (file, startLine). - The `self` receiver is not emitted as a parameter; the receiver relation is the impl block's attachment. +- MM-7 and MM-8 (contract 1.2.0) are not emitted by any extractor of this language (none ships) yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not "no written type", not "no receiver" (PLAN.md §26.10). ## TypeScript — `ts` @@ -556,3 +566,4 @@ Declaration spaces: `abstractClass`, `arrowFunction`, `class`, `enum`, `function - A written value ([TWithValue](/docs/reference/metamodel/traits/#structure)) is emitted for a `const` variable, a `readonly` property, an enum member and a parameter default whose initializer is CONSTANT-SHAPED — a literal, `-N`, an enum member, a type used as a value, arrays and operator expressions over those. TypeScript folds nothing at the declaration, so `4 * 25` rides `unevaluated` with its source text where Java would fold it; an enum member's value is the checker's computed constant. An initializer that is code — a call, a `new`, a function, an object literal — carries no value at all: absence is a claim. Such an initializer's calls and accesses are edges FROM the variable or property (the narrowest declared owner), which then carries [TWithInvocations](/docs/reference/metamodel/traits/#behavior)/[TWithAccesses](/docs/reference/metamodel/traits/#structure). - The metrics pass (`codegraph-metrics`, PLAN.md §18): namespaces, enums, type aliases, interface members without a body and ambient declarations have no big-code-analysis space and carry none of the pass's keys. An exported class's decorators precede tree-sitter's class node; the pass joins across the decorator lines. In a `.tsx` file big-code-analysis's `ploc` can count a line or two fewer than this extractor's `sloc` (a JSX text token counts every line it spans here), so the join's witness differs there by that much. - MM-6 (an edge's `member`, contract 1.1.0): an `invocation`, `access` or `reference` that folds into a stub names the member it reached, spelled as the DECLARATION writes it — the property name. A method call or a property read or write on an external type: `push`, `size` (`isRead`/`isWrite` as at any access; a getter or setter is its property's name). A free function, variable or namespace member of a module: the name the module EXPORTS it under, so an aliased import `import { readFileSync as r }` names `readFileSync`, a default export `default`, a namespace import `fs.readFileSync(…)` `readFileSync`; a member of a namespace is its dotted path below the stub (`util.format`, `constants.R_OK`), and `declare global` is a scope, not a segment. A function used as a value (`reference`), a tagged template's tag and a JSX component name the function. No member where the site reaches the stub itself: `new T()` and a constructor, a call or construct signature (`String(x)`, `super(…)`, `expect(x)`), calling an `export =` module, a type reference (the stub IS the type), a variable folded to its declared type (`declare var Math: Math`), and a property of a signature's anonymous type (`readConfigFile(…).config`). Decorators are `annotationUse` and name none. An edge to a corpus entity never names one, even when an external declaration merges into it. Measured on codegraph itself (2026-11-28): 29 641 of 47 493 edges to stubs named, entity and edge counts unchanged (this extractor never merged edges). +- MM-7 and MM-8 (contract 1.2.0) are not emitted by this language's extractor yet: no entity carries `typeExpr` (the type as written, a tree beside `declaredType`), the profile licenses [`TWithReceiver`](/docs/reference/metamodel/traits/#structure) on no kind, and no `access` carries a `receiver`. Their absence here says nothing — not "no written type", not "no receiver" (PLAN.md §26.10). diff --git a/website/content/docs/tutorials/sql.md b/website/content/docs/tutorials/sql.md index c633e974..8f129e03 100644 --- a/website/content/docs/tutorials/sql.md +++ b/website/content/docs/tutorials/sql.md @@ -82,7 +82,7 @@ SELECT e.id AS ref, CREATE TEMP VIEW dep AS SELECT x.id AS ref, x.from_id AS from_ref, x.to_id AS to_ref, ek.name AS kind, p.name AS provenance, f.path AS file, x.anchor_start AS line, - x.member AS member + x.member AS member, x.receiver AS receiver FROM edge x JOIN edge_kind ek ON ek.id = x.kind_id JOIN provenance p ON p.id = x.provenance_id JOIN file f ON f.id = x.anchor_file_id; diff --git a/website/scripts/edges-diagram.mjs b/website/scripts/edges-diagram.mjs index b2a69fd0..6717b9c3 100644 --- a/website/scripts/edges-diagram.mjs +++ b/website/scripts/edges-diagram.mjs @@ -53,7 +53,7 @@ export const FAMILIES = [ cell: [2, 0], kinds: [ { name: "invocation", ends: "Invocable → Invocable", extra: ["candidates?: EntityId[]", MEMBER], keys: ["candidates", "member"] }, - { name: "access", ends: "Invocable → Structural", extra: ["isRead, isWrite: boolean", MEMBER], keys: ["isRead", "isWrite", "member"] }, + { name: "access", ends: "Invocable → Structural", extra: ["isRead, isWrite: boolean", "receiver?: self | other", MEMBER], keys: ["isRead", "isWrite", "receiver", "member"] }, { name: "throws", ends: "Invocable → exception type", keys: [] }, ], }, diff --git a/website/scripts/traits-diagram.mjs b/website/scripts/traits-diagram.mjs index 50e515d1..cfd1e254 100644 --- a/website/scripts/traits-diagram.mjs +++ b/website/scripts/traits-diagram.mjs @@ -56,6 +56,7 @@ export const FAMILIES = [ { name: "TStructural", sub: "value holder, target of accesses", keys: [], example: true }, { name: "TWithAccesses", sub: "→ access edges", keys: [] }, { name: "TWithValue", sub: "value: Literal", keys: ["value"] }, + { name: "TWithReceiver", sub: "needs an instance of its type", keys: [] }, ], }, { @@ -78,7 +79,7 @@ export const FAMILIES = [ { name: "TType", sub: "isStub: boolean", keys: ["isStub"] }, { name: "TWithInheritances", sub: "→ inheritance edges", keys: [] }, { name: "TWithImplements", sub: "→ interfaceImplementation edges", keys: [] }, - { name: "TTypedEntity", sub: "declaredType?: EntityId", keys: ["declaredType"] }, + { name: "TTypedEntity", sub: ["declaredType?: EntityId", "typeExpr?: TypeExpr"], keys: ["declaredType", "typeExpr"] }, ], }, {