Skip to content

Compile contracts at weaving time, cache per-call work, evaluate only built-in contracts - #88

Open
lisachenko wants to merge 2 commits into
masterfrom
feature/jolly-babbage-0a1vs6
Open

lisachenko wants to merge 2 commits into
masterfrom
feature/jolly-babbage-0a1vs6

Conversation

@lisachenko

@lisachenko lisachenko commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Closes #76, closes #80, closes #84, closes #85. Covers the eval part of #81 (see the end).

#76: compiled contracts on PHP 8.5+

On PHP 8.5+, contract expressions are compiled while Go! AOP weaves the file. The compiled closure goes into the attribute, on the same source line:

#[Verify('$amount > $this->limit', check: static function ($__this, $amount, ...$__arguments) { return ($amount > $__this->limit); })]

Because the closure lives in the woven file, opcache caches it, it can be preloaded, and cache:warmup:aop builds it. Calls skip eval(), the per-call Closure::bind and extract(). A breakpoint on the contract line stops inside it. ReflectionFunction reports the user's source file and the attribute's line.

  • ContractRewriter (new): a PrefilteredNodeRewriter (marker PhpDeal), registered through addLazyService() in registerAspects(), on PHP 8.5+ only. It changes the token text only, so line numbers stay the same. It works with Go! AOP 4.0.0 and 5.x.
  • ContractCompiler (new): turns an expression into closure source with the same meaning it has under eval():
    • $this becomes $__this (AST Variable nodes only, so '$this' inside a string is left alone);
    • names become fully qualified, because expressions are written for the global namespace;
    • comments are dropped and newlines become spaces;
    • signatures: Verify gets ($__this, ...params, ...$__arguments), Ensure adds $__result = null, $__old = null before the variadic, Invariant gets ($__this, $__result = null, ...$__arguments). The trailing variadic takes the extra arguments of an overriding method;
    • the finished closure is parsed once more before it is written, because an invalid closure would break the whole woven file.
  • It stays on eval() whenever compiled code could behave differently:
    • a syntax error, or $this in a static method: both still throw InvalidContractException at call time;
    • static:: or self::method() in an instance context;
    • a nested function () {}, magic constants, variable variables;
    • compact(), extract() or get_defined_vars();
    • a newline inside a string literal;
    • an invariant that reads a variable other than $this and $__result.
  • Attributes: Verify, Ensure and Invariant get an optional ?Closure $check = null. PhpDeal fills it in; nobody writes it by hand.
  • ContractFetcher: the proxy re-declares attributes from the AST, so its copies have no closure. The fetcher reads them from the ...OriginalAlias method or the ...OriginalTrait instead.
  • BoundContract: binds the closure to its scope once, so interface contracts still run in the scope of the implementing class.

#80: per-call work is cached

Issue item Change
inheritsPreconditions() ran before the cache lookup; cache keys were built per call ContractFetcher answers with $cache[$method->class][$method->name] ??= .... No reflection call and no key concatenation on a hit.
getParameters() ran on every call, in each of the three aspects ContractEvaluator caches the parameter layout per method. A default that holds an object (new in an initializer) is still evaluated on every call, so it is never shared. Enum cases are cached.
new ReflectionObject($instance) for invariants and isCloneable() getInvariants() takes the class name. ContractEvaluator::cloneState() caches cloneability per class. BoundContract::$usesOldState is computed once.
$this regex per static call; $location built per call The $this check is cached per expression (see #84). The location string is built only when an exception is thrown.
Closure::bind per contract Gone for compiled contracts (#76). The eval cache uses nested arrays instead of string keys.

I skipped the optional item, sharing the argument map between the three aspects. The MethodInvocation object is reused across calls, so it is not a safe cache key, and with the cached layout the remaining cost is small.

#84: the $this check for static methods

The check now tokenizes the expression with PhpToken::tokenize() and looks for a T_VARIABLE $this, once per expression. '$this' inside a string literal no longer causes an InvalidContractException. On the compiled path, the AST already ignores string literals. A new fixture, Account::staticWithThisInString(), covers both paths.

#85: only built-in contracts reach eval()

  • BoundContract::$contract is now typed Verify|Ensure|Invariant, so no other Contract implementation can be evaluated.
  • The fetcher reads exactly these three classes, without IS_INSTANCEOF. A test checks that a custom attribute whose expression comes from getenv() is ignored.
  • The Contract interface and the README say that expressions are executed as PHP code and must be written in the source.
  • Compiled contracts come straight from the string literal in the source.

#81: what is covered and what is not

  • Covered: the eval part, about 3 µs per expression on every PHP-FPM request. Compiled contracts live in the woven files, which opcache caches.
  • Not covered: storing the contract metadata itself in an opcache-cached file. Reading a method's contracts still costs ≈2.9 µs on the first call of each request. Most of that is newInstance() (≈390 ns, since that is when the closure is created) and Closure::bind (≈140 ns). Both are needed to keep the closure on the user's source line, so a metadata file could only save the ancestor walk (≈0.7 µs per method per request). It would also need its own cache format and invalidation. I'd suggest a separate follow-up if that is still wanted.

Numbers

Local micro-benchmark, a full woven call including Go! AOP's interception (PHP 8.5, opcache on, JIT off):

Call master (eval) compiled (#76) + #80 caching
#[Verify] ≈2.8 µs ≈1.8 µs ≈1.0 µs
two #[Ensure] + $__old ≈3.5 µs ≈2.3 µs ≈1.5 µs

Tests

  • ContractCompilerTest, ContractRewriterTest (exact output, line by line) and CompiledContractTest (woven fixtures, RequiresPhp >= 8.5.0).
  • ContractEvaluatorTest: the compiled path, object defaults are not shared between calls, cloneState(), and $this inside a string in a static method.
  • ContractFetcherTest: other Contract implementations are ignored, $__old detection, and caching.
  • Locally, the full suite passes on the compiled path (214 tests). With the rewriter switched off, which is the eval path PHP 8.4 uses, 209 tests pass; the five excluded tests are the registration check and the four compiled-only tests. CI's 8.4 jobs cover that path.

Docs: README, CHANGELOG, the skill's references/expressions.md, and AGENTS.md.

🤖 Generated with Claude Code

https://claude.ai/code/session_01FxhC1EtLcA5S6bhb3s1f6Q

On PHP 8.5 a new Go! AOP NodeRewriter (ContractRewriter) adds the compiled
expression to every #[Verify], #[Ensure] and #[Invariant] as a static
closure in the new `check` argument, on the line of the attribute. The
woven file is cached by opcache, contracts run without eval(), and
breakpoints and stack traces point to the contract.

- ContractCompiler keeps the eval() semantics: $this becomes $__this, names
  are fully qualified, comments are dropped and newlines flattened so line
  numbers do not change. Expressions that could behave differently as a
  static closure are left to eval().
- ContractFetcher reads attributes from the ...OriginalAlias method or the
  ...OriginalTrait, since the proxy re-declares them without the closure.
- BoundContract binds the closure to the contract scope once, so interface
  and parent contracts keep their current scope.
- PHP 8.4, classes that are not woven and third-party Contract
  implementations keep using eval().

Closes #76

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FxhC1EtLcA5S6bhb3s1f6Q
@lisachenko
lisachenko marked this pull request as ready for review November 10, 2026 22:08
…uilt-in contracts

- ContractFetcher answers from nested per-class caches before any reflection
  call, and looks invariants up by class name (#80).
- ContractEvaluator caches the parameter layout of a method (a default
  created with `new` is still evaluated on every call), the cloneability of
  a class and the eval() closures, and builds the error location only when
  it throws (#80). BoundContract precomputes whether `$__old` is used.
- The `$this` check for static methods tokenizes the expression once, so
  `$this` inside a string literal is no longer rejected (#84).
- BoundContract accepts only Verify, Ensure and Invariant, and the fetcher
  reads only those classes: no computed expression can reach eval(). The
  Contract interface documents that expressions must come from the source
  (#85).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FxhC1EtLcA5S6bhb3s1f6Q
@lisachenko lisachenko changed the title Compile contract expressions into the woven classes on PHP 8.5+ Compile contracts at weaving time, cache per-call work, evaluate only built-in contracts Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants