# Flow Analysis Source Boundary Refactoring

This document proposes replacing naked source offsets in flow-analysis recording APIs with semantic source boundaries, and defining source-position queries using one inclusive boundary convention.

The intended result has three layers:

- resolver and type-analysis code identifies semantic boundaries such as “after this statement,” “before argument 2,” and “at loop updater entry”;
- flow analysis records state transitions at those boundaries, including the source-order repairs required when analysis visits code out of lexical order; and
- `FlowAnalysisLog` stores compact integer keys and treats the final transition at an offset as the state for the source interval beginning at that offset.

Integer offsets remain the internal indexing representation. The refactoring removes them from semantic call sites because a bare integer does not say which construct the point belongs to or which side of the construct it represents.

The immediate consumer is `FunctionBody.lookupPromotedThisType`, used by analysis-server completion to determine the effective type of implicit `this` at a cursor. The design is intentionally general enough for other flow-log queries, but it does not otherwise redesign flow analysis.

---

## 1. Current Model

`FlowAnalysisLog` records snapshots of two pieces of state:

- the current `PromotionInfo`; and
- the promotion key currently bound to `this`.

Each snapshot is paired with an integer offset. On the first query, the log stably sorts the snapshots by offset and then uses binary search. This supports source-based lookup even though type analysis does not always visit constructs in source order.

The current query convention is left-biased: if a transition is recorded at offset `n`, a query at offset `n` returns the state immediately to the left of the transition. The transition is visible only at offsets greater than `n`.

The current recording API describes offsets using prose such as:

> The last source offset that should be considered to be prior to the transition.

Callers therefore choose among values such as:

- `token.offset`;
- `token.end`;
- `node.offset`;
- `node.end`; and
- a nearby separator's offset or end.

These values are all integers, but they are not interchangeable. `node.end` and `token.end` are exclusive source positions, while `token.offset` points at the first code unit of a token. The current log convention treats all of them as if they named a character to the left of the state transition.

### 1.1 Non-Source-Order Analysis

Several constructs are deliberately analyzed in an order different from their lexical order:

- a conventional `for` loop's updater is written before the body but analyzed after it;
- a pattern assignment's right-hand side is analyzed before its pattern;
- a pattern variable declaration's initializer is analyzed before its pattern;
- a pattern for-in loop's iterable expression is analyzed before its pattern; and
- horizontal inference defers function-literal arguments until other arguments have been analyzed.

For these constructs, sorting snapshots by offset is not sufficient. Flow analysis must also record restoration snapshots at the boundaries of lexically displaced regions. Otherwise, state produced by a later source region leaks backward into an earlier region after sorting.

The current implementation exposes this repair protocol through operations such as `allowOutOfOrderOffsets()` and `recordArgumentVisitOrderException(offset: ...)`. The client must detect every discontinuity, choose the correct punctuation boundary, record the current state, and perform a final repair if analysis does not end on the last source argument.

---

## 2. Problems

### 2.1 Exact-Boundary Lookup Is Left-Biased

Consider:

```dart
if (this is D) {}^
```

The caret is at `ifStatement.end`. Completion is after the `if`, so `this` is no longer promoted. Flow analysis records the joined post-`if` state at `ifStatement.end`, but the current left-biased lookup excludes transitions at the query offset and returns the stale `D` state from inside the branch.

Under ordinary half-open source coordinates, a transition at offset `n` describes the state beginning at `n`. A query at `n` should therefore include that transition. The current strict comparison gives exclusive node ends a different meaning from other half-open source positions.

### 2.2 Exclusive Ends Violate the Current Left-Biased Convention

Many flow transitions are recorded using `node.end`. Under the current lookup rule, a query at that same exclusive end observes the state before the transition.

This produces both directions of error.

Over-promotion:

```dart
if (this is D) {}/* expected: unpromoted; actual: D */
```

Under-promotion through non-linear execution flow:

```dart
try {
  if (b) return;
  this as D;
} finally {
}/* expected: D; actual: unpromoted */
```

Only the promoted path reaches the code after the `try/finally`, so the correct live-out type is `D`. At the exact statement end, the current query observes the joined entry-to-`finally` state rather than the attached live-out state recorded at the same exclusive end.

The problem is not specific to one statement kind. Conditional expressions, loops, if statements, switch statements, try/catch, null-aware expressions, logical operators, and anonymous-method exits all have call sites that can record a transition at an exclusive end.

### 2.3 Horizontal Inference Leaks State at an Exact Comma Boundary

Horizontal inference demonstrates the interaction between exact boundaries and out-of-source-order analysis:

```dart
g(
  () { /* `this` is D in the deferred body */ },
  /* `this` is not yet D here */ this as D,
);
```

The later non-function argument is analyzed first and promotes `this`. When analysis returns to the deferred first argument, the closure body intentionally sees `D`. To reconstruct lexical source regions, the analyzer records the pre-second-argument state at the preceding comma.

The current analyzer computes that repair point as `comma.end`. A query immediately after the comma also has offset `comma.end`. Because lookup excludes transitions at the exact query offset, it misses the restoration snapshot and sees the later argument's `D` promotion leaking backward.

The final horizontal-inference repair similarly uses `rightParenthesis.end`, even though the flow-analysis documentation describes the right parenthesis itself as the boundary.

This is a client-protocol failure made easy by a primitive interface. Both `comma.offset` and `comma.end` look locally plausible, and neither call site expresses whether the intended boundary is before the comma, after the comma, or before the following argument.

### 2.4 Assertions Validate Monotonicity, Not Meaning

`FlowAnalysisLogBuilder.checkOffset` checks that offsets are nondecreasing. `allowOutOfOrderOffsets` resets that check for a displaced source region.

This catches some missing offset plumbing, but it cannot establish that:

- the selected boundary is semantically correct;
- a restoration snapshot was recorded for every skipped lexical interval;
- a final restoration was recorded after an out-of-order traversal;
- equal-offset snapshots have the intended semantic ordering; or
- a caller used `offset` rather than exclusive `end` under the current lookup convention.

The checks are assertions and therefore provide no protection in release builds. A missed restoration can silently produce a plausible but incorrect source-ordered log.

### 2.5 `offset = 0` Hides Missing Plumbing

Many flow-analysis operations accept `int offset = 0`. This was convenient while offsets were introduced incrementally, but it weakens the final interface. A caller can omit a meaningful source point and still compile. Depending on analysis order and build mode, the mistake either triggers an assertion or records real flow state at the beginning of the file.

An absent semantic boundary should be explicit. If logging is disabled for a client, the adapter can discard the boundary; the semantic operation should not pretend that source offset zero is a real substitute.

### 2.6 Stable Sorting Needs a Right-Side Invariant

Stable sorting is useful for multiple transitions at the same offset because it preserves their recording order. The log still needs to define which state applies to the source interval beginning at that offset.

The proposed invariant is right-continuous: a query at offset `n` observes all transitions recorded at `n`, and therefore returns the final state at that offset. Recording code is responsible for ensuring that this final state describes the source immediately to the right. Intermediate states between equal-offset transitions are not source-position query results.

---

## 3. Design Goals

- Represent semantic recording boundaries without exposing naked integers at flow-analysis call sites.
- Make a transition visible at its exact boundary using one inclusive lookup rule.
- Preserve compact integer storage and binary-search lookup inside `FlowAnalysisLog`.
- Encapsulate bookkeeping for constructs analyzed out of source order.
- Make incorrect or missing boundary plumbing difficult to compile.
- Provide useful debug descriptions and validation for boundary mismatches.
- Keep analyzer and CFE clients able to construct boundaries from their own syntax representations.
- Test the semantic contract at the analyzer ownership layer and retain a small number of analysis-server integration tests.

## 4. Non-Goals

- Do not redesign the flow model, SSA representation, or promotion rules.
- Do not replace AST offsets, token offsets, or ordinary source ranges throughout the analyzer.
- Do not replace the integer-indexed log with an interval tree solely for abstraction purity.
- Do not make `FlowAnalysisLog` a general execution trace.
- Do not expose intermediate states between equal-offset transitions unless a real consumer requires them.
- Do not guarantee precise flow types where parser recovery collapses several synthetic transitions onto a source position with no corresponding source interval.
- Do not add one analysis-server completion test for every flow construct; semantic coverage belongs primarily in analyzer tests.

---

## 5. Terminology and Semantics

### 5.1 Source Boundary

A source boundary is a position between source code units at which flow state changes. It has:

- a materialized integer offset used by the log;
- a semantic construction operation, such as before a token, after a token, before a node, or after a node; and
- an optional debug identity describing the construct landmark while the boundary is materialized.

Examples include:

```text
afterToken(ifStatement.rightParenthesis)
afterNode(ifStatement)
beforeNode(argument)
afterToken(argumentList.leftParenthesis)
afterToken(forParts.rightSeparator)
```

The structural origin is not merely a type name around an integer. The factory call states why the offset is correct and validates properties such as `afterNode(node).offset == node.end`. The production value need not retain the node or token after that validation.

### 5.2 Transition

A transition changes the flow state at a source boundary. The state on the two sides is conceptually:

```text
                         boundary n
state before n  ----------------|----------------  state after n
```

The log stores the state after the transition. Inclusive lookup observes the transition at the exact numeric boundary.

### 5.3 Right-Continuous Query Semantics

A source-position query returns the final entry whose offset is less than or equal to the requested offset:

```text
last entry where entry.offset <= queryOffset
```

Conceptually, an entry at `n` defines the state for the half-open interval from `n` to the next distinct entry offset. If several transitions have offset `n`, stable recording order makes the final transition the state for that interval.

There is no source interval between equal-offset transitions, so the initial API does not expose those intermediate states. A future consumer with a demonstrated need for one must query by structural boundary identity rather than by adding a second global offset interpretation.

### 5.4 Flow State at Lexically Displaced Code

The query reports the flow state in effect when the source region is semantically analyzed, not merely the state produced by scanning characters from left to right.

Consequently:

- a conventional `for` updater can observe effects from the body;
- a pattern can observe effects from its lexically later RHS or initializer;
- a pattern for-in can observe effects from its lexically later iterable expression; and
- a deferred function-literal body can observe effects established by later arguments through horizontal inference.

Restoration entries divide those semantic regions so that unrelated gaps and later source expressions receive the correct state.

---

## 6. Proposed Recording API

### 6.1 Allocation-Free Opaque Boundary Value

Flow-analysis semantic operations accept an opaque boundary rather than an integer:

```dart
extension type const FlowBoundary._(int _offset) {
  int get materializedOffset => _offset;
}

abstract base class FlowBoundaryFactory<Node, Token> {
  int nodeOffset(Node node);
  int nodeEnd(Node node);
  int tokenOffset(Token token);
  int tokenEnd(Token token);

  bool ownsNode(Node node);
  bool ownsToken(Token token);

  FlowBoundary beforeNode(Node node) {
    assert(ownsNode(node));
    return FlowBoundary._(nodeOffset(node));
  }

  FlowBoundary afterNode(Node node) {
    assert(ownsNode(node));
    return FlowBoundary._(nodeEnd(node));
  }

  // beforeToken and afterToken are analogous.
}
```

An extension type is represented by its integer offset and does not allocate. The shared factory owns the private constructor; analyzer and CFE adapters provide access to their node and token coordinates and validate source ownership. Each client reuses one of these adapters rather than constructing a factory per boundary. The semantic factory name remains visible at the call site, but the resulting value does not retain the syntax object.

The important invariants are that semantic flow methods cannot receive a bare `int` and that creating an individual boundary allocates no heap object. Explicit diagnostic tracing may retain origin information, but ordinary analysis and ordinary assert-enabled development runs do not.

### 6.2 Canonical Boundary Coordinates

Boundary offsets use ordinary half-open source coordinates:

- `beforeToken(token)` materializes `token.offset`;
- `afterToken(token)` materializes `token.end`;
- `beforeNode(node)` materializes `node.offset`; and
- `afterNode(node)` materializes `node.end`.

No caller subtracts one from an exclusive end. No documentation speaks about the “last source offset” before a transition. Inclusive equality is part of the query contract, not arithmetic at recording sites.

For example:

```dart
flow.ifStatement_end(boundary: boundaries.afterNode(node));
flow.for_updaterBegin(
  boundary: boundaries.afterToken(forParts.rightSeparator),
);
```

This convention makes whitespace behavior natural. A transition after a comma is recorded at `comma.end`; a query either exactly at `comma.end` or in the following whitespace observes it.

### 6.3 Required Boundaries

Logging-relevant boundaries are required:

```dart
void whileStatement_end({required FlowBoundary boundary});
```

They do not default to source offset zero.

Because `FlowBoundary` has the same runtime representation as its integer offset, a client that does not produce logs pays no boundary-allocation cost. The semantic API still requires the caller to identify the landmark, so logging cannot later be enabled with silently missing information.

### 6.4 Construct-Specific Boundary Groups

Constructs with several related landmarks should expose one typed boundary role instead of independent boundary parameters:

```dart
abstract interface class ForFlowBoundaries {
  FlowBoundary get conditionEntry;
  FlowBoundary get bodyEntry;
  FlowBoundary get updaterEntry;
  FlowBoundary get exit;
}

abstract interface class PatternAssignmentFlowBoundaries {
  FlowBoundary get patternEntry;
  FlowBoundary get rhsEntry;
  FlowBoundary get exit;
}

abstract interface class ArgumentListFlowBoundaries {
  int get argumentCount;
  FlowBoundary beforeArgument(int index);
  FlowBoundary get afterArguments;
}
```

These are semantic roles, not a requirement to allocate new group objects. Existing resolver or inference context objects should implement them where possible. In particular, argument boundaries are computed lazily from the existing argument list; the implementation must not allocate and populate a second `List<FlowBoundary>` for every invocation.

The roles encode landmark identity and cardinality. `ArgumentListFlowBoundaries.argumentCount` must equal the number of syntactic arguments. The implementation owns punctuation policy instead of requiring each resolver call site to choose separator offsets independently.

Simple one-transition operations do not need a construct role; a required `FlowBoundary` is sufficient. Any new group or session allocation must replace comparable existing state or be justified by focused performance measurements.

---

## 7. Encapsulating Out-of-Source-Order Traversal

### 7.1 Problem with `recordArgumentVisitOrderException`

The current horizontal-inference client tracks `lastArgumentVisited` and performs three kinds of checks:

- before the first visited argument if it is not source argument zero;
- between visited arguments when their source indexes are discontinuous; and
- after all arguments if the last visited argument is not the final source argument.

Every discontinuity must record the current state at the appropriate lexical boundary. This is meaningful complexity, but it belongs in one helper rather than every invocation resolver.

### 7.2 Argument Visit Session

Give the existing per-invocation resolver or inference state a visit-session role:

```dart
abstract interface class ArgumentFlowVisitSession {
  void begin(ArgumentListFlowBoundaries boundaries);
  void beforeArgument(int index);
  void finish();
}
```

The existing invocation helper implements this role and holds the last-visited
index. The role does not require another heap object.

There is one additional invariant that a simple `lastVisitedIndex` protocol
does not capture. When more than one function literal is deferred, the live
flow state while the second deferred literal is eventually analyzed may
already include effects from ordinary arguments that occur later in source.
That state is correct inside the deferred literal, but it is not the state of
the lexical gap preceding the literal. The initial source-order scan must
therefore retain the flow-log checkpoint present when each literal is
deferred.

The checkpoint consists of the existing immutable `PromotionInfo` reference
and `this` promotion key. It is stored as fields on the existing deferred
argument metadata object; it is not a newly allocated checkpoint, boundary, or
log-entry object. A visit session that creates a separate object or record for
each checkpoint is not acceptable without measurements demonstrating a need.

The invocation resolver becomes:

```dart
var flowOrder = invocationInference.argumentFlowVisitSession;
flowOrder.begin(argumentBoundaries);

for (var argument in argumentsInSourceOrder) {
  if (shouldDefer(argument)) {
    flowOrder.defer(argument.index, currentLogState);
    continue;
  }
  flowOrder.beforeArgument(argument.index);
  resolve(argument);
}

for (var argument in deferredArguments) {
  flowOrder.beforeDeferredArgument(
    argument.index,
    argument.lexicalLogCheckpoint,
  );
  resolve(argument);
}

flowOrder.finish();
```

`beforeArgument(index)` validates the index and records the current state at
`boundaries.beforeArgument(index)` when the ordinary source-order traversal
skips one or more deferred arguments. `beforeDeferredArgument` records the
saved lexical checkpoint at that boundary, not the current semantic state.
Flow analysis transitions at the deferred function body's own boundaries then
record the current semantic state that the body intentionally observes.
`finish()` records at `afterArguments` when required and asserts that the
session is not used again.

The call site no longer chooses punctuation offsets, exposes
`lastArgumentVisited`, or remembers the final correction. Retaining a lexical
checkpoint is essential: sorting by offset cannot recover a state that was
never recorded, and using the live state at deferred-visit time leaks effects
from later ordinary arguments into earlier source gaps.

### 7.3 Other Displaced Constructs

Pattern and loop displacement is more structurally fixed than horizontal inference. Their existing flow operations can consume typed boundary groups and perform restoration internally.

For example, pattern assignment analysis supplies one `PatternAssignmentFlowBoundaries` view, preferably implemented by existing resolver state. Flow analysis owns the sequence:

```text
record source state at rhsEntry
analyze RHS
move backward to patternEntry
analyze pattern under post-RHS semantic state
record exit state
```

Similarly, a conventional `for` helper owns condition, body, updater, and exit boundaries. This prevents the resolver from passing four unrelated integers whose intended relationships are documented only in prose.

### 7.4 Abrupt Control Through `finally`

An exact source boundary is useful only if the flow model recorded there is
semantically correct. A `break`, `continue`, or anonymous-method `return` whose
target is outside a `try/finally` cannot be joined directly into its target:
the `finally` block still executes on that path.

The active `try/finally` context therefore retains pending abrupt-exit models,
grouped by their eventual targets. These maps are allocated lazily only when
an exit actually crosses the context. At the end of the `finally` block, flow
analysis applies `attachFinally` to every pending model and then routes the
result toward its target. Routing can encounter an enclosing `try/finally`, so
the same operation composes for nested contexts.

Before multiple pending paths for one target are joined, each path must be
unsplit to the reachability parent that was active before entering the `try`.
Branch-local reachability nodes from differently nested `if` or loop
constructs are otherwise incompatible even when their eventual abrupt target
is the same. This checkpoint normalization is a control-flow invariant, not a
source-offset correction, and belongs inside the `try/finally` context rather
than at each `break`, `continue`, or `return` call site.

---

## 8. Proposed Query API

### 8.1 FlowAnalysisLog

The internal query continues to accept an integer offset:

```dart
PromotionInfo? getPromotionInfo(int offset);
PromotionKey? getThisBinding(int offset);
SharedTypeView? lookupPromotedThisType(int offset);
```

The lookup rule is:

```text
last entry where entry.offset <= queryOffset
```

Stable order remains the tie-breaker among entries at the same numeric offset, so lookup observes the final state recorded at that boundary. Recording code must leave the state for the source interval to the right as the last equal-offset entry.

Intermediate states between several transitions at one boundary are not addressable by the initial API. There is no physical source interval in which to observe them. If a future valid-code consumer needs a structurally anchored intermediate state, the query can be extended with boundary identity.

### 8.2 FunctionBody Public API

The public query retains its narrow offset-based interface:

```dart
DartType? lookupPromotedThisType({required int offset});
```

Its contract changes from strict left-biased lookup to the inclusive rule above. Compatibility for a previously published left-biased contract is discussed in Section 13.1; it does not require exposing both conventions permanently.

---

## 9. Log Representation and Validation

### 9.1 Keep Parallel Integer and Value Lists

Production logs store offsets and values in parallel lists, as the current implementation does:

```dart
final List<int> _promotionInfoOffsets = [];
final List<PromotionInfo?> _promotionInfoValues = [];

final List<int> _thisBindingOffsets = [];
final List<PromotionKey> _thisBindingValues = [];
```

There is no heap object per transition. Source offsets are Smis, and values are references to the existing promotion structures. A small `_FlowLogSeries<T>` wrapper around one pair of offset/value lists is acceptable if it improves encapsulation, but it is one object per state channel, not per entry.

Insertion index is the sequence number and is not stored as another field. Stable sorting orders by offset and preserves original list order for equal offsets. Query uses an upper-bound search on the offset list and returns the value at the index immediately before that bound.

The parallel-list representation is a production requirement, not a profiling-dependent option. A retained `_FlowLogEntry` object for every transition would add object headers, pointer chasing, and GC traversal to every resolved function body.

### 9.2 Optional Boundary Tracing

Normal logs retain neither boundary objects, per-transition entry objects, nor syntax identities. An explicitly enabled diagnostic trace may record compact boundary kinds and operation names in a parallel structure:

```text
offset 143, afterNode(IfStatement), ifStatement_end
offset 143, afterNode(AnonymousBlock), anonymousBlockBody_end
```

This makes failures diagnosable without changing release representation or adding allocation to ordinary assert-enabled runs. A trace should retain a node or token identity only when a specific investigation requires it; otherwise the offset, boundary kind, and operation name are sufficient.

### 9.3 Validation

Boundary adapters and construct groups should assert:

- token and node ownership belongs to the analyzed source;
- `before` and `after` factories materialize the expected start or end;
- argument boundary count matches argument count;
- source-ordered construct landmarks are monotonic when they should be;
- a visit session is finished exactly once;
- argument indexes are visited at most once per intended inference stage;
- every explicit out-of-order move is mediated by a construct helper; and
- no logging-relevant operation receives an absent boundary.

Monotonic offset checking remains useful as a secondary invariant. It is not the semantic API.

---

## 10. Alternatives Considered

### 10.1 Change `<` to `<=` Only

This is the query rule adopted by this design. By itself, however, it does not explain recording call sites that mix token offsets and exclusive ends, ensure that equal-offset transitions end in the state for the source interval to the right, or reconstruct source regions analyzed out of lexical order.

Required, but insufficient as the entire refactoring.

### 10.2 Record `node.end - 1`

This adapts exclusive ends to the current “last source offset” convention, but fails for empty nodes, hides token-length assumptions, and moves semantic policy into arithmetic at every call site.

Rejected.

### 10.3 Standardize on `token.offset`

Using the final token's offset can make the current left-biased query appear to work for single-character punctuation. It is not a coherent coordinate model for multi-character tokens, gaps, or transitions before a token.

Useful only as a narrow tactical repair while the boundary API is introduced.

### 10.4 Query by AST Node Only

An API such as `lookupAfter(node)` is useful for tests but insufficient for completion. Carets frequently occur in whitespace, comments, and positions between adjacent constructs where no unique AST node represents the requested point.

Rejected as the sole query API. Node-anchored boundary factories remain useful for recording.

### 10.5 Store Source Intervals Instead of Transitions

The analyzer could materialize a map from source intervals to flow states. This makes some queries direct, but overlapping semantic regions from closures, patterns, and displaced analysis require precedence rules at least as complex as transition boundaries. It also increases storage and construction cost.

Rejected unless measurements or a broader consumer justify it.

### 10.6 Recompute Flow State for Every Query

Completion could partially re-run resolution up to the cursor. This is expensive, difficult for lexically displaced execution regions, and duplicates the resolver's flow semantics.

Rejected.

### 10.7 Use a Publicly Constructible Integer Wrapper

A wrapper that any caller can construct directly from `int` improves type spelling but not correctness. It still permits callers to choose a plausible wrong integer and cannot validate its structural origin.

Rejected. The allocation-free representation has a private constructor and is produced through structural factories.

### 10.8 Retain Boundary Origin Objects

The literal class hierarchy originally considered for `FlowBoundary` requires one boundary allocation plus a second origin-wrapper allocation for every semantic flow event. On a 64-bit Dart VM this is approximately 48 bytes of young-generation allocation per boundary, even though the log ultimately needs only the integer offset. One million boundaries would therefore produce roughly 48 MB of transient allocation traffic.

Rejected for normal analysis. Structural factories validate the origin immediately and return an allocation-free extension-type value. Rich origin objects are permitted only in an explicitly enabled diagnostic trace.

### 10.9 Store Per-Transition Log Entry Objects

A class containing `offset`, `sequence`, and `value` would occupy approximately 32 bytes per transition on a 64-bit Dart VM, in addition to the containing list slot. These objects remain reachable with the resolved function body, unlike temporary boundary values. One million transitions would retain roughly 32 MB in entry objects alone and require the garbage collector to traverse one million additional objects.

Rejected. Production logs use parallel offset and value lists. Original insertion index supplies the stable tie-breaker without a persistent sequence field.

---

## 11. Testing Strategy

### 11.1 FlowAnalysisLog Unit Tests

Add direct tests for:

- inclusive lookup at an exact transition;
- multiple transitions at the same offset, returning the final one;
- out-of-order insertion followed by sorting;
- independent promotion-info and `this`-binding transitions at one boundary;
- queries before the first and after the last transition.

### 11.2 Analyzer Resolution Tests

Use inline `/*this: TYPE*/` expectations at exact source points. Analyzer tests own the semantic matrix because `FunctionBody.lookupPromotedThisType` is the changed API.

Required categories include:

- exact exits from conditional expressions, if statements, loops, switch statements, try/catch, and null-aware/logical expressions;
- `try/finally` where abrupt completion makes the post-statement state more promoted than the state entering `finally`;
- multiple differently nested abrupt paths crossing one or more `finally`
  blocks, including `break`, `continue`, and anonymous-method `return`;
- block- and expression-bodied anonymous-method exits;
- conventional `for` updater state after the body and after `continue` joins;
- pattern assignment, pattern variable declaration, and record-pattern for-in source displacement;
- horizontal inference with the deferred argument first and in a later position;
- exact `(`, comma, and `)` boundaries under horizontal inference;
- multiple deferred arguments with source gaps;
- multiple deferred arguments where each source gap has a different promotion
  state;
- named arguments, including named arguments before positional arguments;
- nested invocations with independent visit sessions.

Tests should contain both over-promotion and under-promotion failures. A matrix in which every expected result is `null` can miss a boundary rule that always chooses the left or right state.

### 11.3 Analysis-Server Completion Tests

Keep a small integration set:

- completion immediately after an `if` must not suggest members available only on a stale promoted subtype;
- completion immediately after a `try/finally` must suggest members available on the promoted live-out subtype.

Additional constructs belong in analyzer tests unless they exercise distinct completion behavior.

### 11.4 Performance Validation

Run representative analyzer resolution benchmarks before and after migrating boundary APIs. Measure elapsed time, allocated bytes, and retained log memory with diagnostic boundary tracing disabled.

Individual `FlowBoundary` values must contribute no allocation, and the number of retained per-transition objects must remain zero. If construct roles or visit sessions introduce new objects, lists, records, or closures, measure them independently and either reuse existing resolver state or demonstrate that their cost is negligible relative to the complexity they remove.

---

## 12. Migration Plan

### Phase 1: Lock Down Current Failures

Land analyzer inline expectations and representative completion tests before changing production behavior. Keep exact punctuation adjacency in source; whitespace after a boundary can accidentally make a broken strict comparison pass.

### Phase 2: Adopt Inclusive Lookup

Change source-position lookup to return the final entry whose offset is less than or equal to the query offset. Document the log as a right-continuous step function. If public compatibility requires preserving the legacy left-biased method temporarily, add a separately named inclusive query and migrate analysis-server completion to it.

### Phase 3: Introduce Boundary Adapters

Add reusable analyzer and CFE factories for `beforeToken`, `afterToken`, `beforeNode`, and `afterNode`. Flow-analysis operations accept the allocation-free `FlowBoundary` extension type while the builder continues storing materialized integers.

Migrate exact-end operations first because they already have demonstrated failures.

### Phase 4: Encapsulate Horizontal Inference

Replace exposed `lastArgumentVisited` and
`recordArgumentVisitOrderException` protocol with `ArgumentFlowVisitSession`
and `ArgumentListFlowBoundaries` roles implemented by existing per-invocation
state. Store each deferred argument's lexical `PromotionInfo` and `this`
binding in its existing metadata object. Add multi-argument, named-argument,
and nested-invocation tests before deleting the old API. Benchmark any
implementation that introduces a new session, checkpoint, or
boundary-container allocation.

### Phase 5: Migrate Other Displaced Constructs

Introduce typed boundary groups for conventional `for` and pattern constructs. Move restoration recording into those helpers and remove direct `allowOutOfOrderOffsets` calls from clients.

### Phase 6: Remove Optional Offset Defaults

Once a semantic operation participates in logging, make its boundary required. Delete `offset = 0` defaults from migrated APIs. Keep an explicit no-log adapter for clients that genuinely do not collect source-position logs.

### Phase 7: Strengthen Validation

Add explicitly enabled debug traces for boundary origins, ensure every out-of-order traversal uses a scoped helper, and retain monotonicity assertions as a backstop. Run the analyzer resolution suite, performance validation, and language/co19 test configurations required for resolver changes.

---

## 13. Compatibility and Performance

### 13.1 API Compatibility

The recording APIs are internal to the SDK and can migrate incrementally through adapters.

`FunctionBody.lookupPromotedThisType` is public analyzer API. If it is still unreleased, change its semantics directly to inclusive lookup. If it has shipped with a documented left-biased contract, add a separately named inclusive method, migrate the analysis server, and deprecate the old method in a normal breaking-change window. Compatibility does not justify exposing both policies as a permanent per-call parameter.

### 13.2 Runtime Cost

Release-mode storage remains integer offsets plus state pointers. Inclusive lookup uses an upper-bound binary search with the same asymptotic cost as the current lookup.

Individual `FlowBoundary` values are allocation-free in production and debug builds. Factory assertions validate source ownership and coordinate selection without retaining the source anchor. The design does not rely on escape analysis to remove boundary allocations. Flow logs likewise allocate no per-transition entry objects; they retain only parallel list elements.

Construct-specific roles and argument visit sessions should reuse existing resolver or inference objects. Any newly allocated group, session, list, record, or closure on the normal resolution path requires a focused benchmark. In particular, disabling flow logging must not be the only mechanism for avoiding boundary allocation, because logging is enabled during ordinary analyzer resolution.

Optional rich boundary tracing is outside the normal performance contract and must be explicitly enabled.

### 13.3 Log Construction Cost

The proposal may reduce duplicated restoration entries by centralizing construct traversal, but that is not a design requirement. Correctness and interface depth come first. Any compaction should be measured after the semantic API is stable.

The current stable sort creates temporary tuple records when a log is first queried. That cost is distinct from retained log representation: it is paid only for the queried function body and the tuples become unreachable after sorting. If profiling justifies improvement, use an index permutation or a custom stable parallel-list sort. Do not replace this transient cost with permanently retained entry objects.

---

## 14. Deferred Work and Open Questions

### 14.1 Equal-Offset Intermediate States

The initial query model exposes only the final state at an offset. Is there a demonstrated valid-code consumer for a state between multiple transitions sharing one boundary? If so, extend queries with structural boundary identity rather than another global offset convention.

### 14.2 Parser-Recovery Precision

Parser recovery can collapse several synthetic transitions onto one source position even though some of those transitions do not begin a real source interval. The initial design accepts best-effort types at such positions rather than complicating every query. If concrete completion regressions justify more precision, investigate suppressing or relocating transitions caused solely by synthetic exits before introducing a structurally anchored query.

### 14.3 Shared Boundary Factories

Analyzer and CFE use different higher-level syntax objects but share token infrastructure and flow analysis. The integer-backed boundary representation is fixed; implementation should determine the smallest reusable factory abstraction that validates ownership and coordinates without coupling `_fe_analyzer_shared` to analyzer AST classes.

### 14.4 Scope of Construct-Specific Groups

Typed roles are clearly justified for argument lists, conventional `for`, and pattern displacement. Simple constructs should continue passing a single boundary. The migration should not create a bespoke class for every flow operation or require a new group allocation for every construct.

### 14.5 Legacy Query Semantics

If the old public API must remain, should it retain the current explicitly documented left-biased behavior temporarily, or should it be deprecated immediately because callers are unlikely to choose that behavior intentionally? This is a release-management decision; the replacement remains unambiguously inclusive.

---

## 15. Decision Summary

The design adopts these decisions:

1. Keep integer offsets and values in parallel lists as the private `FlowAnalysisLog` representation; do not allocate per-transition entry objects or store a persistent sequence field.
2. Replace naked integer parameters in semantic recording APIs with allocation-free, structurally originated `FlowBoundary` extension-type values.
3. Define boundaries using normal half-open coordinates; do not compensate with `end - 1` or punctuation-specific arithmetic.
4. Make transitions visible at their exact offset; lookup returns the final entry at the greatest offset less than or equal to the query offset.
5. Encapsulate horizontal-inference discontinuity bookkeeping in a per-invocation session.
6. Use typed landmark groups for constructs whose source-order reconstruction requires several related boundaries.
7. Remove `offset = 0` defaults from logging-relevant APIs.
8. Keep semantic coverage in analyzer tests and use analysis-server tests only for representative valid-code completion behavior.

This keeps the efficient part of the current design—the sorted integer log—while moving boundary meaning and traversal repair into interfaces that can state and enforce them, and giving exact-position lookup one coherent rule.
