From 21667e78e334f70429215ae29413bcd03fbc9dcf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 22:01:39 +0000 Subject: [PATCH 1/2] Compile contract expressions into the woven classes on PHP 8.5+ 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 Claude-Session: https://claude.ai/code/session_01FxhC1EtLcA5S6bhb3s1f6Q --- AGENTS.md | 10 +- CHANGELOG.md | 4 + README.md | 32 ++- .../references/expressions.md | 7 +- src/Attribute/Ensure.php | 10 +- src/Attribute/Invariant.php | 10 +- src/Attribute/Verify.php | 10 +- src/Contract/BoundContract.php | 17 +- src/Contract/ContractCompiler.php | 242 ++++++++++++++++++ src/Contract/ContractEvaluator.php | 48 ++-- src/Contract/ContractFetcher.php | 31 ++- src/Contract/ContractRewriter.php | 133 ++++++++++ src/ContractApplication.php | 8 +- tests/Functional/CompiledContractTest.php | 90 +++++++ tests/Unit/Contract/ContractCompilerTest.php | 107 ++++++++ tests/Unit/Contract/ContractEvaluatorTest.php | 37 +++ tests/Unit/Contract/ContractRewriterTest.php | 119 +++++++++ tests/Unit/ContractApplicationTest.php | 15 +- 18 files changed, 891 insertions(+), 39 deletions(-) create mode 100644 src/Contract/ContractCompiler.php create mode 100644 src/Contract/ContractRewriter.php create mode 100644 tests/Functional/CompiledContractTest.php create mode 100644 tests/Unit/Contract/ContractCompilerTest.php create mode 100644 tests/Unit/Contract/ContractRewriterTest.php diff --git a/AGENTS.md b/AGENTS.md index 49324be..61e43b9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,7 +37,9 @@ lowest-dependencies job and `composer audit`. | `src/Attribute/` | The attributes. `Verify`, `Ensure`, `Invariant` implement the `Contract` interface (`$expression`). | | `src/Aspect/` | One Go! AOP aspect per contract kind. The pointcuts are in their advice attributes. | | `src/Contract/ContractFetcher.php` | Collects contracts from the method/class and its parents and interfaces, with caching. | -| `src/Contract/ContractEvaluator.php` | Compiles expressions to closures (once), binds them to the object/scope, evaluates them. | +| `src/Contract/ContractEvaluator.php` | Evaluates contracts: calls compiled closures, or compiles expressions with `eval()` (once) and binds them. | +| `src/Contract/ContractRewriter.php` | Go! AOP `NodeRewriter` (PHP 8.5+): adds the compiled closure as `check:` to contract attributes while weaving. | +| `src/Contract/ContractCompiler.php` | Turns an expression into the source of a static closure, or `null` when it must stay on `eval()`. | | `src/Contract/BoundContract.php` | A contract plus the class scope its expression runs in. | | `src/Contract/ContractKind.php` | Enum that maps a check to its violation exception. | | `src/Exception/` | `ContractViolation` and its subclasses, `InvalidContractException`, `ExceptionInterface`. | @@ -70,6 +72,12 @@ lowest-dependencies job and `composer audit`. - `true` or `null` means it holds (`null` exists for assertion libraries). - Any other result, a `ParseError`, or `$this` in a static method throws `InvalidContractException`. - A `Throwable` thrown by the expression becomes the `previous` exception of a violation. +- **Compiled contracts (PHP 8.5+).** `ContractRewriter` appends `check: static function ($__this, ...) {...}` to the + attribute in the token stream, on the same line (comments dropped, newlines flattened, names fully qualified, + `$this` → `$__this`). The proxy re-declares attributes from the AST without `check`, so `ContractFetcher` reads them + from the `...OriginalAlias` method or the `...OriginalTrait`. `BoundContract` binds the closure to its scope once. + `ContractCompiler` returns `null` for anything that could behave differently than in `eval()`; keep it conservative, + an invalid closure breaks the whole woven file. - **Recursion guard.** While an expression is evaluated, `ContractEvaluator::isEvaluating()` is true and every aspect skips its checks. This lets an invariant call public methods of its own class. - **Woven classes.** Go! AOP 4 turns the original class body into a `OriginalTrait`, and the proxy keeps the diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e0f24e..5854bb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,10 @@ specifications into contracted code and tests. See [UPGRADE-2.0.md](UPGRADE-2.0. PHPUnit tests derived from the contracts. It is installable as a Claude Code plugin from this repository (`/plugin marketplace add php-deal/framework`) (#36). - Static checker for contract expressions, `skills/design-by-contract/scripts/lint-contracts.php`. +- On PHP 8.5+ contract expressions are compiled into static closures while Go! AOP weaves the class, on the line of + the attribute (new `check` argument of `#[Verify]`, `#[Ensure]` and `#[Invariant]`, filled in by PhpDeal). They are + cached by opcache, run without `eval()`, and breakpoints and stack traces point to the contract. Expressions that + could behave differently as a static closure, and PHP 8.4, keep using `eval()` (#76). ### Changed diff --git a/README.md b/README.md index 32b35df..c40bcf7 100644 --- a/README.md +++ b/README.md @@ -240,8 +240,9 @@ random values, and `\in_array()` without strict comparison. - 🧬 **Contract inheritance** from parent classes and interfaces, with clear and predictable rules. - 🔒 **Full access to the object**: expressions run in the scope of the class and can read private state. - 🕰️ **`$__old` and `$__result`** to compare the state before and after a call, and to check return values. -- ⚡ **Fast**: each expression is compiled once, contracts are read once per class, and the object is cloned only when - a contract uses `$__old`. +- ⚡ **Fast**: on PHP 8.5+ contracts are compiled into the woven classes, so opcache caches them and no `eval()` runs; + contracts are read once per class, and the object is cloned only when a contract uses `$__old`. +- 🐞 **Debuggable**: on PHP 8.5+ a breakpoint on a contract line stops in the contract, and stack traces point to it. - 🔁 **Recursion-safe**: an invariant may call public methods of its own class. - 🧩 **Works with assertion libraries** such as [beberlei/assert](https://github.com/beberlei/assert). - 🔍 **PHPStan extension** included: properties and methods used only by contracts are not reported as unused. @@ -475,8 +476,8 @@ violated. Returning `null` is accepted too, for assertion helpers that return no - **Scope.** The expression runs in the scope of the class that declares it, so it can read private and protected members with `$this->`, `self::` and `static::`. Contracts of an interface run in the scope of the implementing class. Static methods have no `$this`. -- **Names.** The expression is compiled outside of your file, so `use` imports do not apply: write class and function - names fully qualified, e.g. `'\App\Money::isValid($amount)'` or `'Assert\Assertion::email($email)'`. +- **Names.** The expression is written for the global namespace, so `use` imports do not apply: write class and + function names fully qualified, e.g. `'\App\Money::isValid($amount)'` or `'Assert\Assertion::email($email)'`. - **Errors.** An error or exception thrown by the expression is reported as a violation of the contract, with the original error as the previous exception. Assertion libraries can be used that way: @@ -488,6 +489,26 @@ public function setDiscount(int $percent): void {} - **Mistakes in contracts.** A syntax error, a `$this` in a static method or a result that is neither a boolean nor `null` throws an `InvalidContractException`: this is a bug in the contract itself, not a violation of it. +### Compiled contracts (PHP 8.5+) + +On PHP 8.5 and newer, PhpDeal compiles every expression into a static closure while Go! AOP weaves the class, and +adds it to the attribute on the same line. The woven cache file contains, for example: + +```php +#[Verify('$amount > 0', check: static function ($__this, $amount, ...$__arguments) { return ($amount > 0); })] +``` + +You never write `check:` yourself. Compiled contracts are cached by opcache, can be preloaded, and run without +`eval()`, so they also work on hosts that forbid it. A breakpoint on the line of a contract stops inside it, and an +error raised by the expression points to that line. The cache is built by `cache:warmup:aop` as usual. + +An expression is evaluated with `eval()` instead, as on PHP 8.4, when it could behave differently as a static closure: +a syntax error or `$this` in a static method (both still throw `InvalidContractException` when the method is called), +`static::` or `self::method()` in an instance context, a nested `function () {}`, magic constants such as `__CLASS__`, +variable variables, `compact()`/`extract()`/`get_defined_vars()`, a newline inside a string literal, and an +invariant that reads a variable other than `$this` and `$__result`. Classes that are not woven, and `Contract` +implementations of other packages, use `eval()` too. + ## Handling violations Every exception of PhpDeal implements `PhpDeal\Exception\ExceptionInterface`: @@ -543,7 +564,8 @@ if (($_SERVER['APP_ENV'] ?? 'prod') !== 'prod') { Without the kernel the attributes are plain metadata, and your classes run untouched. If you keep contracts in production, set `'debug' => false` and warm up the cache at deploy time, see the -[Go! AOP deployment guide](https://github.com/goaop/framework/blob/master/docs/configuration.md). +[Go! AOP deployment guide](https://github.com/goaop/framework/blob/master/docs/configuration.md). Build the cache +with the PHP version that runs it: a cache woven on PHP 8.5 holds closures in attributes, which PHP 8.4 can not load. ## Upgrading from 1.x diff --git a/skills/design-by-contract/references/expressions.md b/skills/design-by-contract/references/expressions.md index 7ea357d..95f51d3 100644 --- a/skills/design-by-contract/references/expressions.md +++ b/skills/design-by-contract/references/expressions.md @@ -1,7 +1,8 @@ # Contract expressions -A contract is one PHP expression in a string. PhpDeal compiles it once into a closure and binds the closure to the -object, in the scope of the class that declares the contract. +A contract is one PHP expression in a string. PhpDeal compiles it into a closure that runs in the scope of the class +that declares the contract. On PHP 8.5+ the closure is written into the woven class (the `check:` argument of the +attribute), on PHP 8.4 it is compiled with `eval()` at run time. Never write `check:` yourself. ## Contents @@ -41,7 +42,7 @@ there: an invariant describes the object alone. - The expression can read private and protected members of the declaring class: `$this->balance`, `$this->isValid($x)`, `self::LIMIT`, `static::$registry`. A contract of an interface runs in the scope of the implementing class. A contract of a parent class runs in the scope of the parent and can read its private state. -- The expression is compiled outside of your file, in the global namespace. `use` imports do **not** apply: +- The expression is written for the global namespace. `use` imports do **not** apply: - classes, enums and interfaces are fully qualified: `$status === \App\Order\Status::Paid`, `$at instanceof \DateTimeImmutable`; - functions get a leading backslash: `\count()`, `\in_array($x, self::ALLOWED, true)`, `\preg_match(...)`; diff --git a/src/Attribute/Ensure.php b/src/Attribute/Ensure.php index 8e6d914..9d91ba1 100644 --- a/src/Attribute/Ensure.php +++ b/src/Attribute/Ensure.php @@ -14,6 +14,7 @@ namespace PhpDeal\Attribute; use Attribute; +use Closure; /** * Post-condition: a promise of the method, checked after the method body has returned. @@ -27,7 +28,12 @@ final readonly class Ensure implements Contract { /** - * @param string $expression PHP expression that must evaluate to true + * @param string $expression PHP expression that must evaluate to true + * @param Closure|null $check The expression compiled into a static closure. PhpDeal writes it into the woven + * class on PHP 8.5+, it is not meant to be written by hand */ - public function __construct(public string $expression) {} + public function __construct( + public string $expression, + public ?Closure $check = null, + ) {} } diff --git a/src/Attribute/Invariant.php b/src/Attribute/Invariant.php index 05d7931..c6390a4 100644 --- a/src/Attribute/Invariant.php +++ b/src/Attribute/Invariant.php @@ -14,6 +14,7 @@ namespace PhpDeal\Attribute; use Attribute; +use Closure; /** * Class invariant: a condition that holds after the constructor and after every public method call. @@ -26,7 +27,12 @@ final readonly class Invariant implements Contract { /** - * @param string $expression PHP expression that must evaluate to true + * @param string $expression PHP expression that must evaluate to true + * @param Closure|null $check The expression compiled into a static closure. PhpDeal writes it into the woven + * class on PHP 8.5+, it is not meant to be written by hand */ - public function __construct(public string $expression) {} + public function __construct( + public string $expression, + public ?Closure $check = null, + ) {} } diff --git a/src/Attribute/Verify.php b/src/Attribute/Verify.php index 8a6a4ee..f4f32c9 100644 --- a/src/Attribute/Verify.php +++ b/src/Attribute/Verify.php @@ -14,6 +14,7 @@ namespace PhpDeal\Attribute; use Attribute; +use Closure; /** * Pre-condition: a requirement upon the caller, checked before the method body runs. @@ -26,7 +27,12 @@ final readonly class Verify implements Contract { /** - * @param string $expression PHP expression that must evaluate to true + * @param string $expression PHP expression that must evaluate to true + * @param Closure|null $check The expression compiled into a static closure. PhpDeal writes it into the woven + * class on PHP 8.5+, it is not meant to be written by hand */ - public function __construct(public string $expression) {} + public function __construct( + public string $expression, + public ?Closure $check = null, + ) {} } diff --git a/src/Contract/BoundContract.php b/src/Contract/BoundContract.php index 07ca539..bb83293 100644 --- a/src/Contract/BoundContract.php +++ b/src/Contract/BoundContract.php @@ -13,7 +13,11 @@ namespace PhpDeal\Contract; +use Closure; use PhpDeal\Attribute\Contract; +use PhpDeal\Attribute\Ensure; +use PhpDeal\Attribute\Invariant; +use PhpDeal\Attribute\Verify; /** * A contract together with the class scope its expression is evaluated in @@ -23,6 +27,11 @@ */ final readonly class BoundContract { + /** + * Compiled expression bound to the scope, null when the expression is evaluated with eval() + */ + public ?Closure $check; + /** * @param Contract $contract Contract attribute * @param class-string $scope Class scope for the expression @@ -30,5 +39,11 @@ public function __construct( public Contract $contract, public string $scope, - ) {} + ) { + // Contract implementations of other packages are always evaluated with eval() + $isCompilable = $contract instanceof Verify || $contract instanceof Ensure || $contract instanceof Invariant; + $check = $isCompilable ? $contract->check : null; + // The closure is declared in the woven trait or the interface, it must run in the scope of the contract + $this->check = $check !== null ? Closure::bind($check, null, $scope) : null; + } } diff --git a/src/Contract/ContractCompiler.php b/src/Contract/ContractCompiler.php new file mode 100644 index 0000000..56f02b8 --- /dev/null +++ b/src/Contract/ContractCompiler.php @@ -0,0 +1,242 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Contract; + +use PhpParser\Error; +use PhpParser\Node; +use PhpParser\Node\Expr\ArrowFunction; +use PhpParser\Node\Expr\Closure; +use PhpParser\Node\Expr\FuncCall; +use PhpParser\Node\Expr\StaticCall; +use PhpParser\Node\Expr\Variable; +use PhpParser\Node\Name; +use PhpParser\Node\Scalar\MagicConst; +use PhpParser\Node\Stmt\Expression; +use PhpParser\Node\Stmt\Return_; +use PhpParser\NodeFinder; +use PhpParser\Parser; +use PhpParser\ParserFactory; +use PhpParser\Token; + +/** + * Compiles a contract expression into the source code of a static closure + * + * The closure takes the object as `$__this`, then the variables of the contract by name. It is written into the + * attribute while Go! AOP weaves the class, so it is cached by opcache and needs no `eval()`. The code keeps the + * meaning the expression has in `eval()`: + * - `$this` becomes `$__this`, because a closure in an attribute must be static; + * - names are fully qualified, because the expression is written for the global namespace without imports; + * - comments are removed and newlines become spaces, so the woven file keeps the line numbers of the source. + * + * An expression that could behave differently as a static closure is not compiled, and is evaluated at run time. + * + * @internal Used by {@see ContractRewriter} + */ +final class ContractCompiler +{ + private const string PREFIX = '|null $parameters Parameter names of the method, or null for a class invariant + * @param bool $isStatic Whether the method is static + * @param bool $withResult Whether `$__result` and `$__old` are passed (post-conditions) + */ + public function compile(string $expression, ?array $parameters, bool $isStatic, bool $withResult): ?string + { + $signature = $this->buildSignature($parameters, $withResult); + if ($signature === null) { + return null; + } + $code = self::PREFIX . $expression . self::SUFFIX; + try { + $statements = $this->getParser()->parse($code); + } catch (Error) { + // Syntax errors are reported by the run time evaluation, with the contract and the method + return null; + } + if ($statements === null || \count($statements) !== 1 || !$statements[0] instanceof Return_) { + return null; + } + $tokens = $this->getParser()->getTokens(); + $edits = $this->collectEdits($statements[0], $parameters === null, $isStatic); + if ($edits === null) { + return null; + } + + $body = ''; + foreach ($tokens as $position => $token) { + // The parser ends the list with a sentinel token + if ($token->id !== 0) { + $body .= $edits[$position] ?? self::flatten($token); + } + } + $body = \rtrim(\substr($body, \strlen(self::PREFIX), -\strlen(\ltrim(self::SUFFIX)))); + // A newline inside a string literal can not be flattened, it would shift the lines of the file + if (\str_contains($body, "\n") || \str_contains($body, "\r")) { + return null; + } + + $closure = 'static function (' . $signature . ') { return (' . $body . '); }'; + + // An invalid closure would break the whole woven file, so it is checked once more + return $this->isSingleClosure($closure) ? $closure : null; + } + + private function isSingleClosure(string $code): bool + { + try { + $statements = $this->getParser()->parse('expr instanceof Closure && $statements[0]->expr->static; + } + + /** + * @param list|null $parameters + */ + private function buildSignature(?array $parameters, bool $withResult): ?string + { + if ($parameters === null) { + // Invariants are evaluated with the arguments of whichever method ran, they are not part of the closure + return '$__this, $__result = null, ...$__arguments'; + } + $reserved = ['__this', '__result', '__old', '__arguments']; + if (\array_intersect($parameters, $reserved) !== []) { + return null; + } + $signature = ['$__this']; + foreach ($parameters as $parameter) { + $signature[] = '$' . $parameter; + } + if ($withResult) { + $signature[] = '$__result = null'; + $signature[] = '$__old = null'; + } + // Absorbs arguments of an overriding method that declares more parameters + $signature[] = '...$__arguments'; + + return \implode(', ', $signature); + } + + /** + * Returns the replacement text for tokens, by token position, or null if the expression can not be compiled + * + * @return array|null + */ + private function collectEdits(Return_ $statement, bool $isInvariant, bool $isStatic): ?array + { + $edits = []; + $finder = new NodeFinder(); + $nodes = $finder->find([$statement], static fn(): bool => true); + // Parameters of arrow functions are local to the expression + $localVariables = []; + foreach ($nodes as $node) { + if ($node instanceof ArrowFunction) { + foreach ($node->params as $param) { + if ($param->var instanceof Variable && \is_string($param->var->name)) { + $localVariables[$param->var->name] = true; + } + } + } + } + + foreach ($nodes as $node) { + if (!self::isCompilable($node, $isInvariant, $isStatic, $localVariables)) { + return null; + } + if ($node instanceof Variable && $node->name === 'this') { + $edits[$node->getStartTokenPos()] = '$__this'; + } elseif ($node instanceof Name && !$node instanceof Name\FullyQualified && !self::isKeyword($node)) { + $edits[$node->getStartTokenPos()] = '\\' . $node->toString(); + } + } + + return $edits; + } + + /** + * Checks that a node means the same in a static closure as in a closure bound to the object + * + * @param array $localVariables + */ + private static function isCompilable(Node $node, bool $isInvariant, bool $isStatic, array $localVariables): bool + { + if ($node instanceof Variable) { + if (!\is_string($node->name) || $node->name === '__this' || ($isStatic && $node->name === 'this')) { + return false; + } + // An invariant may only use the object and the result: other variables come from the called method + if ($isInvariant && !\in_array($node->name, ['this', '__result'], true) && !isset($localVariables[$node->name])) { + return false; + } + } + // `static` is the class of the object only in a closure bound to it, and self::method() may forward $this + if (!$isStatic) { + if ($node instanceof Name && $node->toLowerString() === 'static') { + return false; + } + if ($node instanceof StaticCall && $node->class instanceof Name && $node->class->isSpecialClassName()) { + return false; + } + } + if ($node instanceof FuncCall && $node->name instanceof Name + && \in_array($node->name->toLowerString(), self::SCOPE_FUNCTIONS, true) + ) { + return false; + } + + // A closure would need `$this`, magic constants describe the place of the code + return !$node instanceof Closure && !$node instanceof MagicConst; + } + + /** + * `self`, `parent`, `static`, `true`, `false` and `null` keep their meaning without a leading backslash + */ + private static function isKeyword(Name $name): bool + { + return $name->isSpecialClassName() || \in_array($name->toLowerString(), ['true', 'false', 'null'], true); + } + + /** + * Removes comments and replaces newlines in whitespace, so the closure takes a single line + */ + private static function flatten(Token $token): string + { + return match ($token->id) { + \T_COMMENT, \T_DOC_COMMENT => ' ', + \T_WHITESPACE => \str_replace(["\r\n", "\r", "\n"], ' ', $token->text), + default => $token->text, + }; + } + + private function getParser(): Parser + { + return $this->parser ??= new ParserFactory()->createForHostVersion(); + } +} diff --git a/src/Contract/ContractEvaluator.php b/src/Contract/ContractEvaluator.php index 02c0975..311ee75 100644 --- a/src/Contract/ContractEvaluator.php +++ b/src/Contract/ContractEvaluator.php @@ -21,9 +21,10 @@ use Throwable; /** - * Compiles contract expressions into closures and evaluates them for a method invocation + * Evaluates contracts for a method invocation * - * Every expression is compiled once per process. While a contract is evaluated, contracts of nested calls are not + * Contracts compiled while the class was woven (PHP 8.5+, see {@see ContractRewriter}) are called directly. Other + * expressions are compiled with eval() into closures, once per process. While a contract is evaluated, contracts of nested calls are not * checked, so an invariant may call public methods of its own class without recursing endlessly. */ final class ContractEvaluator @@ -82,23 +83,12 @@ public function check(MethodInvocation $invocation, array $contracts, array $var $location = $invocation->getMethod()->class . '::' . $invocation->getMethod()->name . '()'; foreach ($contracts as $boundContract) { $expression = $boundContract->contract->expression; - $isStatic = $instance === null; - if ($isStatic && \preg_match('/\$this\b/', $expression) === 1) { - throw InvalidContractException::forStaticContext($expression, $location); - } - try { - $closure = $this->compile($expression, $isStatic); - } catch (ParseError $error) { - throw InvalidContractException::forSyntaxError($expression, $location, $error); - } - $evaluator = Closure::bind($closure, $instance, $boundContract->scope); - if ($evaluator === null) { - throw InvalidContractException::forStaticContext($expression, $location); - } + $evaluator = $boundContract->check ?? $this->bindExpression($boundContract, $instance, $location); ++$this->depth; try { - $result = $evaluator($variables); + // A compiled contract takes the object first, then the variables by name + $result = $boundContract->check !== null ? $evaluator($instance, ...$variables) : $evaluator($variables); } catch (Throwable $error) { // Assertion libraries signal failures with exceptions, broken expressions with errors throw $kind->createViolation($invocation, $expression, $error); @@ -116,6 +106,32 @@ public function check(MethodInvocation $invocation, array $contracts, array $var } } + /** + * Compiles the expression with eval() and binds it to the object, for contracts that were not compiled while + * the class was woven + * + * @throws InvalidContractException When the expression is not valid PHP or uses $this in a static method + */ + private function bindExpression(BoundContract $boundContract, ?object $instance, string $location): Closure + { + $expression = $boundContract->contract->expression; + $isStatic = $instance === null; + if ($isStatic && \preg_match('/\$this\b/', $expression) === 1) { + throw InvalidContractException::forStaticContext($expression, $location); + } + try { + $closure = $this->compile($expression, $isStatic); + } catch (ParseError $error) { + throw InvalidContractException::forSyntaxError($expression, $location, $error); + } + $evaluator = Closure::bind($closure, $instance, $boundContract->scope); + if ($evaluator === null) { + throw InvalidContractException::forStaticContext($expression, $location); + } + + return $evaluator; + } + /** * @return Closure(array): mixed * diff --git a/src/Contract/ContractFetcher.php b/src/Contract/ContractFetcher.php index 48369ee..c769a71 100644 --- a/src/Contract/ContractFetcher.php +++ b/src/Contract/ContractFetcher.php @@ -13,7 +13,9 @@ namespace PhpDeal\Contract; +use Go\Aop\Framework\AbstractMethodInvocation; use Go\Aop\Proxy; +use Go\Core\AspectContainer; use PhpDeal\Attribute\Contract; use PhpDeal\Attribute\Ensure; use PhpDeal\Attribute\Inherit; @@ -160,10 +162,37 @@ private static function readContracts(ReflectionClass|ReflectionMethod $reflecto { return \array_map( static fn(ReflectionAttribute $attribute): BoundContract => new BoundContract($attribute->newInstance(), $scope), - $reflector->getAttributes($type, ReflectionAttribute::IS_INSTANCEOF), + self::getOriginalDeclaration($reflector)->getAttributes($type, ReflectionAttribute::IS_INSTANCEOF), ); } + /** + * Returns the declaration written in the source, which holds the contracts compiled while weaving + * + * Go! AOP moves the body of a woven class into its `...OriginalTrait` and re-declares the attributes on the proxy + * from the syntax tree, without the compiled closures. The trait and the `...OriginalAlias` methods keep them. + * + * @param ReflectionClass|ReflectionMethod $reflector + * + * @return ReflectionClass|ReflectionMethod + */ + private static function getOriginalDeclaration(ReflectionClass|ReflectionMethod $reflector): ReflectionClass|ReflectionMethod + { + if ($reflector instanceof ReflectionClass) { + return $reflector->getTraits()[$reflector->name . AspectContainer::ORIGINAL_TRAIT_SUFFIX] ?? $reflector; + } + $class = $reflector->getDeclaringClass(); + $aliasName = $reflector->name . AbstractMethodInvocation::TRAIT_ALIAS_SUFFIX; + if ($class->hasMethod($aliasName)) { + $alias = $class->getMethod($aliasName); + if ($alias->getDeclaringClass()->name === $class->name) { + return $alias; + } + } + + return $reflector; + } + /** * Removes repeated expressions, the first (most specific) occurrence wins * diff --git a/src/Contract/ContractRewriter.php b/src/Contract/ContractRewriter.php new file mode 100644 index 0000000..16de746 --- /dev/null +++ b/src/Contract/ContractRewriter.php @@ -0,0 +1,133 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +namespace PhpDeal\Contract; + +use Go\Instrument\Transformer\PrefilteredNodeRewriter; +use Go\Instrument\Transformer\StreamMetaData; +use PhpDeal\Attribute\Ensure; +use PhpDeal\Attribute\Invariant; +use PhpDeal\Attribute\Verify; +use PhpParser\Node; +use PhpParser\Node\Attribute; +use PhpParser\Node\Expr\Variable; +use PhpParser\Node\Name; +use PhpParser\Node\Scalar\String_; +use PhpParser\Node\Stmt\ClassLike; +use PhpParser\Node\Stmt\ClassMethod; + +/** + * Compiles contract expressions into closures while Go! AOP weaves a file (PHP 8.5+) + * + * The closure is added to the attribute as the `check` argument, on the line of the expression: + * + * #[Verify('$amount > 0', check: static function ($__this, $amount, ...$__arguments) { return ($amount > 0); })] + * + * The woven file is cached by opcache, contracts run without `eval()`, and breakpoints and stack traces point to the + * line of the contract. Go! AOP keeps the rewritten declarations in the `...OriginalTrait` of a woven class, where + * {@see ContractFetcher} reads them. + * + * @internal Registered by {@see \PhpDeal\ContractApplication::registerAspects()} + */ +final class ContractRewriter implements PrefilteredNodeRewriter +{ + /** + * Contract attributes and whether their closure gets `$__result` and `$__old` + */ + private const array CONTRACTS = [ + Verify::class => false, + Ensure::class => true, + Invariant::class => true, + ]; + + public array $nodeTypes { + get => [Attribute::class]; + } + + /** + * A contract attribute is always written with the namespace of PhpDeal: in an import, in the name or in the + * namespace of the file + */ + public array $sourceMarkers { + get => ['PhpDeal']; + } + + public function __construct( + private readonly ContractCompiler $compiler = new ContractCompiler(), + ) {} + + public function rewriteNode(Node $node, StreamMetaData $file, array $ancestors): bool + { + if (!$node instanceof Attribute || \count($ancestors) < 2) { + return false; + } + $type = self::resolveName($node->name); + if ($type === null || !isset(self::CONTRACTS[$type]) || \count($node->args) !== 1) { + return false; + } + $argument = $node->args[0]; + if ($argument->unpack || !$argument->value instanceof String_ + || ($argument->name !== null && $argument->name->toString() !== 'expression') + ) { + return false; + } + + $target = $ancestors[\count($ancestors) - 2]; + if ($type === Invariant::class && $target instanceof ClassLike) { + $closure = $this->compiler->compile($argument->value->value, null, false, true); + } elseif ($type !== Invariant::class && $target instanceof ClassMethod) { + $parameters = self::getParameterNames($target); + $closure = $parameters !== null + ? $this->compiler->compile($argument->value->value, $parameters, $target->isStatic(), self::CONTRACTS[$type]) + : null; + } else { + return false; + } + + $endPosition = $argument->value->getEndTokenPos(); + if ($closure === null || !isset($file->tokenStream[$endPosition])) { + return false; + } + $file->tokenStream[$endPosition]->text .= ', check: ' . $closure; + + return true; + } + + private static function resolveName(Name $name): ?string + { + $resolved = $name->getAttribute('resolvedName'); + if ($resolved instanceof Name) { + $name = $resolved; + } elseif (!$name instanceof Name\FullyQualified) { + return null; + } + + return $name->toString(); + } + + /** + * @return list|null + */ + private static function getParameterNames(ClassMethod $method): ?array + { + $names = []; + foreach ($method->params as $param) { + if (!$param->var instanceof Variable || !\is_string($param->var->name)) { + return null; + } + $names[] = $param->var->name; + } + + return $names; + } +} diff --git a/src/ContractApplication.php b/src/ContractApplication.php index 41aacf0..fce94e0 100644 --- a/src/ContractApplication.php +++ b/src/ContractApplication.php @@ -20,6 +20,7 @@ use PhpDeal\Aspect\PreconditionCheckerAspect; use PhpDeal\Contract\ContractEvaluator; use PhpDeal\Contract\ContractFetcher; +use PhpDeal\Contract\ContractRewriter; /** * Aspect kernel that enables Design by Contract checks @@ -40,7 +41,8 @@ class ContractApplication extends AspectKernel /** * Registers the contract aspects in an aspect container * - * Call it from `configureAop()` of your own aspect kernel to combine contracts with other aspects. + * On PHP 8.5+ it also registers {@see ContractRewriter}, which compiles the contract expressions into the woven + * classes. Call it from `configureAop()` of your own aspect kernel to combine contracts with other aspects. */ public static function registerAspects(AspectContainer $container): void { @@ -59,6 +61,10 @@ public static function registerAspects(AspectContainer $container): void InvariantCheckerAspect::class, static fn(): InvariantCheckerAspect => new InvariantCheckerAspect($fetcher, $evaluator), ); + // Closures in attributes need PHP 8.5, older versions evaluate the expressions with eval() + if (\PHP_VERSION_ID >= 80500) { + $container->addLazyService(ContractRewriter::class, static fn(): ContractRewriter => new ContractRewriter()); + } } protected function configureAop(AspectContainer $container): void diff --git a/tests/Functional/CompiledContractTest.php b/tests/Functional/CompiledContractTest.php new file mode 100644 index 0000000..3144b79 --- /dev/null +++ b/tests/Functional/CompiledContractTest.php @@ -0,0 +1,90 @@ += 8.5.0')] +final class CompiledContractTest extends TestCase +{ + private ContractFetcher $fetcher; + + protected function setUp(): void + { + $this->fetcher = new ContractFetcher(); + } + + public function testPreconditionIsCompiledOnTheLineOfTheAttribute(): void + { + [$contract] = $this->fetcher->getPreconditions(new ReflectionMethod(Account::class, 'aboveLimit')); + + self::assertNotNull($contract->check); + $closure = new ReflectionFunction($contract->check); + self::assertSame(self::findLine('Verify/Account.php', "#[Verify('\$amount > \$this->limit')]"), $closure->getStartLine()); + self::assertSame(Account::class, $closure->getClosureScopeClass()?->name); + } + + public function testInterfaceContractRunsInTheScopeOfTheImplementingClass(): void + { + $contracts = $this->fetcher->getPostconditions(new ReflectionMethod(InterfaceCounter::class, 'add')); + + self::assertCount(3, $contracts); + foreach ($contracts as $contract) { + self::assertNotNull($contract->check); + self::assertSame(InterfaceCounter::class, new ReflectionFunction($contract->check)->getClosureScopeClass()?->name); + } + } + + public function testInvariantIsCompiled(): void + { + [$contract] = $this->fetcher->getInvariants(new ReflectionClass(Particle::class)); + + self::assertNotNull($contract->check); + $particle = new Particle(10); + self::assertTrue(($contract->check)($particle)); + new ReflectionProperty(Particle::class, 'speed')->setValue($particle, -10.0); + self::assertFalse(($contract->check)($particle)); + } + + public function testThisInStaticMethodIsLeftToTheRunTimeCheck(): void + { + [$contract] = $this->fetcher->getPreconditions(new ReflectionMethod(Account::class, 'staticWithThis')); + + self::assertNull($contract->check); + } + + /** + * Returns the line of the code in a fixture source file + */ + private static function findLine(string $fixture, string $code): int + { + $lines = \file(\dirname(__DIR__) . '/Fixtures/' . $fixture); + self::assertIsArray($lines); + foreach ($lines as $index => $line) { + if (\str_contains($line, $code)) { + return $index + 1; + } + } + self::fail("{$code} not found in {$fixture}"); + } +} diff --git a/tests/Unit/Contract/ContractCompilerTest.php b/tests/Unit/Contract/ContractCompilerTest.php new file mode 100644 index 0000000..0766fa8 --- /dev/null +++ b/tests/Unit/Contract/ContractCompilerTest.php @@ -0,0 +1,107 @@ +compiler = new ContractCompiler(); + } + + public function testPreconditionTakesTheParameters(): void + { + self::assertSame( + 'static function ($__this, $amount, $rest, ...$__arguments) { return ($amount > 0); }', + $this->compiler->compile('$amount > 0', ['amount', 'rest'], false, false), + ); + } + + public function testPostconditionTakesTheResultAndTheOldState(): void + { + self::assertSame( + 'static function ($__this, $amount, $__result = null, $__old = null, ...$__arguments) {' + . ' return ($__this->value === $__old->value + $amount); }', + $this->compiler->compile('$this->value === $__old->value + $amount', ['amount'], false, true), + ); + } + + public function testInvariantTakesTheObjectAndTheResult(): void + { + self::assertSame( + 'static function ($__this, $__result = null, ...$__arguments) { return ($__this->balance >= 0); }', + $this->compiler->compile('$this->balance >= 0', null, false, true), + ); + } + + #[TestWith(['Assert\Assertion::integer($x)', '\Assert\Assertion::integer($x)'])] + #[TestWith(['\Assert\Assertion::integer($x)', '\Assert\Assertion::integer($x)'])] + #[TestWith(['namespace\Money::isValid($x)', '\Money::isValid($x)'])] + #[TestWith(['count($x) > PHP_INT_SIZE', '\count($x) > \PHP_INT_SIZE'])] + #[TestWith(['$x instanceof DateTimeImmutable', '$x instanceof \DateTimeImmutable'])] + #[TestWith(['$x === null || $x === TRUE', '$x === null || $x === TRUE'])] + #[TestWith(['self::LIMIT > $x', 'self::LIMIT > $x'])] + #[TestWith(['"$this->name" === $x', '"$__this->name" === $x'])] + #[TestWith(['\array_all($x, fn($i) => $i > $this->min)', '\array_all($x, fn($i) => $i > $__this->min)'])] + #[TestWith(['$x > 0 // must be positive', '$x > 0'])] + #[TestWith(["\$x > 0\n && \$x < 10", '$x > 0 && $x < 10'])] + #[TestWith(['$x /* inline */ > 0', '$x > 0'])] + #[TestWith(['\'$this\' === $x', '\'$this\' === $x'])] + public function testExpressionKeepsItsMeaningOutsideOfEval(string $expression, string $body): void + { + self::assertSame( + 'static function ($__this, $x, ...$__arguments) { return (' . $body . '); }', + $this->compiler->compile($expression, ['x'], false, false), + ); + } + + public function testStaticMethodKeepsStatic(): void + { + self::assertSame( + 'static function ($__this, ...$__arguments) { return (static::create() instanceof self); }', + $this->compiler->compile('static::create() instanceof self', [], true, false), + ); + } + + #[TestWith(['$amount >'], 'syntax error')] + #[TestWith(['1); (2'], 'two statements')] + #[TestWith(['1 ?> 0'], 'variable variable')] + #[TestWith(['\count(\get_defined_vars()) > 0'], 'scope function')] + #[TestWith(['(function () { return true; })()'], 'closure that would need $this')] + #[TestWith(['__CLASS__ !== ""'], 'magic constant')] + #[TestWith(['static::LIMIT > 0'], 'late static binding')] + #[TestWith(['self::isValid($amount)'], 'call that may forward $this')] + #[TestWith(["\$name !== \"a\nb\""], 'newline in a string')] + public function testExpressionThatMayBehaveDifferentlyIsNotCompiled(string $expression): void + { + self::assertNull($this->compiler->compile($expression, ['amount', 'name'], false, false)); + } + + public function testThisInStaticMethodIsNotCompiled(): void + { + self::assertNull($this->compiler->compile('$this->limit > 0', [], true, false)); + } + + public function testInvariantWithMethodArgumentsIsNotCompiled(): void + { + self::assertNull($this->compiler->compile('$amount > 0', null, false, true)); + self::assertNotNull($this->compiler->compile('\array_all($this->items, fn($item) => $item > 0)', null, false, true)); + } + + public function testReservedParameterNameIsNotCompiled(): void + { + self::assertNull($this->compiler->compile('$__result > 0', ['__result'], false, false)); + } +} diff --git a/tests/Unit/Contract/ContractEvaluatorTest.php b/tests/Unit/Contract/ContractEvaluatorTest.php index 86906a6..7bb0214 100644 --- a/tests/Unit/Contract/ContractEvaluatorTest.php +++ b/tests/Unit/Contract/ContractEvaluatorTest.php @@ -20,6 +20,7 @@ use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\TestCase; +use ReflectionFunction; use RuntimeException; use stdClass; use Throwable; @@ -137,6 +138,42 @@ public function testThisInStaticInvocationIsInvalid(): void ); } + public function testCompiledContractIsCalledInTheScopeOfTheContract(): void + { + $invocation = FakeInvocation::on(new Square(), 'scale', 2.0); + // The expression is not evaluated when a compiled closure is given + $contract = new BoundContract( + new Verify('false', static fn(Square $__this, float $factor): bool => $factor === 2.0), + Square::class, + ); + + $this->evaluator->check($invocation, [$contract], ['factor' => 2.0], ContractKind::Precondition); + + self::assertNotNull($contract->check); + self::assertSame(Square::class, new ReflectionFunction($contract->check)->getClosureScopeClass()?->name); + self::assertFalse($this->evaluator->isEvaluating()); + } + + public function testCompiledContractReportsTheExpression(): void + { + $invocation = FakeInvocation::on(new Square(), 'scale', 2.0); + $contracts = [new BoundContract(new Ensure('$__result > 5', static fn($__this, $__result): bool => $__result > 5), Square::class)]; + + $this->expectException(PostconditionViolation::class); + $this->expectExceptionMessage('Postcondition "$__result > 5" violated'); + $this->evaluator->check($invocation, $contracts, ['__result' => 4.0], ContractKind::Postcondition); + } + + public function testCompiledContractGetsNoObjectInStaticMethod(): void + { + $invocation = FakeInvocation::onStatic(Square::class, 'create'); + $contracts = [new BoundContract(new Ensure('true', static fn($__this): bool => $__this === null), Square::class)]; + + $this->evaluator->check($invocation, $contracts, [], ContractKind::Postcondition); + + $this->addToAssertionCount(1); + } + public function testSyntaxErrorIsInvalid(): void { $invocation = FakeInvocation::on(new Square(), 'scale', 2.0); diff --git a/tests/Unit/Contract/ContractRewriterTest.php b/tests/Unit/Contract/ContractRewriterTest.php new file mode 100644 index 0000000..4fb2e95 --- /dev/null +++ b/tests/Unit/Contract/ContractRewriterTest.php @@ -0,0 +1,119 @@ +balance >= 0')] + class Account + { + #[Verify('$amount > 0')] + #[Ensure( + '$this->balance === $__old->balance + $amount' + )] + public function deposit(float $amount): void {} + + #[Verify(expression: '$amount > 0')] + #[\PhpDeal\Attribute\Verify('$amount >')] + #[OtherVerify('$amount > 0')] + #[Verify('$amount > 0', check: null)] + public static function create(float $amount, float ...$rest): void {} + } + PHP; + + private string $file = ''; + + protected function setUp(): void + { + $this->file = \sys_get_temp_dir() . '/php-deal-rewriter-' . \bin2hex(\random_bytes(4)) . '.php'; + \file_put_contents($this->file, self::SOURCE); + } + + protected function tearDown(): void + { + if (\is_file($this->file)) { + \unlink($this->file); + } + } + + public function testCompilesContractsOnTheirLines(): void + { + $metadata = $this->createMetadata(); + + $result = new SyntaxTreeRewriter(new ContractRewriter())->transform($metadata); + + self::assertSame(TransformerResult::Transformed, $result); + $lines = \explode("\n", $metadata->source); + self::assertCount(\substr_count(self::SOURCE, "\n") + 1, $lines, 'Line numbers must not change'); + self::assertSame( + "#[Invariant('\$this->balance >= 0', check: static function (\$__this, \$__result = null, ...\$__arguments)" + . ' { return ($__this->balance >= 0); })]', + $lines[9], + ); + self::assertSame( + " #[Verify('\$amount > 0', check: static function (\$__this, \$amount, ...\$__arguments)" + . ' { return ($amount > 0); })]', + $lines[12], + ); + self::assertSame( + " '\$this->balance === \$__old->balance + \$amount', check: static function (\$__this, \$amount," + . ' $__result = null, $__old = null, ...$__arguments) { return ($__this->balance === $__old->balance + $amount); }', + $lines[14], + ); + self::assertSame( + " #[Verify(expression: '\$amount > 0', check: static function (\$__this, \$amount, \$rest, ...\$__arguments)" + . ' { return ($amount > 0); })]', + $lines[18], + ); + // A syntax error, an attribute of another library and a given closure are left alone + self::assertSame(" #[\\PhpDeal\\Attribute\\Verify('\$amount >')]", $lines[19]); + self::assertSame(" #[OtherVerify('\$amount > 0')]", $lines[20]); + self::assertSame(" #[Verify('\$amount > 0', check: null)]", $lines[21]); + } + + public function testSourceWithoutContractsIsNotTransformed(): void + { + \file_put_contents($this->file, "transform($this->createMetadata()); + + self::assertSame(TransformerResult::Abstain, $result); + } + + private function createMetadata(): StreamMetaData + { + $stream = \fopen($this->file, 'rb'); + if ($stream === false) { + throw new RuntimeException('Can not open ' . $this->file); + } + try { + return new StreamMetaData($stream, (string) \file_get_contents($this->file)); + } finally { + \fclose($stream); + } + } +} diff --git a/tests/Unit/ContractApplicationTest.php b/tests/Unit/ContractApplicationTest.php index af67865..6b9ecc8 100644 --- a/tests/Unit/ContractApplicationTest.php +++ b/tests/Unit/ContractApplicationTest.php @@ -9,6 +9,7 @@ use PhpDeal\Aspect\InvariantCheckerAspect; use PhpDeal\Aspect\PostconditionCheckerAspect; use PhpDeal\Aspect\PreconditionCheckerAspect; +use PhpDeal\Contract\ContractRewriter; use PhpDeal\ContractApplication; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; @@ -18,10 +19,14 @@ final class ContractApplicationTest extends TestCase { public function testRegistersEveryContractAspect(): void { + $expected = [PreconditionCheckerAspect::class, PostconditionCheckerAspect::class, InvariantCheckerAspect::class]; + if (\PHP_VERSION_ID >= 80500) { + $expected[] = ContractRewriter::class; + } $container = $this->createMock(AspectContainer::class); $factories = []; $container - ->expects(self::exactly(3)) + ->expects(self::exactly(\count($expected))) ->method('addLazyService') ->willReturnCallback(static function (string $id, Closure $factory) use (&$factories): void { $factories[$id] = $factory; @@ -29,13 +34,13 @@ public function testRegistersEveryContractAspect(): void ContractApplication::registerAspects($container); - self::assertSame( - [PreconditionCheckerAspect::class, PostconditionCheckerAspect::class, InvariantCheckerAspect::class], - \array_keys($factories), - ); + self::assertSame($expected, \array_keys($factories)); self::assertInstanceOf(PreconditionCheckerAspect::class, $factories[PreconditionCheckerAspect::class]($container)); self::assertInstanceOf(PostconditionCheckerAspect::class, $factories[PostconditionCheckerAspect::class]($container)); self::assertInstanceOf(InvariantCheckerAspect::class, $factories[InvariantCheckerAspect::class]($container)); + if (isset($factories[ContractRewriter::class])) { + self::assertInstanceOf(ContractRewriter::class, $factories[ContractRewriter::class]($container)); + } } public function testKernelIsRunning(): void From c452603d471c6a763a0e5dbbba3db691280a29cd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 22:14:30 +0000 Subject: [PATCH 2/2] Cache per-call work, tokenize the static $this check, evaluate only built-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 Claude-Session: https://claude.ai/code/session_01FxhC1EtLcA5S6bhb3s1f6Q --- AGENTS.md | 5 +- CHANGELOG.md | 6 + README.md | 6 +- src/Aspect/InvariantCheckerAspect.php | 3 +- src/Aspect/PostconditionCheckerAspect.php | 10 +- src/Attribute/Contract.php | 5 + src/Contract/BoundContract.php | 21 ++- src/Contract/ContractEvaluator.php | 164 ++++++++++++++---- src/Contract/ContractFetcher.php | 70 +++++--- tests/Fixtures/Verify/Account.php | 3 + tests/Functional/CompiledContractTest.php | 3 +- tests/Functional/VerifyTest.php | 8 + tests/Unit/Contract/ContractEvaluatorTest.php | 35 ++++ tests/Unit/Contract/ContractFetcherTest.php | 22 ++- tests/Unit/Stub/CustomContract.php | 22 +++ tests/Unit/Stub/Square.php | 8 + 16 files changed, 315 insertions(+), 76 deletions(-) create mode 100644 tests/Unit/Stub/CustomContract.php diff --git a/AGENTS.md b/AGENTS.md index 61e43b9..1bc1379 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,7 +34,7 @@ lowest-dependencies job and `composer audit`. | Path | Contents | |------------------------------|----------| -| `src/Attribute/` | The attributes. `Verify`, `Ensure`, `Invariant` implement the `Contract` interface (`$expression`). | +| `src/Attribute/` | The attributes. `Verify`, `Ensure`, `Invariant` implement the `Contract` interface (`$expression`); only these three are ever evaluated. | | `src/Aspect/` | One Go! AOP aspect per contract kind. The pointcuts are in their advice attributes. | | `src/Contract/ContractFetcher.php` | Collects contracts from the method/class and its parents and interfaces, with caching. | | `src/Contract/ContractEvaluator.php` | Evaluates contracts: calls compiled closures, or compiles expressions with `eval()` (once) and binds them. | @@ -78,6 +78,9 @@ lowest-dependencies job and `composer audit`. from the `...OriginalAlias` method or the `...OriginalTrait`. `BoundContract` binds the closure to its scope once. `ContractCompiler` returns `null` for anything that could behave differently than in `eval()`; keep it conservative, an invalid closure breaks the whole woven file. +- **Per-call cost.** Aspects run on every call: keep reflection and string building out of the hot path. Cache by + class and method name in nested arrays (`ContractFetcher`, `ContractEvaluator`), and build error text only when + throwing. - **Recursion guard.** While an expression is evaluated, `ContractEvaluator::isEvaluating()` is true and every aspect skips its checks. This lets an invariant call public methods of its own class. - **Woven classes.** Go! AOP 4 turns the original class body into a `OriginalTrait`, and the proxy keeps the diff --git a/CHANGELOG.md b/CHANGELOG.md index 5854bb7..6687ffe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,11 @@ specifications into contracted code and tests. See [UPGRADE-2.0.md](UPGRADE-2.0. - Contracts of parent classes are evaluated in the scope of the declaring class. - Inherited preconditions are checked before the method body. - The object is cloned for `$__old` only when a postcondition uses it. +- Less work per call: contracts, method parameters, invariants by class name and the cloneability of a class are + looked up in per-process caches before any reflection call, and error locations are built only on errors (#80). +- Only the built-in `#[Verify]`, `#[Ensure]` and `#[Invariant]` attributes are evaluated; `BoundContract` accepts no + other `Contract` implementation, so computed text can not reach `eval()`. Compiled contracts come from the string + literal in the source (#85). - Violations point to the line of the method that declares the contract. ### Fixed @@ -48,6 +53,7 @@ specifications into contracted code and tests. See [UPGRADE-2.0.md](UPGRADE-2.0. - Arrays and objects among the arguments no longer break the violation message. - Variadic arguments are passed to contracts as a list. - A trailing `//` comment in an expression no longer breaks it. +- `$this` inside a string literal of a static method's contract no longer throws `InvalidContractException` (#84). ### Removed diff --git a/README.md b/README.md index c40bcf7..6c8c63a 100644 --- a/README.md +++ b/README.md @@ -506,8 +506,10 @@ An expression is evaluated with `eval()` instead, as on PHP 8.4, when it could b a syntax error or `$this` in a static method (both still throw `InvalidContractException` when the method is called), `static::` or `self::method()` in an instance context, a nested `function () {}`, magic constants such as `__CLASS__`, variable variables, `compact()`/`extract()`/`get_defined_vars()`, a newline inside a string literal, and an -invariant that reads a variable other than `$this` and `$__result`. Classes that are not woven, and `Contract` -implementations of other packages, use `eval()` too. +invariant that reads a variable other than `$this` and `$__result`. Classes that are not woven use `eval()` too. + +Only the built-in attributes are evaluated, and their expressions are constant expressions in your source code. Never +build an expression from configuration, environment variables, a database or user input: it is executed as PHP code. ## Handling violations diff --git a/src/Aspect/InvariantCheckerAspect.php b/src/Aspect/InvariantCheckerAspect.php index a01e4c6..f6b681d 100644 --- a/src/Aspect/InvariantCheckerAspect.php +++ b/src/Aspect/InvariantCheckerAspect.php @@ -20,7 +20,6 @@ use PhpDeal\Contract\ContractFetcher; use PhpDeal\Contract\ContractKind; use PhpDeal\Exception\InvariantViolation; -use ReflectionObject; /** * Checks `#[Invariant]` class invariants after the constructor and after every public method @@ -48,7 +47,7 @@ public function checkInvariants(MethodInvocation $invocation): mixed if ($instance === null || $this->evaluator->isEvaluating()) { return $result; } - $contracts = $this->fetcher->getInvariants(new ReflectionObject($instance)); + $contracts = $this->fetcher->getInvariants($instance::class); if ($contracts === []) { return $result; } diff --git a/src/Aspect/PostconditionCheckerAspect.php b/src/Aspect/PostconditionCheckerAspect.php index 9eb2f72..f281b98 100644 --- a/src/Aspect/PostconditionCheckerAspect.php +++ b/src/Aspect/PostconditionCheckerAspect.php @@ -21,7 +21,6 @@ use PhpDeal\Contract\ContractFetcher; use PhpDeal\Contract\ContractKind; use PhpDeal\Exception\PostconditionViolation; -use ReflectionObject; /** * Checks `#[Ensure]` post-conditions after the method body has returned @@ -56,8 +55,11 @@ public function checkPostconditions(MethodInvocation $invocation): mixed $variables = $this->evaluator->getArguments($invocation); $instance = $invocation->getThis(); // Cloning is skipped when no contract needs the previous state - if ($instance !== null && self::usesOldState($contracts) && new ReflectionObject($instance)->isCloneable()) { - $variables['__old'] = clone $instance; + if ($instance !== null && self::usesOldState($contracts)) { + $oldState = $this->evaluator->cloneState($instance); + if ($oldState !== null) { + $variables['__old'] = $oldState; + } } $result = $invocation->proceed(); @@ -73,7 +75,7 @@ public function checkPostconditions(MethodInvocation $invocation): mixed private static function usesOldState(array $contracts): bool { foreach ($contracts as $boundContract) { - if (\str_contains($boundContract->contract->expression, '$__old')) { + if ($boundContract->usesOldState) { return true; } } diff --git a/src/Attribute/Contract.php b/src/Attribute/Contract.php index f35efde..b10315f 100644 --- a/src/Attribute/Contract.php +++ b/src/Attribute/Contract.php @@ -18,6 +18,11 @@ * * The expression is evaluated in the scope of the class that declares the method, so it can read private and * protected members through `$this` or `self::`. Method arguments are available by their names. + * + * Only the built-in {@see Verify}, {@see Ensure} and {@see Invariant} attributes are evaluated. The expression is + * executed as PHP code, so it must be written in the source code, as a constant expression of the attribute. Never + * build it from configuration, environment variables, a database or user input. Other implementations of this + * interface are ignored. */ interface Contract { diff --git a/src/Contract/BoundContract.php b/src/Contract/BoundContract.php index bb83293..aff78b2 100644 --- a/src/Contract/BoundContract.php +++ b/src/Contract/BoundContract.php @@ -14,7 +14,6 @@ namespace PhpDeal\Contract; use Closure; -use PhpDeal\Attribute\Contract; use PhpDeal\Attribute\Ensure; use PhpDeal\Attribute\Invariant; use PhpDeal\Attribute\Verify; @@ -24,6 +23,9 @@ * * Contracts of a class are evaluated in the scope of that class, so they can read its private members even when the * method is called on a subclass. Contracts of an interface are evaluated in the scope of the implementing class. + * + * Only the built-in attributes are accepted: their expressions are constant expressions written in the source, so + * no computed text ever reaches eval(). */ final readonly class BoundContract { @@ -33,17 +35,20 @@ public ?Closure $check; /** - * @param Contract $contract Contract attribute - * @param class-string $scope Class scope for the expression + * Whether the expression reads `$__old`, so the object must be cloned before the call + */ + public bool $usesOldState; + + /** + * @param Verify|Ensure|Invariant $contract Contract attribute + * @param class-string $scope Class scope for the expression */ public function __construct( - public Contract $contract, + public Verify|Ensure|Invariant $contract, public string $scope, ) { - // Contract implementations of other packages are always evaluated with eval() - $isCompilable = $contract instanceof Verify || $contract instanceof Ensure || $contract instanceof Invariant; - $check = $isCompilable ? $contract->check : null; // The closure is declared in the woven trait or the interface, it must run in the scope of the contract - $this->check = $check !== null ? Closure::bind($check, null, $scope) : null; + $this->check = $contract->check !== null ? Closure::bind($contract->check, null, $scope) : null; + $this->usesOldState = \str_contains($contract->expression, '$__old'); } } diff --git a/src/Contract/ContractEvaluator.php b/src/Contract/ContractEvaluator.php index 311ee75..3eeaf83 100644 --- a/src/Contract/ContractEvaluator.php +++ b/src/Contract/ContractEvaluator.php @@ -18,21 +18,53 @@ use ParseError; use PhpDeal\Exception\ContractViolation; use PhpDeal\Exception\InvalidContractException; +use PhpToken; +use ReflectionClass; +use ReflectionMethod; +use ReflectionParameter; use Throwable; +use UnitEnum; /** * Evaluates contracts for a method invocation * * Contracts compiled while the class was woven (PHP 8.5+, see {@see ContractRewriter}) are called directly. Other - * expressions are compiled with eval() into closures, once per process. While a contract is evaluated, contracts of nested calls are not - * checked, so an invariant may call public methods of its own class without recursing endlessly. + * expressions are compiled with eval() into closures, once per process. While a contract is evaluated, contracts of + * nested calls are not checked, so an invariant may call public methods of its own class without recursing endlessly. + * + * Everything that does not change between calls is cached per process: the parameters of a method, the closures + * compiled with eval(), the static checks of an expression and whether a class can be cloned. */ final class ContractEvaluator { /** - * @var array): mixed> + * Closures compiled with eval(), for static and dynamic calls, by expression + * + * @var array{static: array): mixed>, dynamic: array): mixed>} */ - private array $compiled = []; + private array $compiled = ['static' => [], 'dynamic' => []]; + + /** + * Parameters of a method by class and method name: name, whether it is variadic, the default value, and the + * parameter itself when its default must be evaluated on every call (it creates an object) + * + * @var array>> + */ + private array $parameters = []; + + /** + * Whether an expression uses the `$this` variable, by expression + * + * @var array + */ + private array $usesThis = []; + + /** + * Whether objects of a class can be cloned, by class name + * + * @var array + */ + private array $cloneable = []; private int $depth = 0; @@ -51,23 +83,35 @@ public function isEvaluating(): bool */ public function getArguments(MethodInvocation $invocation): array { - $values = $invocation->getArguments(); - $variables = []; - foreach ($invocation->getMethod()->getParameters() as $index => $parameter) { - if ($parameter->isVariadic()) { - $variables[$parameter->name] = \array_slice($values, $index); + $method = $invocation->getMethod(); + $parameters = $this->parameters[$method->class][$method->name] ??= self::describeParameters($method); + $values = $invocation->getArguments(); + $variables = []; + foreach ($parameters as $index => [$name, $isVariadic, $default, $lazyDefault]) { + if ($isVariadic) { + $variables[$name] = \array_slice($values, $index); break; } - $variables[$parameter->name] = match (true) { - \array_key_exists($index, $values) => $values[$index], - $parameter->isDefaultValueAvailable() => $parameter->getDefaultValue(), - default => null, + $variables[$name] = match (true) { + \array_key_exists($index, $values) => $values[$index], + $lazyDefault !== null => $lazyDefault->getDefaultValue(), + default => $default, }; } return $variables; } + /** + * Returns a clone of the object for `$__old`, or null if objects of its class can not be cloned + */ + public function cloneState(object $instance): ?object + { + $isCloneable = $this->cloneable[$instance::class] ??= new ReflectionClass($instance)->isCloneable(); + + return $isCloneable ? clone $instance : null; + } + /** * Evaluates every contract and throws on the first one that does not hold * @@ -80,28 +124,31 @@ public function getArguments(MethodInvocation $invocation): array public function check(MethodInvocation $invocation, array $contracts, array $variables, ContractKind $kind): void { $instance = $invocation->getThis(); - $location = $invocation->getMethod()->class . '::' . $invocation->getMethod()->name . '()'; foreach ($contracts as $boundContract) { - $expression = $boundContract->contract->expression; - $evaluator = $boundContract->check ?? $this->bindExpression($boundContract, $instance, $location); + $check = $boundContract->check; + $evaluator = $check ?? $this->bindExpression($boundContract, $invocation); ++$this->depth; try { // A compiled contract takes the object first, then the variables by name - $result = $boundContract->check !== null ? $evaluator($instance, ...$variables) : $evaluator($variables); + $result = $check !== null ? $check($instance, ...$variables) : $evaluator($variables); } catch (Throwable $error) { // Assertion libraries signal failures with exceptions, broken expressions with errors - throw $kind->createViolation($invocation, $expression, $error); + throw $kind->createViolation($invocation, $boundContract->contract->expression, $error); } finally { --$this->depth; } if ($result === false) { - throw $kind->createViolation($invocation, $expression); + throw $kind->createViolation($invocation, $boundContract->contract->expression); } // null is accepted for assertion helpers that return nothing if ($result !== true && $result !== null) { - throw InvalidContractException::forInvalidResult($expression, $location, $result); + throw InvalidContractException::forInvalidResult( + $boundContract->contract->expression, + self::describeLocation($invocation), + $result, + ); } } } @@ -110,28 +157,87 @@ public function check(MethodInvocation $invocation, array $contracts, array $var * Compiles the expression with eval() and binds it to the object, for contracts that were not compiled while * the class was woven * + * @return Closure(array): mixed + * * @throws InvalidContractException When the expression is not valid PHP or uses $this in a static method */ - private function bindExpression(BoundContract $boundContract, ?object $instance, string $location): Closure + private function bindExpression(BoundContract $boundContract, MethodInvocation $invocation): Closure { $expression = $boundContract->contract->expression; + $instance = $invocation->getThis(); $isStatic = $instance === null; - if ($isStatic && \preg_match('/\$this\b/', $expression) === 1) { - throw InvalidContractException::forStaticContext($expression, $location); + if ($isStatic && ($this->usesThis[$expression] ??= self::usesThisVariable($expression))) { + throw InvalidContractException::forStaticContext($expression, self::describeLocation($invocation)); } try { $closure = $this->compile($expression, $isStatic); } catch (ParseError $error) { - throw InvalidContractException::forSyntaxError($expression, $location, $error); + throw InvalidContractException::forSyntaxError($expression, self::describeLocation($invocation), $error); } $evaluator = Closure::bind($closure, $instance, $boundContract->scope); if ($evaluator === null) { - throw InvalidContractException::forStaticContext($expression, $location); + throw InvalidContractException::forStaticContext($expression, self::describeLocation($invocation)); } return $evaluator; } + /** + * Method that declares the contract, for error messages, e.g. "App\Account::deposit()" + */ + private static function describeLocation(MethodInvocation $invocation): string + { + $method = $invocation->getMethod(); + + return $method->class . '::' . $method->name . '()'; + } + + /** + * Tells whether the expression reads the `$this` variable; `$this` inside a string literal does not count + */ + private static function usesThisVariable(string $expression): bool + { + foreach (PhpToken::tokenize('is(\T_VARIABLE) && $token->text === '$this') { + return true; + } + } + + return false; + } + + /** + * @return list + */ + private static function describeParameters(ReflectionMethod $method): array + { + $parameters = []; + foreach ($method->getParameters() as $parameter) { + $default = null; + $lazyDefault = null; + if (!$parameter->isVariadic() && $parameter->isDefaultValueAvailable()) { + $default = $parameter->getDefaultValue(); + // A default created with `new` must not be shared between calls + if (self::containsObject($default)) { + [$default, $lazyDefault] = [null, $parameter]; + } + } + $parameters[] = [$parameter->name, $parameter->isVariadic(), $default, $lazyDefault]; + } + + return $parameters; + } + + private static function containsObject(mixed $value): bool + { + if (\is_array($value)) { + return \array_any($value, self::containsObject(...)); + } + + // Enum cases are singletons, they can be shared + return \is_object($value) && !$value instanceof UnitEnum; + } + /** * @return Closure(array): mixed * @@ -139,9 +245,9 @@ private function bindExpression(BoundContract $boundContract, ?object $instance, */ private function compile(string $expression, bool $isStatic): Closure { - $cacheKey = ($isStatic ? 'static:' : 'dynamic:') . $expression; - if (isset($this->compiled[$cacheKey])) { - return $this->compiled[$cacheKey]; + $kind = $isStatic ? 'static' : 'dynamic'; + if (isset($this->compiled[$kind][$expression])) { + return $this->compiled[$kind][$expression]; } // The closing parenthesis is on its own line, so a trailing "//" comment can not swallow it $code = 'return ' . ($isStatic ? 'static ' : '') @@ -156,6 +262,6 @@ private function compile(string $expression, bool $isStatic): Closure } /** @var Closure(array): mixed $closure */ - return $this->compiled[$cacheKey] = $closure; + return $this->compiled[$kind][$expression] = $closure; } } diff --git a/src/Contract/ContractFetcher.php b/src/Contract/ContractFetcher.php index c769a71..988ddd0 100644 --- a/src/Contract/ContractFetcher.php +++ b/src/Contract/ContractFetcher.php @@ -16,7 +16,6 @@ use Go\Aop\Framework\AbstractMethodInvocation; use Go\Aop\Proxy; use Go\Core\AspectContainer; -use PhpDeal\Attribute\Contract; use PhpDeal\Attribute\Ensure; use PhpDeal\Attribute\Inherit; use PhpDeal\Attribute\Invariant; @@ -28,14 +27,31 @@ /** * Collects the contracts of methods and classes, including the ones inherited from parents and interfaces * - * Results are cached per class and method, attributes are read only once per process. + * Results are cached per class and method, attributes are read only once per process. A cached answer is found + * with one array lookup, before any reflection call. */ final class ContractFetcher { /** + * Pre-conditions by class and method name + * + * @var array>> + */ + private array $preconditions = []; + + /** + * Post-conditions by class and method name + * + * @var array>> + */ + private array $postconditions = []; + + /** + * Invariants by class name + * * @var array> */ - private array $cache = []; + private array $invariants = []; /** * Returns the pre-conditions of a method @@ -47,7 +63,8 @@ final class ContractFetcher */ public function getPreconditions(ReflectionMethod $method): array { - return $this->getMethodContracts($method, Verify::class, $this->inheritsPreconditions($method)); + return $this->preconditions[$method->class][$method->name] + ??= self::readMethodContracts($method, Verify::class, self::inheritsPreconditions($method)); } /** @@ -57,45 +74,46 @@ public function getPreconditions(ReflectionMethod $method): array */ public function getPostconditions(ReflectionMethod $method): array { - return $this->getMethodContracts($method, Ensure::class, true); + return $this->postconditions[$method->class][$method->name] + ??= self::readMethodContracts($method, Ensure::class, true); } /** * Returns the invariants of a class, together with the ones of parent classes and interfaces * - * @param ReflectionClass $class + * @param class-string $className * * @return list */ - public function getInvariants(ReflectionClass $class): array + public function getInvariants(string $className): array { - $cacheKey = $class->name . '#' . Invariant::class; - if (isset($this->cache[$cacheKey])) { - return $this->cache[$cacheKey]; - } + return $this->invariants[$className] ??= self::readInvariants(new ReflectionClass($className)); + } + /** + * @param ReflectionClass $class + * + * @return list + */ + private static function readInvariants(ReflectionClass $class): array + { $contracts = self::readContracts($class, Invariant::class, $class->name); foreach (self::getAncestors($class) as $ancestor) { $scope = $ancestor->isInterface() ? $class->name : $ancestor->name; \array_push($contracts, ...self::readContracts($ancestor, Invariant::class, $scope)); } - return $this->cache[$cacheKey] = self::unique($contracts); + return self::unique($contracts); } /** - * @param class-string $type Contract attribute to collect + * @param class-string $type Contract attribute to collect * * @return list */ - private function getMethodContracts(ReflectionMethod $method, string $type, bool $withAncestors): array + private static function readMethodContracts(ReflectionMethod $method, string $type, bool $withAncestors): array { - $class = $method->getDeclaringClass(); - $cacheKey = $class->name . '::' . $method->name . '#' . $type . ($withAncestors ? '+' : ''); - if (isset($this->cache[$cacheKey])) { - return $this->cache[$cacheKey]; - } - + $class = $method->getDeclaringClass(); $contracts = self::readContracts($method, $type, $class->name); if ($withAncestors) { foreach (self::getAncestors($class) as $ancestor) { @@ -112,10 +130,10 @@ private function getMethodContracts(ReflectionMethod $method, string $type, bool } } - return $this->cache[$cacheKey] = self::unique($contracts); + return self::unique($contracts); } - private function inheritsPreconditions(ReflectionMethod $method): bool + private static function inheritsPreconditions(ReflectionMethod $method): bool { if ($method->getAttributes(Inherit::class) !== []) { return true; @@ -152,8 +170,12 @@ private static function getAncestors(ReflectionClass $class): array } /** + * Only the built-in attributes are read: their expressions are constant expressions written in the source + * + * @template T of Verify|Ensure|Invariant + * * @param ReflectionClass|ReflectionMethod $reflector - * @param class-string $type + * @param class-string $type * @param class-string $scope * * @return list @@ -162,7 +184,7 @@ private static function readContracts(ReflectionClass|ReflectionMethod $reflecto { return \array_map( static fn(ReflectionAttribute $attribute): BoundContract => new BoundContract($attribute->newInstance(), $scope), - self::getOriginalDeclaration($reflector)->getAttributes($type, ReflectionAttribute::IS_INSTANCEOF), + self::getOriginalDeclaration($reflector)->getAttributes($type), ); } diff --git a/tests/Fixtures/Verify/Account.php b/tests/Fixtures/Verify/Account.php index 041a28f..4a281d0 100644 --- a/tests/Fixtures/Verify/Account.php +++ b/tests/Fixtures/Verify/Account.php @@ -66,4 +66,7 @@ private function isAllowed(int $amount): bool { return $amount % 2 === 0; } + + #[Verify('$name !== \'$this\'')] + public static function staticWithThisInString(string $name): void {} } diff --git a/tests/Functional/CompiledContractTest.php b/tests/Functional/CompiledContractTest.php index 3144b79..dd8dd5f 100644 --- a/tests/Functional/CompiledContractTest.php +++ b/tests/Functional/CompiledContractTest.php @@ -13,7 +13,6 @@ use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\RequiresPhp; use PHPUnit\Framework\TestCase; -use ReflectionClass; use ReflectionFunction; use ReflectionMethod; use ReflectionProperty; @@ -57,7 +56,7 @@ public function testInterfaceContractRunsInTheScopeOfTheImplementingClass(): voi public function testInvariantIsCompiled(): void { - [$contract] = $this->fetcher->getInvariants(new ReflectionClass(Particle::class)); + [$contract] = $this->fetcher->getInvariants(Particle::class); self::assertNotNull($contract->check); $particle = new Particle(10); diff --git a/tests/Functional/VerifyTest.php b/tests/Functional/VerifyTest.php index 7b49567..33090f9 100644 --- a/tests/Functional/VerifyTest.php +++ b/tests/Functional/VerifyTest.php @@ -117,6 +117,14 @@ public function testThisInStaticMethodIsAnInvalidContract(): void Account::staticWithThis(100); } + public function testThisInStringOfStaticMethodIsValid(): void + { + Account::staticWithThisInString('account'); + + $this->expectException(PreconditionViolation::class); + Account::staticWithThisInString('$this'); + } + public function testSyntaxErrorIsAnInvalidContract(): void { $this->expectException(InvalidContractException::class); diff --git a/tests/Unit/Contract/ContractEvaluatorTest.php b/tests/Unit/Contract/ContractEvaluatorTest.php index 7bb0214..a2a2014 100644 --- a/tests/Unit/Contract/ContractEvaluatorTest.php +++ b/tests/Unit/Contract/ContractEvaluatorTest.php @@ -17,6 +17,7 @@ use PhpDeal\Exception\PreconditionViolation; use PhpDeal\Tests\Unit\Stub\FakeInvocation; use PhpDeal\Tests\Unit\Stub\Square; +use PhpDeal\Tests\Unit\Stub\Status; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\TestCase; @@ -50,6 +51,40 @@ public function testMissingArgumentsUseDefaults(): void self::assertSame(['a' => 1, 'b' => 5, 'rest' => []], $this->evaluator->getArguments($invocation)); } + public function testObjectDefaultsAreNotSharedBetweenCalls(): void + { + $invocation = FakeInvocation::on(new Square(), 'withDefaults'); + + $first = $this->evaluator->getArguments($invocation); + $second = $this->evaluator->getArguments($invocation); + + self::assertInstanceOf(stdClass::class, $first['options']); + self::assertNotSame($first['options'], $second['options']); + self::assertSame(Status::Active, $second['status']); + self::assertSame([1], $second['list']); + } + + public function testOldStateIsAClone(): void + { + $square = new Square(); + + $clone = $this->evaluator->cloneState($square); + + self::assertInstanceOf(Square::class, $clone); + self::assertNotSame($square, $clone); + self::assertNull($this->evaluator->cloneState(Status::Active)); + } + + public function testThisInStringOfStaticMethodIsAllowed(): void + { + $invocation = FakeInvocation::onStatic(Square::class, 'create'); + $contracts = [new BoundContract(new Ensure('\'$this\' !== "" && "\\$this" !== ""'), Square::class)]; + + $this->evaluator->check($invocation, $contracts, [], ContractKind::Postcondition); + + $this->addToAssertionCount(1); + } + public function testHoldingContractsPass(): void { $invocation = FakeInvocation::on(new Square(), 'scale', 2.0); diff --git a/tests/Unit/Contract/ContractFetcherTest.php b/tests/Unit/Contract/ContractFetcherTest.php index e0660b4..f4ee3ed 100644 --- a/tests/Unit/Contract/ContractFetcherTest.php +++ b/tests/Unit/Contract/ContractFetcherTest.php @@ -13,7 +13,6 @@ use PhpDeal\Tests\Unit\Stub\Square; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; -use ReflectionClass; use ReflectionMethod; #[CoversClass(ContractFetcher::class)] @@ -73,7 +72,7 @@ public function testPrivateParentMethodsAreNotPrototypes(): void public function testInvariantsOfInterfacesUseTheScopeOfTheClass(): void { - $contracts = $this->fetcher->getInvariants(new ReflectionClass(Square::class)); + $contracts = $this->fetcher->getInvariants(Square::class); self::assertSame( [ @@ -86,13 +85,28 @@ public function testInvariantsOfInterfacesUseTheScopeOfTheClass(): void self::assertContainsOnlyInstancesOf(Invariant::class, \array_map(static fn(BoundContract $c) => $c->contract, $contracts)); } + public function testOtherContractImplementationsAreIgnored(): void + { + $contracts = $this->fetcher->getPreconditions(new ReflectionMethod(Square::class, 'withDefaults')); + + self::assertSame([['true', Square::class]], self::describe($contracts)); + } + + public function testOldStateIsDetectedOnce(): void + { + $contract = new BoundContract(new Ensure('$this->sides === $__old->sides'), Square::class); + + self::assertTrue($contract->usesOldState); + self::assertFalse(new BoundContract(new Ensure('$__result > 0'), Square::class)->usesOldState); + } + public function testResultsAreCached(): void { $method = new ReflectionMethod(Square::class, 'scale'); - $class = new ReflectionClass(Square::class); self::assertSame($this->fetcher->getPostconditions($method), $this->fetcher->getPostconditions($method)); - self::assertSame($this->fetcher->getInvariants($class), $this->fetcher->getInvariants($class)); + self::assertSame($this->fetcher->getPreconditions($method), $this->fetcher->getPreconditions($method)); + self::assertSame($this->fetcher->getInvariants(Square::class), $this->fetcher->getInvariants(Square::class)); } /** diff --git a/tests/Unit/Stub/CustomContract.php b/tests/Unit/Stub/CustomContract.php new file mode 100644 index 0000000..4ab5254 --- /dev/null +++ b/tests/Unit/Stub/CustomContract.php @@ -0,0 +1,22 @@ +expression = (string) \getenv('PHP_DEAL_CUSTOM_CONTRACT'); + } +} diff --git a/tests/Unit/Stub/Square.php b/tests/Unit/Stub/Square.php index be894e7..422e6ad 100644 --- a/tests/Unit/Stub/Square.php +++ b/tests/Unit/Stub/Square.php @@ -8,6 +8,7 @@ use PhpDeal\Attribute\Inherit; use PhpDeal\Attribute\Invariant; use PhpDeal\Attribute\Verify; +use stdClass; use Stringable; #[Invariant('$this->sides === 4')] @@ -42,6 +43,13 @@ public function hidden(int $secret): void {} #[Verify('$a > 0')] public function withParameters(int $a, int $b = 5, int ...$rest): void {} + /** + * @param list $list + */ + #[CustomContract] + #[Verify('true')] + public function withDefaults(stdClass $options = new stdClass(), Status $status = Status::Active, array $list = [1]): void {} + #[Verify('$__result')] public static function create(): self {