Repository navigation
Compile contracts at weaving time, cache per-call work, evaluate only built-in contracts - #88
Open
lisachenko wants to merge 2 commits into
Open
lisachenko wants to merge 2 commits into
lisachenko wants to merge 2 commits into
Conversation
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
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #76, closes #80, closes #84, closes #85. Covers the
evalpart 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:
Because the closure lives in the woven file, opcache caches it, it can be preloaded, and
cache:warmup:aopbuilds it. Calls skipeval(), the per-callClosure::bindandextract(). A breakpoint on the contract line stops inside it.ReflectionFunctionreports the user's source file and the attribute's line.ContractRewriter(new): aPrefilteredNodeRewriter(markerPhpDeal), registered throughaddLazyService()inregisterAspects(), 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 undereval():$thisbecomes$__this(ASTVariablenodes only, so'$this'inside a string is left alone);Verifygets($__this, ...params, ...$__arguments),Ensureadds$__result = null, $__old = nullbefore the variadic,Invariantgets($__this, $__result = null, ...$__arguments). The trailing variadic takes the extra arguments of an overriding method;eval()whenever compiled code could behave differently:$thisin a static method: both still throwInvalidContractExceptionat call time;static::orself::method()in an instance context;function () {}, magic constants, variable variables;compact(),extract()orget_defined_vars();$thisand$__result.Verify,EnsureandInvariantget 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...OriginalAliasmethod or the...OriginalTraitinstead.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
inheritsPreconditions()ran before the cache lookup; cache keys were built per callContractFetcheranswers 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 aspectsContractEvaluatorcaches the parameter layout per method. A default that holds an object (newin an initializer) is still evaluated on every call, so it is never shared. Enum cases are cached.new ReflectionObject($instance)for invariants andisCloneable()getInvariants()takes the class name.ContractEvaluator::cloneState()caches cloneability per class.BoundContract::$usesOldStateis computed once.$thisregex per static call;$locationbuilt per call$thischeck is cached per expression (see #84). The location string is built only when an exception is thrown.Closure::bindper contractevalcache uses nested arrays instead of string keys.I skipped the optional item, sharing the argument map between the three aspects. The
MethodInvocationobject is reused across calls, so it is not a safe cache key, and with the cached layout the remaining cost is small.#84: the
$thischeck for static methodsThe check now tokenizes the expression with
PhpToken::tokenize()and looks for aT_VARIABLE$this, once per expression.'$this'inside a string literal no longer causes anInvalidContractException. 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::$contractis now typedVerify|Ensure|Invariant, so no otherContractimplementation can be evaluated.IS_INSTANCEOF. A test checks that a custom attribute whose expression comes fromgetenv()is ignored.Contractinterface and the README say that expressions are executed as PHP code and must be written in the source.#81: what is covered and what is not
evalpart, about 3 µs per expression on every PHP-FPM request. Compiled contracts live in the woven files, which opcache caches.newInstance()(≈390 ns, since that is when the closure is created) andClosure::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):
eval)#[Verify]#[Ensure]+$__oldTests
ContractCompilerTest,ContractRewriterTest(exact output, line by line) andCompiledContractTest(woven fixtures,RequiresPhp >= 8.5.0).ContractEvaluatorTest: the compiled path, object defaults are not shared between calls,cloneState(), and$thisinside a string in a static method.ContractFetcherTest: otherContractimplementations are ignored,$__olddetection, and caching.evalpath 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