From cb24fc25b57d7d57248a527e4d2b032413ccdc17 Mon Sep 17 00:00:00 2001 From: roxblnfk Date: Tue, 24 Nov 2026 10:47:11 +0400 Subject: [PATCH] fix(codecov): count only lines every driver reports for files no test loaded Reports of several suites are merged line by line, so a line the estimate adds for an unloaded file stays uncovered once another suite loads the file and its driver does not report that line. The estimate now marks a line only where an operation starts and the line is the same for Xdebug, PCOV and turbocov on every PHP version from 8.2, leaving out lines whose opcode moves with the layout of an expression, with what is loaded at the time, with the PHP version, or with unreachable code. The last-line check for loaded files gets its own answer on bodies that fall through, so it keeps a closing brace the estimate leaves out. Refs #444. Assisted-By: Claude Opus 5.5 --- .../src/Internal/Driver/UncountedLines.php | 2 +- .../codecov/src/Internal/ExecutableLines.php | 1089 +++++++++++++++-- .../Fixture/ExecutableLines/hooks.php.inc | 4 + .../Fixture/ExecutableLines/operands.php.inc | 272 ++++ .../tests/Unit/Driver/UncountedLinesTest.php | 2 + .../Unit/Internal/ExecutableLinesTest.php | 114 +- skills/testo-coverage/SKILL.md | 2 +- 7 files changed, 1334 insertions(+), 151 deletions(-) create mode 100644 plugin/codecov/tests/Fixture/ExecutableLines/operands.php.inc diff --git a/plugin/codecov/src/Internal/Driver/UncountedLines.php b/plugin/codecov/src/Internal/Driver/UncountedLines.php index 68b20463..9155eb7d 100644 --- a/plugin/codecov/src/Internal/Driver/UncountedLines.php +++ b/plugin/codecov/src/Internal/Driver/UncountedLines.php @@ -92,7 +92,7 @@ private static function scan(string $path): array|false # A last line that only closes, such as `}` or `);`, carries the top-level `return`, and code only when # it ends a function body that falls through. - if (isset($code[$last]) && $onlyClosers && !isset(ExecutableLines::of($source)[$last])) { + if (isset($code[$last]) && $onlyClosers && !isset(ExecutableLines::bodyEnds($source)[$last])) { unset($code[$last]); } diff --git a/plugin/codecov/src/Internal/ExecutableLines.php b/plugin/codecov/src/Internal/ExecutableLines.php index db040f47..ab7db8a1 100644 --- a/plugin/codecov/src/Internal/ExecutableLines.php +++ b/plugin/codecov/src/Internal/ExecutableLines.php @@ -8,11 +8,15 @@ * Estimates the executable lines of PHP source from its tokens, without loading it. * * Stands in for a coverage driver on files no test loaded, so they reach the report with every line - * unexecuted. The estimate follows the lines Xdebug and PCOV report, which are the lines PHP attaches - * opcodes to: code inside function bodies, a reachable closing brace that carries an implicit `return`, - * the signature of a generator or of a constructor that promotes properties, inline HTML, and top-level - * statements other than declarations. Drivers and PHP versions disagree on a few constructs, so a - * file's count can be a few lines off. + * unexecuted. A line counts only when every driver reports it once the file is loaded, on every PHP version + * from 8.2: Xdebug, PCOV and turbocov. Those are lines where an operation starts, such as a call, an + * assignment or a jump, plus a reachable closing brace that carries an implicit `return`, inline HTML and + * top-level statements other than declarations. Where the line of an opcode depends on how an expression + * is laid out, on what is loaded at the time or on the PHP version, the line is left out. + * + * The estimate never adds a line a driver would not report: reports of several runs merged line by line, + * across drivers and PHP versions, keep such a line uncovered even after another run loads the file. A + * line left out costs nothing once a run loads the file. * * @internal */ @@ -36,8 +40,71 @@ final class ExecutableLines \T_ELLIPSIS, \T_INC, \T_DEC, \T_STATIC, ]; - /** Tokens of a `match` subject that leave an opcode on its line. */ - private const SUBJECT_OPCODE = [\T_OBJECT_OPERATOR, \T_NULLSAFE_OBJECT_OPERATOR, \T_DOUBLE_COLON]; + /** Keywords that compile to an opcode on their own line. */ + private const ACTION = [ + \T_NEW, \T_THROW, \T_INC, \T_DEC, \T_BREAK, \T_CONTINUE, \T_GOTO, \T_CATCH, + ]; + + /** Keywords that consume the value of the expression after them. */ + private const CONSUMER = [ + \T_CLONE, \T_ECHO, \T_PRINT, \T_EXIT, \T_EVAL, \T_INCLUDE, \T_INCLUDE_ONCE, \T_REQUIRE, \T_REQUIRE_ONCE, + ]; + + /** Compound assignments, emitted once their value is computed. */ + private const ASSIGNMENT = [ + \T_PLUS_EQUAL, \T_MINUS_EQUAL, \T_MUL_EQUAL, \T_DIV_EQUAL, \T_CONCAT_EQUAL, \T_MOD_EQUAL, + \T_AND_EQUAL, \T_OR_EQUAL, \T_XOR_EQUAL, \T_SL_EQUAL, \T_SR_EQUAL, \T_POW_EQUAL, \T_COALESCE_EQUAL, + ]; + + /** Binary operators, `instanceof` and the `?` of a ternary. */ + private const BINARY = [ + \T_BOOLEAN_AND, \T_BOOLEAN_OR, \T_LOGICAL_AND, \T_LOGICAL_OR, \T_LOGICAL_XOR, \T_COALESCE, + \T_IS_EQUAL, \T_IS_NOT_EQUAL, \T_IS_IDENTICAL, \T_IS_NOT_IDENTICAL, \T_IS_SMALLER_OR_EQUAL, + \T_IS_GREATER_OR_EQUAL, \T_SPACESHIP, \T_SL, \T_SR, \T_POW, \T_INSTANCEOF, + '+', '-', '*', '/', '%', '.', '&', '|', '^', '<', '>', '?', + ]; + + /** Binary operators that jump past their right operand, emitted right after the left one. */ + private const SHORT_CIRCUIT = [\T_BOOLEAN_AND, \T_BOOLEAN_OR, \T_LOGICAL_AND, \T_LOGICAL_OR, \T_COALESCE, '?']; + + /** Tokens that end an operand. */ + private const OPERAND_END = [ + \T_VARIABLE, \T_LNUMBER, \T_DNUMBER, \T_CONSTANT_ENCAPSED_STRING, \T_STRING, \T_NAME_QUALIFIED, + \T_NAME_FULLY_QUALIFIED, \T_NAME_RELATIVE, \T_CLASS, \T_LINE, \T_FILE, \T_DIR, \T_CLASS_C, \T_TRAIT_C, + \T_METHOD_C, \T_FUNC_C, \T_NS_C, ')', ']', '"', \T_END_HEREDOC, + ]; + + /** Operands PHP may fold into a constant while compiling. */ + private const FOLDABLE = [ + \T_LNUMBER, \T_DNUMBER, \T_CONSTANT_ENCAPSED_STRING, \T_STRING, \T_NAME_QUALIFIED, \T_NAME_FULLY_QUALIFIED, + \T_NAME_RELATIVE, \T_CLASS, \T_LINE, \T_FILE, \T_DIR, \T_CLASS_C, \T_TRAIT_C, \T_METHOD_C, \T_FUNC_C, \T_NS_C, + ]; + + /** Casts, emitted once their operand is computed. */ + private const CAST = [ + \T_INT_CAST, \T_DOUBLE_CAST, \T_STRING_CAST, \T_ARRAY_CAST, \T_OBJECT_CAST, \T_BOOL_CAST, + ]; + + /** Tokens a chain of property fetches is built of. */ + private const CHAIN = [ + \T_VARIABLE, \T_STRING, \T_NAME_QUALIFIED, \T_NAME_FULLY_QUALIFIED, \T_NAME_RELATIVE, \T_STATIC, + \T_OBJECT_OPERATOR, \T_NULLSAFE_OBJECT_OPERATOR, \T_DOUBLE_COLON, + ]; + + /** Openers of brackets that pair with `)`, `]` or `}`. */ + private const OPENER = ['(', '[', '{', '#[', '${']; + + /** + * Functions PHP compiles into dedicated opcodes, which take the lines of the arguments rather than the + * line of the call; `sprintf()` since PHP 8.4. Compared in lower case. + */ + private const COMPILED_FUNCTIONS = [ + 'strlen', 'is_null', 'is_bool', 'is_long', 'is_int', 'is_integer', 'is_float', 'is_double', 'is_string', + 'is_array', 'is_object', 'is_resource', 'is_scalar', 'boolval', 'intval', 'floatval', 'doubleval', + 'strval', 'defined', 'chr', 'ord', 'call_user_func_array', 'call_user_func', 'in_array', 'count', + 'sizeof', 'get_class', 'get_called_class', 'gettype', 'func_num_args', 'func_get_args', 'array_slice', + 'array_key_exists', 'sprintf', + ]; /** Literals a `match` can dispatch on through a jump table. */ private const JUMP_KEY = [\T_LNUMBER, \T_CONSTANT_ENCAPSED_STRING]; @@ -45,54 +112,91 @@ final class ExecutableLines /** Heads of top-level statements that compile to no opcode. */ private const DECLARATION = [ \T_NAMESPACE, \T_USE, \T_DECLARE, \T_CLASS, \T_INTERFACE, \T_TRAIT, \T_ENUM, - \T_ABSTRACT, \T_FINAL, \T_READONLY, \T_FUNCTION, \T_ATTRIBUTE, + \T_ABSTRACT, \T_FINAL, \T_READONLY, \T_FUNCTION, \T_ATTRIBUTE, \T_CONST, ]; + /** Heads of statements that never let the next one in the block run. */ + private const JUMP = [\T_RETURN, \T_THROW, \T_GOTO, \T_BREAK, \T_CONTINUE, \T_EXIT]; + /** Keywords that continue a compound statement rather than starting a new one. */ private const CONTINUATION = [\T_ELSE, \T_ELSEIF, \T_CATCH, \T_FINALLY]; /** Tokens after which a name followed by `:` is a `goto` label. */ private const STATEMENT_START = [';', '{', '}', ':']; - /** Modifiers that promote a parameter, compared by text: `private(set)` has a token of its own on PHP 8.4. */ - private const PROMOTION = ['public', 'protected', 'private', 'readonly', 'public(set)', 'protected(set)', 'private(set)']; - /** Tokens after which a declaration keyword is a name: of a method, a class member or a property. */ private const NAME_PREFIX = [\T_FUNCTION, \T_DOUBLE_COLON, \T_OBJECT_OPERATOR, \T_NULLSAFE_OBJECT_OPERATOR]; + /** Shapes of an argument that passes a literal or a constant. */ + private const LITERAL_ARGUMENT = [ + [\T_CONSTANT_ENCAPSED_STRING], [\T_LNUMBER], [\T_DNUMBER], [\T_STRING], [\T_NAME_FULLY_QUALIFIED], + [\T_STRING, \T_DOUBLE_COLON, \T_STRING], [\T_STRING, \T_DOUBLE_COLON, \T_CLASS], + [\T_NAME_QUALIFIED, \T_DOUBLE_COLON, \T_STRING], [\T_NAME_QUALIFIED, \T_DOUBLE_COLON, \T_CLASS], + [\T_NAME_FULLY_QUALIFIED, \T_DOUBLE_COLON, \T_STRING], [\T_NAME_FULLY_QUALIFIED, \T_DOUBLE_COLON, \T_CLASS], + ]; + /** Tokens after which `(` opens the argument list of a call. */ private const CALLEE = [ \T_STRING, \T_NAME_QUALIFIED, \T_NAME_FULLY_QUALIFIED, \T_NAME_RELATIVE, \T_VARIABLE, \T_STATIC, ')', ']', '}', ]; + /** + * Matching brackets of the source being scanned, so that finding the end of a call or a condition does + * not walk its tokens again for every nested one. + * + * @var array + */ + private static array $pairs = []; + /** * @return array, true> Line number => true. */ public static function of(string $source): array + { + return self::scan($source)[0]; + } + + /** + * Closing braces of function bodies that every driver lets the code fall through to, where the implicit + * `return` runs. + * + * Unlike {@see of()} this answers for a file a driver did load, so it leaves out nothing it cannot rule + * out, whatever line a driver reports elsewhere. + * + * @return array, true> Line number => true. + */ + public static function bodyEnds(string $source): array + { + return self::scan($source)[1]; + } + + /** + * @return array{array, true>, array, true>} The estimate and the body ends. + */ + private static function scan(string $source): array { $lines = []; + $ends = []; - # Contexts opened by `{`: 'func' (a function body), 'constant' (the body of a closure in a constant - # expression), 'class', 'block', 'match' (a `match` body), 'interp' (`{$` in a string). + # Contexts opened by `{`: 'func' (a function body), 'constant' (a body drivers do not report: a closure + # in a constant expression or a property hook), 'class', 'hooks', 'block', 'switch' and 'match' (their + # bodies), 'interp' (`{$` in a string or a member named by an expression). $stack = []; # Open `(` and `[` of the current brace context, saved and restored around nested ones. An array - # entry collects the lines of its constant elements until it closes and shows whether it folds. - /** @var list, call: bool, index: int, shape: list, held: array, resolved: bool}> $brackets */ + # entry collects the lines of its constant elements until it closes and shows whether it folds; a + # call entry reads its arguments one by one. + /** @var list, call: bool, shape: list, dynamic: bool, from: int|null, to: int|null}> $brackets */ $brackets = []; $savedBrackets = []; # What the next `{` opens, once a declaration keyword is seen, and for a function whether it is # an anonymous one in a constant expression. $pending = null; - $signatureLine = 0; - $promotes = false; $parens = 0; $constant = false; $anonymous = null; $resumes = false; - # A promoted parameter with hooks leaves the constructor signature without an opcode. - $hooked = false; # Signatures suspended by a closure in a default value or by hooks of a promoted parameter, and per # `constant` or `hooks` depth whether one resumes. $suspended = []; @@ -115,20 +219,55 @@ public static function of(string $source): array $className = null; # Depths of the hooks written as `get => expr;`, a body without braces. $shortHooks = []; + # Index of the last token of a code region that may compile to no opcode. + $muted = -1; + # Per brace depth: whether a string opened by a quote is being read. + $quotes = []; + # Bracket count of the arrow function whose signature is being read. + $arrowSignature = null; + # Unreachable code being read: its statement depth and first line; and the line ranges read so far. + $dead = null; + $deadRanges = []; + # Per depth of a `switch` body: whether it has a `default` and whether every way out of it returns. + $switches = []; + # Per brace depth: whether it is the body of a loop. + $loops = []; + # Per statement depth: whether the statement has an `?? throw`. + $coalesceThrows = []; + # Per statement depth: whether the last statement leaves only by an `?? throw`. + $coalesceExit = []; + # Whether the `while` or `for` being read never ends by its condition. + $endless = false; + # What the class being declared is; per class body depth the methods a call on `$this` binds while + # compiling, null for a trait; per function body depth whether it is a closure. + $classKind = null; + $bound = []; + $closures = []; + # Whether a namespace is open, so an unqualified function is resolved at runtime unless imported. + $namespaced = false; + $importsFunctions = false; # Per statement depth: the first token of the current statement, whether the last finished one # leaves the block, and the `if` or `try` it continues. $head = []; $exits = []; $compound = []; - # Per function body depth: the signature line and whether the body yields. - $signature = []; - $generator = []; # Per `match` body depth: what its arms dispatch on. $arms = []; $topHead = null; $tokens = \PhpToken::tokenize($source); + $use = false; + foreach ($tokens as $i => $t) { + # Text inside a string or around the tags may read `(`, `,` or `;`: a leading NUL keeps it from + # passing for punctuation, and keeps its line breaks. + $t->is([\T_ENCAPSED_AND_WHITESPACE, \T_INLINE_HTML]) and $t->text = "\0" . $t->text; + # A `use function`, plain or in a group, imports a function by its unqualified name. + $t->id === \T_USE && self::next($tokens, $i)?->text !== '(' and $use = true; + $use && $t->id === \T_FUNCTION and $importsFunctions = true; + $t->text === ';' and $use = false; + } + self::$pairs = self::pairs($tokens); foreach ($tokens as $i => $t) { if ($t->isIgnorable() || $t->is([\T_OPEN_TAG, \T_CLOSE_TAG])) { continue; @@ -162,15 +301,16 @@ public static function of(string $source): array break; } - # A heredoc that interpolates is assembled at runtime, starting on the line of its first text part. + # A heredoc that interpolates is assembled at runtime, starting on the line of its first text part + # when that part fits on one line; a longer one moves the start. if ($t->id === \T_START_HEREDOC) { $heredocText = null; } elseif ($t->id === \T_END_HEREDOC) { $heredocText = false; } elseif ($t->id === \T_ENCAPSED_AND_WHITESPACE) { - $heredocText ??= $t->line; + $heredocText ??= \str_contains($t->text, "\n") ? false : $t->line; } elseif (\is_int($heredocText)) { - $inCode and $lines[$heredocText] = true; + $inCode && $dead === null && $i > $muted and $lines[$heredocText] = true; $heredocText = false; } @@ -179,8 +319,10 @@ public static function of(string $source): array if ($returnLine !== null) { if ($t->text === '[' || $t->is([\T_ARRAY, \T_MATCH])) { $returnArray = $t->id !== \T_MATCH; - } else { - $lines[$returnLine] = true; + } elseif (self::endLine($tokens, $i) === $t->line) { + # A value spread over lines puts the opcode on a line that depends on its shape: leave it + # to the operations inside. + $lines[$t->text === ';' ? $returnLine : $t->line] = true; } $returnLine = null; } @@ -193,6 +335,7 @@ public static function of(string $source): array ); $t->id === \T_DOUBLE_COLON and $scope = $previous; + $t->id === \T_NAMESPACE && $atTop and $namespaced = self::next($tokens, $i)?->text !== '{'; $t->id === \T_STRING && $previous?->is(self::CLASS_LIKE) and $className = $t->text; # The lexer emits `T_ENUM` only before a name, so a soft-keyword `enum` never lands here. @@ -200,30 +343,36 @@ public static function of(string $source): array $anonymous === null && $pending === 'func' and $anonymous = false; } elseif ($t->is(self::CLASS_LIKE)) { $pending = 'class'; + $classKind = $t->id; } elseif ($t->id === \T_FUNCTION) { + # A private or final method declared so far is bound while compiling when called on `$this`. + ($stack[$depth - 1] ?? null) === 'class' && isset($bound[$depth]) && self::bindsOnThis($tokens, $i) + and $bound[$depth][\strtolower((string) self::methodName($tokens, $i))] = true; # A closure as a default value suspends the signature it sits in until it closes. $resumes = $pending === 'func'; - $resumes and $suspended[] = [$signatureLine, $promotes, $parens, $constant, $anonymous, $hooked]; - $hooked = false; + $resumes and $suspended[] = [$parens, $constant, $anonymous]; # A closure outside running code belongs to a constant expression: an attribute, a constant # or a default value. Drivers never report its body. $constant = !$inCode || $resumes; $anonymous = null; $pending = 'func'; - $signatureLine = $t->line; - $promotes = false; $parens = 0; } elseif ($anonymous === null && $pending === 'func' && $t->text !== '&') { # A method may be named by a keyword (`print`, `array`), so only `(` tells a closure. $anonymous = $t->text === '('; } - # Parameters, `use` and the return type compile to no opcode on their own lines. - $inSignature = $pending === 'func' && $t->id !== \T_FUNCTION; + # A `while` or `for` whose condition is always true leaves only through a `break`. + $t->is([\T_WHILE, \T_FOR]) and $endless = self::endless($tokens, $i); + + # Parameters, `use` and the return type compile to no opcode on their own lines; those of an arrow + # function run up to its `=>`. + $t->id === \T_DOUBLE_ARROW && $arrowSignature === \count($brackets) and $arrowSignature = null; + $inSignature = ($pending === 'func' && $t->id !== \T_FUNCTION) || ($arrowSignature !== null && $t->id !== \T_FN); + $t->id === \T_FN and $arrowSignature = \count($brackets); if ($pending === 'func') { $t->text === '(' and $parens++; $t->text === ')' and $parens--; - $parens > 0 && \in_array(\strtolower($t->text), self::PROMOTION, true) and $promotes = true; # A body-less method: abstract or declared by an interface. $t->text === ';' && $parens === 0 and $pending = null; } @@ -232,42 +381,49 @@ public static function of(string $source): array $interpolation = $t->is([\T_CURLY_OPEN, \T_DOLLAR_OPEN_CURLY_BRACES]); if ($t->text === '{' || $interpolation) { $brackets !== [] && !$interpolation and self::markRuntime($brackets); + # A member or variable named by an expression, `$o->{$name}`, is one more part of it. + $interpolation = $interpolation || $previous?->is([\T_OBJECT_OPERATOR, \T_NULLSAFE_OBJECT_OPERATOR, \T_DOUBLE_COLON]) + || $previous?->text === '$'; if ($interpolation) { $stack[] = 'interp'; } elseif ($pending === 'func' && $parens > 0) { # Hooks of a promoted parameter: the signature resumes after them. $stack[] = 'hooks'; - $suspended[] = [$signatureLine, $promotes, $parens, $constant, $anonymous, true]; + $suspended[] = [$parens, $constant, $anonymous]; $resume[$depth + 1] = true; $pending = null; } elseif ($property && $pending === null && ($stack[$depth - 1] ?? null) === 'class') { $stack[] = 'hooks'; $resume[$depth + 1] = false; } elseif ($pending === null && ($stack[$depth - 1] ?? null) === 'hooks') { - # The body of a property hook. - $stack[] = 'func'; - $signature[$depth + 1] = $t->line; - $generator[$depth + 1] = false; + # The body of a property hook: PCOV before PHP 8.6 leaves it out, Xdebug reports it only once run. + $stack[] = 'constant'; + $resume[$depth + 1] = false; } elseif ($pending === 'func' && $parens === 0 && $constant && $anonymous) { $stack[] = 'constant'; $resume[$depth + 1] = $resumes; $pending = null; } elseif ($pending !== null && $parens === 0) { $stack[] = $pending; - if ($pending === 'func') { - $promotes && !$hooked and $lines[$signatureLine] = true; - $signature[$depth + 1] = $signatureLine; - $generator[$depth + 1] = false; - } + # The scope of a trait is unknown while compiling, so nothing is bound in it. + $pending === 'class' and $bound[$depth + 1] = $classKind === \T_TRAIT ? null : []; + $pending === 'func' and $closures[$depth + 1] = $anonymous === true; $pending = null; } elseif ($header !== null && $header['kind'] === 'match' && $header['at'] === \count($brackets)) { $stack[] = 'match'; $arms[$depth + 1] = ['line' => $header['line'], 'keys' => 0, 'type' => null, 'table' => true, 'cond' => [], 'inCond' => true]; + } elseif ($header !== null && $header['kind'] === 'switch' && $header['at'] === \count($brackets)) { + $stack[] = 'switch'; + $switches[$depth + 1] = ['default' => false, 'exits' => true]; } else { # A block at the top level, such as `namespace X { … }`, holds statements of its own. $atTop and $topHead = null; $stack[] = 'block'; + $loops[$depth + 1] = ($head[$level] ?? null)?->is([\T_FOR, \T_FOREACH, \T_WHILE, \T_DO]) + ? ['endless' => $endless && ($head[$level] ?? null)?->is([\T_FOR, \T_WHILE]), 'breaks' => false] + : null; } + $endless = false; $header !== null && $header['at'] === \count($brackets) and $header = null; $head[$depth + 1] = null; $exits[$depth + 1] = false; @@ -284,29 +440,48 @@ public static function of(string $source): array $closing = \array_pop($stack); $brackets = \array_pop($savedBrackets) ?? []; $leaves = self::statementExits($exits[$depth] ?? false, $compound[$depth] ?? null); - unset($head[$depth], $exits[$depth], $compound[$depth]); + # Whether the body leaves in the eyes of every driver, Xdebug's reading of `?? throw` aside. + $leavesForAll = $leaves && !($coalesceExit[$depth] ?? false); + $loop = $loops[$depth] ?? null; + unset($head[$depth], $exits[$depth], $compound[$depth], $coalesceThrows[$depth], $coalesceExit[$depth], + $loops[$depth], $bound[$depth], $closures[$depth]); $property = false; + # Unreachable code ends with the block it is in; the brace of a body it ends is unreachable too. + if ($dead !== null && $dead['level'] === $depth) { + $deadRanges[] = [$dead['from'], $t->line]; + $leavesForAll = !$dead['coalesce']; + $dead = null; + $leaves = true; + } + if ($closing === 'constant' || $closing === 'hooks') { if ($resume[$depth]) { - [$signatureLine, $promotes, $parens, $constant, $anonymous, $hooked] = \array_pop($suspended); + [$parens, $constant, $anonymous] = \array_pop($suspended); $pending = 'func'; } unset($resume[$depth]); } elseif ($closing === 'func') { # Falling off the end of a body runs an implicit `return` on its closing brace. $leaves or $lines[$t->line] = true; - # A generator is created when the call starts, on the signature. - $generator[$depth] and $lines[$signature[$depth]] = true; - # A closure passed to a call is sent from the line it ends on. - $brackets !== [] && \end($brackets)['call'] and $lines[$t->line] = true; - unset($signature[$depth], $generator[$depth]); + $leavesForAll or $ends[$t->line] = true; + # Xdebug sends a closure passed to a call from the line it ends on. + $brackets !== [] && \end($brackets)['call'] and $ends[$t->line] = true; } elseif ($closing === 'match') { $a = self::endArmCondition($arms[$depth]); # Literal keys of one type let PHP dispatch through a table, an opcode on the subject line. $a['table'] && $a['keys'] >= 2 and $lines[$a['line']] = true; unset($arms[$depth]); + } elseif ($closing === 'switch') { + # With a `default` and every case group leaving, nothing gets past the `switch`. + $s = $switches[$depth]; + unset($switches[$depth]); + $parent = $depth - 1; + $compound[$parent] = null; + $exits[$parent] = $s['default'] && $s['exits'] && $leaves; + $coalesceExit[$parent] = $exits[$parent] && !$leavesForAll; + $head[$parent] = null; } elseif ($closing === 'block') { $parent = $depth - 1; $opener = $head[$parent] ?? null; @@ -316,7 +491,9 @@ public static function of(string $source): array : $compound[$parent]['exits'] = $compound[$parent]['exits'] && $leaves; } else { $compound[$parent] = null; - $exits[$parent] = false; + # Nothing gets past an endless loop no `break` leaves. + $exits[$parent] = $loop !== null && $loop['endless'] && !$loop['breaks']; + $coalesceExit[$parent] = false; } $head[$parent] = null; } @@ -332,10 +509,8 @@ public static function of(string $source): array # A short property hook, `get => expr;`, is a body without braces. $short = \end($shortHooks); if ($t->id === \T_DOUBLE_ARROW && $brackets === [] && ($stack[$depth - 1] ?? null) === 'hooks') { - $stack[] = 'func'; + $stack[] = 'constant'; $shortHooks[] = $depth + 1; - $signature[$depth + 1] = $t->line; - $generator[$depth + 1] = false; $head[$depth + 1] = null; $exits[$depth + 1] = false; $compound[$depth + 1] = null; @@ -347,7 +522,7 @@ public static function of(string $source): array \array_pop($stack); \array_pop($shortHooks); $brackets = \array_pop($savedBrackets) ?? []; - unset($head[$depth], $exits[$depth], $compound[$depth], $signature[$depth], $generator[$depth]); + unset($head[$depth], $exits[$depth], $compound[$depth]); while (\end($arrows) !== false && \end($arrows)[0] >= $depth) { \array_pop($arrows); } @@ -356,8 +531,11 @@ public static function of(string $source): array continue; } - if ($t->text === '(' || $t->text === '[') { - $isArray = $t->text === '[' || $previous?->id === \T_ARRAY; + # Arguments of an attribute are a constant expression. + $t->id === \T_ATTRIBUTE and $muted = \max($muted, self::closer($tokens, $i)); + + if ($t->text === '(' || $t->text === '[' || $t->id === \T_ATTRIBUTE) { + $isArray = $t->text !== '(' || $previous?->id === \T_ARRAY; # A call keeps the enclosing array from folding. !$isArray && $brackets !== [] && !$previous?->is(self::NEUTRAL) and self::markRuntime($brackets); $top = \array_key_last($brackets); @@ -368,23 +546,22 @@ public static function of(string $source): array 'const' => true, 'weak' => [], 'call' => !$isArray && !$inSignature && $previous?->is(self::CALLEE), - 'index' => 0, 'shape' => [], - 'held' => [], - 'resolved' => ($previous?->id === \T_NAME_FULLY_QUALIFIED && self::builtInFunction($previous->text)) - || ($previous?->id === \T_STRING && $beforePrevious?->id === \T_DOUBLE_COLON - && self::knownWhileCompiling($scope, $className)), + # Inside an array literal the arguments of a call are sent from lines of their own, and + # inside code compiled out they are not sent at all. + 'dynamic' => !$isArray && !$inSignature && $inCode && $i > $muted + && !\in_array('[', \array_column($brackets, 'type'), true) + && self::boundAtRuntime($tokens, $i, self::thisMethods($stack, $bound, $closures, $arrows), $namespaced && !$importsFunctions), + 'from' => null, + 'to' => null, ]; } elseif ($t->text === ')' || $t->text === ']') { $closed = \array_pop($brackets); - $closed !== null && $closed['call'] and $lines += self::argumentLines($closed); + $closed !== null && $closed['call'] && $dead === null && $i > $muted and $lines += self::argumentLine($closed); if ($closed !== null && $closed['type'] === '[' && $inCode && !$inSignature) { if (!$closed['const']) { $lines += $closed['weak']; $brackets === [] or self::markRuntime($brackets); - } elseif ((\end($brackets)['type'] ?? null) === '(') { - # A constant array passed as an argument is sent from the line it starts on. - $lines[$closed['line']] = true; } elseif ($returnArray) { # An empty array returned: nothing else took the `return`. $lines[$closed['line']] = true; @@ -428,43 +605,117 @@ public static function of(string $source): array unset($a); } - $marks = $significant && $inCode && !$inSignature && !$t->is(self::INERT) - && ($header === null || ($header['kind'] === 'match' && $t->is(self::SUBJECT_OPCODE))); + # A statement after one that leaves the block cannot run, up to a label a jump may reach. + if ($inBody && $significant && ($head[$level] ?? null) === null) { + $label = $t->is([\T_CASE, \T_DEFAULT]) || ($t->id === \T_STRING && self::next($tokens, $i)?->text === ':'); + if ($dead === null && !$label && !$t->is(self::CONTINUATION) + && self::statementExits($exits[$level] ?? false, $compound[$level] ?? null) + ) { + $dead = ['level' => $level, 'from' => $t->line, 'coalesce' => $coalesceExit[$level] ?? false]; + } elseif ($dead !== null && $label && $dead['level'] === $level) { + $deadRanges[] = [$dead['from'], $t->line - 1]; + $dead = null; + } + } + + # A `break` leaves the innermost loop or `switch`, `break 2` the next one too; a `continue` leaves + # a `switch` the same way but stays in a loop. + if ($t->is([\T_BREAK, \T_CONTINUE])) { + $numbered = self::next($tokens, $i)?->id === \T_LNUMBER; + for ($d = $depth; $d > 0; $d--) { + if ($stack[$d - 1] === 'switch') { + $switches[$d]['exits'] = false; + } elseif (isset($loops[$d])) { + $t->id === \T_BREAK and $loops[$d]['breaks'] = true; + } else { + continue; + } + if (!$numbered) { + break; + } + } + } + + # A quote closes the string it opened at the same depth; the closing one starts nothing. + $closingQuote = false; + if ($t->text === '"' || $t->text === '`') { + $closingQuote = $quotes[$depth] ?? false; + $quotes[$depth] = !$closingQuote; + } + + # The `:` of a ternary is the only punctuation that may start an operation. + $code = ($significant || ($t->text === ':' && self::ternaryColon($tokens, $i))) + && $inCode && !$inSignature && !$t->is(self::INERT) && $i > $muted && $dead === null; + + # `zend.assertions=-1` compiles an assertion out, and runs merged into one report may differ in it. + if ($code && self::callsAssert($tokens, $i)) { + $muted = self::closer($tokens, self::nextIndex($tokens, $i)); + $code = false; + } - if ($marks && $t->is([\T_RETURN, \T_YIELD])) { + # A logical operator after a constant operand may be decided while compiling, dropping the rest. + if ($code && $t->is([\T_BOOLEAN_AND, \T_BOOLEAN_OR, \T_LOGICAL_AND, \T_LOGICAL_OR]) && self::constantBefore($tokens, $i)) { + $muted = self::endIndex($tokens, self::nextIndex($tokens, $i)); + $code = false; + } + + # An `if` decided while compiling drops the branch not taken, and the decision may differ between + # the PHP versions of runs merged into one report. + if ($code && $t->is([\T_IF, \T_ELSEIF]) && self::foldableCondition($tokens, $i)) { + $muted = \max($muted, self::chainEnd($tokens, $i)); + $code = false; + } + + if ($code && $t->is([\T_RETURN, \T_YIELD])) { $returnLine = $t->line; - $marks = false; + $code = false; } - if ($marks && \end($brackets) !== false && \end($brackets)['type'] === '[' && !$t->is(self::RUNTIME)) { - if ($returnArray) { - $returnArray = false; - } else { - # Held until the array closes: a constant array leaves its element lines empty. - $brackets[\array_key_last($brackets)]['weak'][$t->line] = true; - $marks = false; - } + # A line is executable when an operation starts on it: an operand alone leaves its value to the + # operation that consumes it, on the line that operation starts on. + $marks = $code && !$closingQuote && ( + self::operates($tokens, $i, $previous) + # The result of a `match` arm, when it fits on one line. + || ($depth > 0 && $stack[$depth - 1] === 'match' && $brackets === [] && $previous?->id === \T_DOUBLE_ARROW + && self::endLine($tokens, $i) === $t->line) + ); + + $open = \end($brackets); + # Inside an array literal the operations of an element are emitted in an order of its own. + $open !== false && $open['type'] === '[' && ($t->is(self::BINARY) || $t->text === ':') and $marks = false; + # An element of an array built at runtime, `key => $value`, is added on its line unless the array + # is an element of another one. + $code && $open !== false && $open['type'] === '[' && $t->id === \T_VARIABLE + && $previous?->id === \T_DOUBLE_ARROW && $previous->line === $t->line + && \in_array(self::next($tokens, $i)?->text, [',', ']'], true) + && (($brackets[\count($brackets) - 2] ?? null)['type'] ?? null) !== '[' + and $marks = true; + if ($code && $returnArray && $open !== false && $open['type'] === '[') { + # The first element of a returned array literal carries the `return`, when it fits on its line. + $returnArray = false; + self::endLine($tokens, $i) === $t->line and $lines[$t->line] = true; + $marks = false; + } elseif ($marks && $open !== false && $open['type'] === '[' && !$t->is(self::RUNTIME)) { + # Held until the array closes: a constant array leaves its element lines empty. + $brackets[\array_key_last($brackets)]['weak'][$t->line] = true; + $marks = false; } - # Arguments of a call: a line that only passes a variable gets no opcode of its own. + # Arguments of a call: what each one is built of, and the lines it spans. $top = \array_key_last($brackets); if ($top !== null && $brackets[$top]['call'] && $t->text !== '(' && $t->text !== '[') { if ($t->text === ',') { - $lines += self::argumentLines($brackets[$top]); - $brackets[$top]['index']++; + $dead === null and $lines += self::argumentLine($brackets[$top]); $brackets[$top]['shape'] = []; - $brackets[$top]['held'] = []; + $brackets[$top]['from'] = $brackets[$top]['to'] = null; } else { $brackets[$top]['shape'][] = $t->id; - $marks and $brackets[$top]['held'][$t->line] = true; - $marks = false; + $brackets[$top]['from'] ??= $t->line; + $brackets[$top]['to'] = $t->line + \substr_count($t->text, "\n"); } } if ($inBody) { - # A `yield` in an arrow function makes that one a generator, not the enclosing function. - $t->is([\T_YIELD, \T_YIELD_FROM]) && (\end($arrows)[0] ?? null) !== $depth - and $generator[$funcDepth] = true; $marks and $lines[$t->line] = true; if ($significant && ($head[$level] ?? null) === null) { @@ -477,7 +728,8 @@ public static function of(string $source): array $compound[$level] = null; } } - if ($t->id === \T_ELSE && ($compound[$level] ?? null) !== null) { + # `else if` goes on with the chain, as `elseif` does. + if ($t->id === \T_ELSE && ($compound[$level] ?? null) !== null && self::next($tokens, $i)?->id !== \T_IF) { $compound[$level]['else'] = true; } if ($t->id === \T_FINALLY && ($compound[$level] ?? null) !== null) { @@ -485,6 +737,9 @@ public static function of(string $source): array $compound[$level]['exits'] or $lines[$t->line] = true; } + # Xdebug takes the code after `?? throw` for unreachable. + $t->id === \T_THROW && $previous?->id === \T_COALESCE and $coalesceThrows[$level] = true; + # A `goto` label and the `default:` of a `switch` are jump targets, not code. if ($t->text === ':' && $brackets === [] && ( $previous?->id === \T_DEFAULT @@ -494,8 +749,21 @@ public static function of(string $source): array $head[$level] = null; } + # A `case` or `default` label starts a group of statements reached by a jump. + if ($t->text === ':' && $brackets === [] && ($stack[$level - 1] ?? null) === 'switch' + && ($previous?->id === \T_DEFAULT || ($head[$level] ?? null)?->id === \T_CASE) + ) { + $previous?->id === \T_DEFAULT and $switches[$level]['default'] = true; + $head[$level] = null; + $exits[$level] = $coalesceExit[$level] = false; + $compound[$level] = null; + } + if ($t->text === ';' && $brackets === [] && $level === $depth) { - $exits[$level] = ($head[$level] ?? null)?->is([\T_RETURN, \T_THROW]) ?? false; + $jumps = ($head[$level] ?? null)?->is(self::JUMP) ?? false; + $coalesceExit[$level] = !$jumps && isset($coalesceThrows[$level]); + $exits[$level] = $jumps || $coalesceExit[$level]; + unset($coalesceThrows[$level]); $head[$level] = null; $compound[$level] = null; } @@ -512,9 +780,14 @@ public static function of(string $source): array } $returnLine === null or $lines[$returnLine] = true; + $dead === null or $deadRanges[] = [$dead['from'], \PHP_INT_MAX]; + foreach ($deadRanges as [$from, $to]) { + $lines = \array_filter($lines, static fn(int $line): bool => $line < $from || $line > $to, \ARRAY_FILTER_USE_KEY); + } \ksort($lines); + self::$pairs = []; - return $lines; + return [$lines, $ends]; } /** @@ -577,22 +850,123 @@ private static function endArmCondition(array $arms): array } /** - * Lines of the argument just read that carry an opcode. + * The line of the argument just read when sending it is an opcode of its own. * - * Passing a variable, plain or named, gets no line of its own unless it is the first argument or the - * callee is bound while compiling: a fully qualified built-in function, or a static method of a class - * {@see knownWhileCompiling() known} at that moment. + * A callee bound only at runtime is sent a literal by an opcode on the literal's line. A callee PHP may + * bind while compiling is sent it by an opcode that drivers leave out, and a variable is sent to any + * callee that way. * - * @param array{index: int, shape: list, held: array, resolved: bool} $call + * @param array{shape: list, dynamic: bool, from: int|null, to: int|null} $call * @return array */ - private static function argumentLines(array $call): array + private static function argumentLine(array $call): array { $shape = $call['shape']; - $passesVariable = $shape === [\T_VARIABLE] - || (\count($shape) === 3 && $shape[1] === \ord(':') && $shape[2] === \T_VARIABLE); + # A named argument, `name: value`. + \count($shape) > 2 && $shape[0] === \T_STRING && $shape[1] === \ord(':') and $shape = \array_slice($shape, 2); + $literal = \in_array($shape, self::LITERAL_ARGUMENT, true) + || (($shape[0] ?? null) === \ord('-') && \in_array(\array_slice($shape, 1), [[\T_LNUMBER], [\T_DNUMBER]], true)); + + return $call['dynamic'] && $literal && $call['from'] !== null && $call['from'] === $call['to'] + ? [$call['from'] => true] + : []; + } - return $passesVariable && $call['index'] > 0 && !$call['resolved'] ? [] : $call['held']; + /** + * Whether the call whose argument list opens at `$open` is bound only at runtime. + * + * PHP binds while compiling a function or a static method it finds loaded, which depends on the run, + * and a method called on `$this` that is private or final and declared above; since PHP 8.6 also the + * constructor of a loaded class. A closure in a variable, a method of another object, `parent::` and + * `static::` calls and, in a namespace, an unqualified function not imported are left to runtime. + * + * @param list<\PhpToken> $tokens + * @param array|null $thisMethods Methods a call on `$this` binds, or null when none. + * @param bool $fallback Whether an unqualified function name is resolved at runtime. + */ + private static function boundAtRuntime(array $tokens, int $open, ?array $thisMethods, bool $fallback): bool + { + # The open tag always comes first, so a bracket has a token before it. + $c = self::previousIndex($tokens, $open); + $callee = $tokens[$c]; + if ($callee->id === \T_VARIABLE) { + return true; + } + + $before = $tokens[$b = self::previousIndex($tokens, $c)] ?? null; + if ($callee->id !== \T_STRING || $before?->id === \T_NEW) { + return false; + } + if ($before?->is([\T_OBJECT_OPERATOR, \T_NULLSAFE_OBJECT_OPERATOR])) { + return ($tokens[self::previousIndex($tokens, $b)] ?? null)?->text !== '$this' + || $thisMethods === null + || !isset($thisMethods[\strtolower($callee->text)]); + } + if ($before?->id === \T_DOUBLE_COLON) { + $class = $tokens[self::previousIndex($tokens, $b)] ?? null; + + return $class?->id === \T_STATIC || \strcasecmp((string) $class?->text, 'parent') === 0; + } + + return $fallback && !$before?->is([\T_FUNCTION, \T_FN]) && \strcasecmp($callee->text, 'assert') !== 0; + } + + /** + * Methods a call on `$this` binds while compiling at the current token, or null when the scope is not + * known then: outside a class, in a trait or in a closure, which may be bound to another object. + * + * @param list $stack + * @param array|null> $bound + * @param array $closures + * @param list $arrows + * @return array|null + */ + private static function thisMethods(array $stack, array $bound, array $closures, array $arrows): ?array + { + if ($arrows !== []) { + return null; + } + for ($d = \count($stack); $d > 0; $d--) { + if ($stack[$d - 1] === 'func' && ($closures[$d] ?? false)) { + return null; + } + if ($stack[$d - 1] === 'class') { + return $bound[$d] ?? null; + } + } + + return null; + } + + /** + * Whether the method declared by the `function` at `$i` is private or final. + * + * @param list<\PhpToken> $tokens + */ + private static function bindsOnThis(array $tokens, int $i): bool + { + while (($i = self::previousIndex($tokens, $i)) >= 0 + && $tokens[$i]->is([\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_STATIC, \T_ABSTRACT, \T_READONLY]) + ) { + if ($tokens[$i]->is([\T_PRIVATE, \T_FINAL])) { + return true; + } + } + + return false; + } + + /** + * Name of the function declared by the `function` at `$i`, or null for a closure. + * + * @param list<\PhpToken> $tokens + */ + private static function methodName(array $tokens, int $i): ?string + { + $name = self::next($tokens, $i); + $name?->text === '&' and $name = self::next($tokens, self::nextIndex($tokens, $i)); + + return $name === null || $name->text === '(' ? null : $name->text; } /** @@ -602,18 +976,509 @@ private static function argumentLines(array $call): array */ private static function next(array $tokens, int $i): ?\PhpToken { - while (isset($tokens[++$i])) { - if (!$tokens[$i]->isIgnorable()) { - return $tokens[$i]; + return $tokens[self::nextIndex($tokens, $i)] ?? null; + } + + /** + * Index of the next token after `$i` that is not whitespace or a comment, or the token count. + * + * @param list<\PhpToken> $tokens + */ + private static function nextIndex(array $tokens, int $i): int + { + while (isset($tokens[++$i]) && $tokens[$i]->isIgnorable()); + + return $i; + } + + /** + * Index of the previous token before `$i` that is not whitespace or a comment, or -1. + * + * @param list<\PhpToken> $tokens + */ + private static function previousIndex(array $tokens, int $i): int + { + while (isset($tokens[--$i]) && $tokens[$i]->isIgnorable()); + + return $i; + } + + /** + * Index of the bracket closing the one opened at `$open`, or of the last token. + * + * @param list<\PhpToken> $tokens + */ + private static function closer(array $tokens, int $open): int + { + return self::$pairs[$open] ?? \count($tokens) - 1; + } + + /** + * Pairs of matching brackets, both ways: opener index => closer index and closer index => opener index. + * + * @param list<\PhpToken> $tokens + * @return array + */ + private static function pairs(array $tokens): array + { + $pairs = []; + $open = []; + foreach ($tokens as $i => $t) { + if (\in_array($t->text, self::OPENER, true)) { + $open[] = $i; + } elseif (($t->text === ')' || $t->text === ']' || $t->text === '}') && $open !== []) { + $o = \array_pop($open); + $pairs[$o] = $i; + $pairs[$i] = $o; } } - return null; + return $pairs; + } + + /** + * Line of the last token of the expression starting at `$i`: up to a `;` or `,` outside brackets, or + * the bracket that encloses it. + * + * @param list<\PhpToken> $tokens + * @param bool $colon Whether a `:` outside brackets ends the expression too: the first branch of a ternary. + */ + private static function endLine(array $tokens, int $i, bool $colon = false): int + { + $last = $tokens[self::endIndex($tokens, $i, $colon)]; + + return $last->line + \substr_count($last->text, "\n"); + } + + /** + * Index of the last token of the expression starting at `$i`, as {@see endLine()} bounds it. + * + * @param list<\PhpToken> $tokens + */ + private static function endIndex(array $tokens, int $i, bool $colon = false): int + { + $end = $i; + $depth = 0; + for ($count = \count($tokens); $i < $count; $i++) { + $t = $tokens[$i]; + if ($t->isIgnorable()) { + continue; + } + if (\in_array($t->text, self::OPENER, true)) { + $depth++; + } elseif ($t->text === ')' || $t->text === ']' || $t->text === '}') { + if (--$depth < 0) { + break; + } + } elseif ($depth === 0 && ($t->text === ';' || $t->text === ',' || $t->id === \T_CLOSE_TAG + || ($colon && $t->text === ':')) + ) { + break; + } + $end = $i; + } + + return $end; + } + + /** + * Whether the operand before the operator at `$i` is built of literals and constants alone, from the + * start of its expression: PHP may fold it and drop what it decides. + * + * @param list<\PhpToken> $tokens + */ + private static function constantBefore(array $tokens, int $i): bool + { + # The walk stops at the open tag at the latest: it is neither a boundary nor foldable. + $any = false; + do { + $t = $tokens[$i = self::previousIndex($tokens, $i)]; + if ($t->is([\T_RETURN, \T_DOUBLE_ARROW]) || \in_array($t->text, ['(', '=', ',', ';', '{', '[', '?', ':'], true)) { + return $any; + } + $any = true; + } while ($t->is([...self::FOLDABLE, \T_DOUBLE_COLON, \T_IS_EQUAL, \T_IS_NOT_EQUAL, \T_IS_IDENTICAL, + \T_IS_NOT_IDENTICAL, \T_IS_SMALLER_OR_EQUAL, \T_IS_GREATER_OR_EQUAL, '<', '>', '!'])); + + return false; + } + + /** + * Whether the token at `$i` starts an operation that compiles to an opcode on its own line. + * + * @param list<\PhpToken> $tokens + */ + private static function operates(array $tokens, int $i, ?\PhpToken $previous): bool + { + $t = $tokens[$i]; + $nextIndex = self::nextIndex($tokens, $i); + $next = $tokens[$nextIndex] ?? null; + + # A closure is created where it starts; a named function declared in code is bound while compiling. + if ($t->is([\T_FUNCTION, \T_FN])) { + return $next?->text === '(' || ($next?->text === '&' && self::next($tokens, $nextIndex)?->text === '('); + } + + # A `case` compares on its line, unless PHP resolves its label into a jump table. + if ($t->id === \T_CASE) { + return $next !== null && ($next->is([\T_LNUMBER, \T_DNUMBER, \T_CONSTANT_ENCAPSED_STRING, \T_VARIABLE]) + || \in_array(\strtolower($next->text), ['true', 'false', 'null'], true)); + } + + # A keyword that consumes a value is emitted once the value is computed. + if ($t->is(self::CONSUMER)) { + return self::endLine($tokens, $nextIndex) === $t->line; + } + + if ($t->is(self::ACTION) || $t->text === '@') { + return true; + } + + # An assignment takes the line its target starts on. A compound one is emitted once its value is + # computed, so a value spread over lines moves it. + if ($t->text === '=') { + return self::targetStartsOn($tokens, $i, $t->line); + } + if ($t->is(self::ASSIGNMENT)) { + return self::targetStartsOn($tokens, $i, $t->line) && self::endLine($tokens, $nextIndex) === $t->line; + } + + # A string that interpolates, or a shell command, is assembled where it starts, unless its first part + # breaks the line. + if ($t->text === '"' || $t->text === '`') { + return !($next?->id === \T_ENCAPSED_AND_WHITESPACE && \str_contains($next->text, "\n")); + } + + # A condition on one line puts its jump there; a longer one leaves it to the operations inside, and + # a constant one may compile to no jump at all. + if ($t->is([\T_IF, \T_ELSEIF, \T_WHILE, \T_FOREACH])) { + $close = self::closer($tokens, $nextIndex); + # An endless `while` jumps back to its condition line. + if ($t->id === \T_WHILE && self::endless($tokens, $i)) { + return $tokens[$close]->line === $t->line; + } + for ($k = $nextIndex + 1; $k < $close; $k++) { + if ($tokens[$k]->is([\T_VARIABLE, \T_OBJECT_OPERATOR, \T_NULLSAFE_OBJECT_OPERATOR]) || $tokens[$k]->text === '(') { + return $tokens[$close]->line === $t->line; + } + } + + return false; + } + + # A unary operation is emitted after its operand; a literal operand folds. + if ($t->is(self::CAST) || $t->text === '!' || $t->text === '~') { + $operand = self::operandStart($tokens, $nextIndex); + + return $operand !== null && !$operand->is(self::FOLDABLE) && self::operandEndLine($tokens, $nextIndex) === $t->line; + } + + # A branch of a ternary that fits on one line is assigned on its line. + if (($t->text === '?' && $previous?->is(self::OPERAND_END)) || ($t->text === ':' && self::ternaryColon($tokens, $i))) { + $branch = $next !== null && $next->line === $t->line && $next->text !== '[' && $next->id !== \T_ARRAY + && self::endLine($tokens, $nextIndex, $t->text === '?') === $t->line; + if ($branch || $t->text === ':') { + return $branch; + } + } + + # A binary operation is emitted after its operands; two literal operands fold. A short-circuit + # jump follows the left operand alone. + if ($t->is(self::BINARY)) { + if ($previous === null || $previous->line !== $t->line || !$previous->is(self::OPERAND_END)) { + return false; + } + if ($previous->text === ')' || $previous->text === ']') { + $open = self::opener(self::previousIndex($tokens, $i)); + if ($tokens[$open]->line !== $t->line) { + return false; + } + } + $operand = self::operandStart($tokens, $nextIndex); + if ($operand === null || $operand->line !== $t->line || ($previous->is(self::FOLDABLE) && $operand->is(self::FOLDABLE))) { + return false; + } + + return $t->is(self::SHORT_CIRCUIT) || self::operandEndLine($tokens, $nextIndex) === $t->line; + } + + if (!$t->is([...self::CHAIN, \T_ISSET, \T_EMPTY, \T_UNSET]) || $t->is(self::NAME_PREFIX)) { + return false; + } + + if ($next?->text === '(') { + # `isset()`, `empty()` and `unset()` take the line of their argument. + if ($t->is([\T_ISSET, \T_EMPTY, \T_UNSET])) { + return self::next($tokens, $nextIndex)?->line === $t->line; + } + $multiLine = $tokens[self::closer($tokens, $nextIndex)]->line !== $t->line; + + return !($multiLine && $t->is([\T_STRING, \T_NAME_FULLY_QUALIFIED]) && self::compiledFunction($t->text)); + } + + # A property fetch takes the line its object starts on. + if ($previous?->is([\T_OBJECT_OPERATOR, \T_NULLSAFE_OBJECT_OPERATOR])) { + return self::chainStartsOn($tokens, $i, $t->line); + } + + # A static property; a class constant may fold. + return $previous?->id === \T_DOUBLE_COLON && $t->id === \T_VARIABLE && self::chainStartsOn($tokens, $i, $t->line); } /** - * Whether PHP knows the class before `::` while compiling, so its constant folds into the value and - * a call of its method is bound in advance. + * Whether the `:` at `$i` separates the branches of a ternary. + * + * @param list<\PhpToken> $tokens + */ + private static function ternaryColon(array $tokens, int $i): bool + { + $depth = 0; + while (($i = self::previousIndex($tokens, $i)) >= 0) { + $t = $tokens[$i]; + if ($t->text === ')' || $t->text === ']' || $t->text === '}') { + $depth++; + } elseif (\in_array($t->text, self::OPENER, true)) { + if (--$depth < 0) { + return false; + } + } elseif ($depth === 0) { + if ($t->text === '?') { + return true; + } + if ($t->text === ';' || $t->text === ',' || $t->text === ':' || $t->is([\T_DOUBLE_ARROW, \T_CASE, \T_DEFAULT])) { + return false; + } + } + } + + return false; + } + + /** + * The first token of the operand starting at `$i`, past opening parentheses. + * + * @param list<\PhpToken> $tokens + */ + private static function operandStart(array $tokens, int $i): ?\PhpToken + { + while (($tokens[$i] ?? null)?->text === '(') { + $i = self::nextIndex($tokens, $i); + } + + return $tokens[$i] ?? null; + } + + /** + * Line the operand starting at `$i` ends on: a name, variable or literal with the fetches, calls and + * brackets that follow it. + * + * @param list<\PhpToken> $tokens + */ + private static function operandEndLine(array $tokens, int $i): int + { + $line = $tokens[$i]->line; + $prefix = true; + while (isset($tokens[$i])) { + $t = $tokens[$i]; + if (\in_array($t->text, self::OPENER, true)) { + $i = self::closer($tokens, $i); + } elseif ($t->text === '"') { + while (isset($tokens[++$i]) && $tokens[$i]->text !== '"'); + } elseif ($t->id === \T_START_HEREDOC) { + while (isset($tokens[++$i]) && $tokens[$i]->id !== \T_END_HEREDOC); + } elseif (!$t->is([...self::CHAIN, ...self::FOLDABLE, \T_NEW, \T_CLONE, \T_ISSET, \T_EMPTY, \T_ARRAY]) + && !($prefix && ($t->is(self::CAST) || \in_array($t->text, ['!', '~', '@', '-', '+'], true))) + ) { + break; + } + $prefix = $t->is(self::CAST) || \in_array($t->text, ['!', '~', '@', '-', '+'], true); + # A string left open runs to the end of the source. + $i = \min($i, \count($tokens) - 1); + $line = $tokens[$i]->line + \substr_count($tokens[$i]->text, "\n"); + $i = self::nextIndex($tokens, $i); + } + + return $line; + } + + /** + * Index of the bracket opening the one closed at `$close`, or 0. + */ + private static function opener(int $close): int + { + return self::$pairs[$close] ?? 0; + } + + /** + * Whether the target written by the assignment operator at `$i` starts on `$line`: a variable with the + * fetches and indexes that follow it. + * + * @param list<\PhpToken> $tokens + */ + private static function targetStartsOn(array $tokens, int $i, int $line): bool + { + for ($k = self::previousIndex($tokens, $i); isset($tokens[$k]); $k = self::previousIndex($tokens, $k)) { + $t = $tokens[$k]; + if ($t->text === '}') { + # Only a name built by an expression, `$o->{$name}`, is part of the target; a block ends before it. + $open = self::opener($k); + $before = $tokens[self::previousIndex($tokens, $open)] ?? null; + if (!$before?->is([\T_OBJECT_OPERATOR, \T_NULLSAFE_OBJECT_OPERATOR, \T_DOUBLE_COLON]) && $before?->text !== '$') { + break; + } + $k = $open; + } elseif ($t->text === ')' || $t->text === ']') { + $k = self::opener($k); + } elseif (!$t->is(self::CHAIN) && $t->text !== '$') { + break; + } + if ($tokens[$k]->line !== $line) { + return false; + } + } + + return true; + } + + /** + * Whether the chain of fetches ending at `$i` (`$a->b::$c`) is a simple one that starts on `$line`. + * + * @param list<\PhpToken> $tokens + */ + private static function chainStartsOn(array $tokens, int $i, int $line): bool + { + while ($i >= 0 && $tokens[$i]->is(self::CHAIN)) { + if ($tokens[$i]->line !== $line) { + return false; + } + $i = self::previousIndex($tokens, $i); + } + + # An object built by a call or an index may start on an earlier line. + return $i < 0 || !\in_array($tokens[$i]->text, [')', ']', '}'], true); + } + + /** + * Whether the name is a function PHP compiles into a dedicated opcode. + */ + private static function compiledFunction(string $name): bool + { + $name = \strtolower(\ltrim($name, '\\')); + + return \in_array($name, self::COMPILED_FUNCTIONS, true); + } + + /** + * Whether PHP may decide the condition of the `if` or `elseif` at `$i` while compiling: it is built of + * literals and constants alone, or a logical operator in it follows such an operand. + * + * @param list<\PhpToken> $tokens + */ + private static function foldableCondition(array $tokens, int $i): bool + { + $open = self::nextIndex($tokens, $i); + $close = self::closer($tokens, $open); + $constant = true; + for ($k = self::nextIndex($tokens, $open); $k < $close; $k = self::nextIndex($tokens, $k)) { + $t = $tokens[$k]; + if ($t->is([\T_BOOLEAN_AND, \T_BOOLEAN_OR, \T_LOGICAL_AND, \T_LOGICAL_OR]) && self::constantBefore($tokens, $k)) { + return true; + } + $t->is([...self::FOLDABLE, \T_DOUBLE_COLON, \T_IS_EQUAL, \T_IS_NOT_EQUAL, \T_IS_IDENTICAL, + \T_IS_NOT_IDENTICAL, \T_IS_SMALLER_OR_EQUAL, \T_IS_GREATER_OR_EQUAL, \T_BOOLEAN_AND, \T_BOOLEAN_OR, + '<', '>', '!', '(', ')']) or $constant = false; + # A name followed by `(` is a call. + $t->is([\T_STRING, \T_NAME_QUALIFIED, \T_NAME_FULLY_QUALIFIED]) && self::next($tokens, $k)?->text === '(' + and $constant = false; + } + + return $constant; + } + + /** + * Index of the last token of the `if` chain whose `if` or `elseif` is at `$i`: its branches, the + * `else` included. A chain in the alternative syntax ends with its condition. + * + * @param list<\PhpToken> $tokens + */ + private static function chainEnd(array $tokens, int $i): int + { + $close = self::closer($tokens, self::nextIndex($tokens, $i)); + $body = self::nextIndex($tokens, $close); + if (($tokens[$body] ?? null)?->text === ':') { + return $close; + } + $end = self::branchEnd($tokens, $body); + $after = self::nextIndex($tokens, $end); + if (($tokens[$after] ?? null)?->id === \T_ELSEIF) { + return self::chainEnd($tokens, $after); + } + if (($tokens[$after] ?? null)?->id !== \T_ELSE) { + return $end; + } + $branch = self::nextIndex($tokens, $after); + + return $tokens[$branch]->id === \T_IF ? self::chainEnd($tokens, $branch) : self::branchEnd($tokens, $branch); + } + + /** + * Index of the last token of the branch starting at `$i`: a block or a single statement. + * + * @param list<\PhpToken> $tokens + */ + private static function branchEnd(array $tokens, int $i): int + { + return ($tokens[$i] ?? null)?->text === '{' + ? self::closer($tokens, $i) + : self::nextIndex($tokens, self::endIndex($tokens, $i)); + } + + /** + * Whether the `while` or `for` at `$i` has a condition that is always true: `true`, `1` or none. + * + * @param list<\PhpToken> $tokens + */ + private static function endless(array $tokens, int $i): bool + { + $open = self::nextIndex($tokens, $i); + $close = self::closer($tokens, $open); + $parts = [[]]; + $depth = 0; + for ($k = $open + 1; $k < $close; $k++) { + $t = $tokens[$k]; + if ($t->isIgnorable()) { + continue; + } + \in_array($t->text, self::OPENER, true) and $depth++; + \in_array($t->text, [')', ']', '}'], true) and $depth--; + if ($depth === 0 && $t->text === ';') { + $parts[] = []; + continue; + } + $parts[\array_key_last($parts)][] = \strtolower($t->text); + } + $condition = $tokens[$i]->id === \T_FOR ? ($parts[1] ?? null) : $parts[0]; + + return $condition === [] || $condition === ['true'] || $condition === ['1']; + } + + /** + * Whether the token at `$i` names a call of `assert()`. + * + * @param list<\PhpToken> $tokens + */ + private static function callsAssert(array $tokens, int $i): bool + { + $t = $tokens[$i]; + + return $t->is([\T_STRING, \T_NAME_FULLY_QUALIFIED]) + && \strcasecmp(\ltrim($t->text, '\\'), 'assert') === 0 + && self::next($tokens, $i)?->text === '(' + && !($tokens[self::previousIndex($tokens, $i)] ?? null)?->is([...self::NAME_PREFIX, \T_NEW]); + } + + /** + * Whether PHP knows the class before `::` while compiling, so its constant folds into the value. * * Only the class being declared and built-in classes qualify: whether any other class is loaded at * that moment depends on the run. A built-in enum does not qualify, since its cases are objects. @@ -639,20 +1504,10 @@ private static function knownWhileCompiling(?\PhpToken $class, ?string $declared return $reflection->isInternal() && !$reflection->isEnum(); } - /** - * Whether a fully qualified function name is a built-in function, bound while compiling. - */ - private static function builtInFunction(string $name): bool - { - $name = \ltrim($name, '\\'); - - return \function_exists($name) && (new \ReflectionFunction($name))->isInternal(); - } - /** * Marks the innermost open array as built at runtime. * - * @param list, call: bool, index: int, shape: list, held: array, resolved: bool}> $brackets + * @param list, call: bool, shape: list, dynamic: bool, from: int|null, to: int|null}> $brackets */ private static function markRuntime(array &$brackets): void { diff --git a/plugin/codecov/tests/Fixture/ExecutableLines/hooks.php.inc b/plugin/codecov/tests/Fixture/ExecutableLines/hooks.php.inc index 347659d6..08031776 100644 --- a/plugin/codecov/tests/Fixture/ExecutableLines/hooks.php.inc +++ b/plugin/codecov/tests/Fixture/ExecutableLines/hooks.php.inc @@ -20,6 +20,10 @@ final class HookedProperties + $this->b; } + public \Closure $maker { + get => fn(): int => 1; + } + public int $withDefault = 3 { set(int $v) { $this->withDefault = $v * 2; diff --git a/plugin/codecov/tests/Fixture/ExecutableLines/operands.php.inc b/plugin/codecov/tests/Fixture/ExecutableLines/operands.php.inc new file mode 100644 index 00000000..a98437a5 --- /dev/null +++ b/plugin/codecov/tests/Fixture/ExecutableLines/operands.php.inc @@ -0,0 +1,272 @@ + 0 + && $b > 0 + ) { + return 1; + } + return 0; + } + + public function format(string $a, string $b): string + { + return \sprintf( + '%s %s', + $a, + $b, + ); + } + + public function arguments(object $o, string $x): void + { + $o->run( + 'literal', + self::A, + $x, + name: true, + ); + $this->own( + 'literal', + $x, + ); + \in_array( + $x, + [self::A, self::B], + true, + ); + } + + private function own(string $a, string $b): void {} + + public function ternary(bool $flag): string + { + $value = $flag + ? 'yes' + : 'no'; + return $value; + } + + public function cases(string $rule): int + { + switch ($rule) { + case self::A: + return 1; + case self::B: + return 2; + } + return 0; + } + + public function exhaustive(int $x): int + { + switch ($x) { + case 1: + return 1; + default: + return 0; + } + } + + public function unreachable(?int $x): int + { + $y = $x ?? throw new \LogicException('none'); + return $y; + } + + public function afterReturn(): \Generator + { + return; + yield; + } + + public function constantCondition(object $o): int + { + if (\PHP_INT_SIZE < 4 + || $o->has('x')) { + return 1; + } + return 0; + } + + public function endless(object $o): void + { + while (true) { + $o->tick(); + } + } + + public function elseIf(bool $a, bool $b): int + { + if ($a) { + return 1; + } else if ($b) { + return 2; + } + return 3; + } + + public function strings(string $t, string $a, string $b): string + { + $sql = "SELECT * + FROM {$t} + WHERE id = ?"; + $list = "$a,$b" + . $t; + return $sql . $list; + } + + public function longTarget(string $value): void + { + $this->name + = $value; + } + + public function arrowDefault(): \Closure + { + return fn( + int $x = 0, + ) => $x; + } + + public function versioned(bool $x): int + { + if (\PHP_VERSION_ID < 80400 && $x) { + return \strlen('old'); + } + return 0; + } + + public function imported(): void + { + helper( + 'literal', + ); + } + + public function revived(int $x): int + { + goto done; + $x++; + done: + return $x; + } + + public function breakInBlock(array $items): int + { + foreach ($items as $item) { + if ($item) { + break; + } + } + return 0; + } + + public function constantOperand(object $o): bool + { + $ok = \PHP_INT_SIZE < 4 + || $o->has('x'); + return $ok; + } + + public function closures(): array + { + $arrow = fn() => $this->own( + 'literal', + 'other', + ); + $closure = function () { + $this->own( + 'literal', + 'other', + ); + }; + return [$arrow, $closure]; + } + + public function constantLoop(): int + { + $n = 0; + while (self::A === 'b') { + $n++; + } + return $n; + } + + public function operands(object $o, string $a, string $b): string + { + $x = $o->wrap( + $a, + ) . 'x'; + $y = !($a) . ($b); + $z = $a . "v{$b}"; + $o->{$a} = 1; + $w = $o + ->prop; + return $x . $y . $z . $w; + } + + public function lateConstants(): array + { + return [ + static::A, + $this::B, + ]; + } + + public function versionChains(object $o): int + { + if (\PHP_INT_SIZE > 100) $o->a(); + if (\PHP_INT_SIZE > 100) { + $o->b(); + } elseif ($o->c()) { + $o->d(); + } + if (\PHP_INT_SIZE > 100) { + $o->e(); + } else if ($o->f()) { + $o->g(); + } + if (\PHP_INT_SIZE > 100) { + $o->h(); + } else { + $o->i(); + } + if (\PHP_INT_SIZE > 100) { + $o->j(); + } else $o->k(); + if (\PHP_INT_SIZE > 100): + $o->l(); + endif; + return 0; + } +} diff --git a/plugin/codecov/tests/Unit/Driver/UncountedLinesTest.php b/plugin/codecov/tests/Unit/Driver/UncountedLinesTest.php index ad2a16d3..a5120e95 100644 --- a/plugin/codecov/tests/Unit/Driver/UncountedLinesTest.php +++ b/plugin/codecov/tests/Unit/Driver/UncountedLinesTest.php @@ -197,6 +197,8 @@ public function removeDropsBranchesOnIgnoredLinesWithTheirPaths(): void #[DataSet([" 1, 6 => 1], [5 => 1]], 'function ending in throw, Xdebug')] #[DataSet([" 1, 6 => 1, 8 => -1, 10 => 1], [5 => 1, 6 => 1, 8 => -1]], 'function whose every branch returns, Xdebug')] #[DataSet([" 1, 6 => 1, 8 => -1, 9 => -1], [5 => 1, 6 => 1, 8 => -1, 9 => -1]], 'function falling through past an if, PCOV')] + #[DataSet([" 1, 6 => 1, 7 => -1, 8 => -1, 10 => 1], [5 => 1, 6 => 1, 7 => -1, 8 => -1, 10 => 1]], 'function falling through past an else if, PCOV')] + #[DataSet([" 1, 6 => 1, 7 => 1], [5 => 1, 6 => 1, 7 => 1]], 'function falling through past ?? throw, PCOV')] #[DataSet([" -1, 4 => 1, 5 => 1], [3 => -1, 4 => 1, 5 => 1]], 'closure falling through, PCOV')] #[DataSet([" 1, 4 => 1, 5 => 1, 6 => 1], [3 => 1, 4 => 1, 5 => 1]], 'top-level if, Xdebug')] #[DataSet(["", [5 => -1, 8 => -1, 9 => -1], [5 => -1, 8 => -1]], 'closing tag, PCOV')] diff --git a/plugin/codecov/tests/Unit/Internal/ExecutableLinesTest.php b/plugin/codecov/tests/Unit/Internal/ExecutableLinesTest.php index 1d0a891e..cf1fa604 100644 --- a/plugin/codecov/tests/Unit/Internal/ExecutableLinesTest.php +++ b/plugin/codecov/tests/Unit/Internal/ExecutableLinesTest.php @@ -80,7 +80,11 @@ abstract public function run(): void; Assert::same(self::lines($source), []); } - public function promotingConstructorSignatureIsExecutable(): void + /** + * The promoting opcodes sit on the signature before PHP 8.5 and on the parameters since, where turbocov + * leaves them out, so only the closing brace counts. + */ + public function promotingConstructorCountsItsClosingBraceOnly(): void { $source = <<<'PHP' 0, + ); + return $x; + } + PHP; + + Assert::same(self::lines($source), [7]); } public function interpolationDoesNotEndTheStatement(): void @@ -130,13 +154,14 @@ public function heredocContentIsNotExecutable(): void $expected */ #[DataSet(['altsyntax.php.inc', [4, 5, 6, 8, 9, 11, 13]], 'alternative syntax')] - #[DataSet(['args.php.inc', [4, 5, 9, 12, 13, 14, 17, 20, 21, 22, 25, 29, 30, 36, 37, 39, 42]], 'call arguments')] - #[DataSet(['classes.php.inc', [13, 17, 18, 22, 27, 32, 35, 45, 55]], 'classes, traits, enums, interfaces')] - #[DataSet(['class-constants.php.inc', [9, 16, 17, 18, 20, 24, 28, 29, 30, 32, 37, 42, 43, 46, 47, 48, 50, 51, 52, 54, 55, 56, 58, 59, 60, 62, 63, 66]], 'class constants in arrays and static calls')] + #[DataSet(['args.php.inc', [4, 9, 12, 14, 17, 20, 22, 25, 29, 36, 37, 39, 42]], 'call arguments')] + #[DataSet(['class-constants.php.inc', [9, 16, 20, 24, 28, 32, 37, 42, 46, 50, 54, 58, 62, 66]], 'class constants in arrays and static calls')] + #[DataSet(['classes.php.inc', [17, 18, 22, 27, 32, 35, 45, 55]], 'classes, traits, enums, interfaces')] #[DataSet(['constant-closures.php.inc', [8, 29, 30, 34, 41]], 'closures in constant expressions')] - #[DataSet(['edge.php.inc', [4, 5, 6, 8, 11, 16, 17, 19, 21, 24, 25, 26, 27, 30, 31, 34, 37, 38, 41, 42, 45]], 'argument and switch edges')] + #[DataSet(['edge.php.inc', [4, 5, 8, 11, 16, 17, 19, 24, 25, 26, 30, 31, 34, 37, 38, 41, 42, 45]], 'argument and switch edges')] #[DataSet(['eval.php.inc', [4, 5]], 'eval')] - #[DataSet(['generator.php.inc', [2, 4, 5, 6, 7]], 'generator')] - #[DataSet(['generators.php.inc', [4, 6, 7, 9, 11, 13, 14, 16, 18, 24, 25, 26, 27, 30, 32, 33, 35, 36, 38, 40, 41, 42, 44, 47, 48, 50, 54]], 'generator methods, closures and arrow functions')] - #[DataSet(['goto.php.inc', [4, 6, 7, 8, 10, 15, 16, 17, 22, 23, 24, 27, 29, 34, 36, 38, 40]], 'goto and labels')] + #[DataSet(['generator.php.inc', [4, 6, 7]], 'generator')] + #[DataSet(['generators.php.inc', [6, 7, 9, 13, 14, 18, 24, 25, 26, 27, 32, 33, 35, 36, 40, 41, 42, 47, 48, 50, 54]], 'generator methods, closures and arrow functions')] + #[DataSet(['goto.php.inc', [4, 6, 7, 8, 10, 15, 16, 17, 22, 23, 24, 27, 34, 36, 38]], 'goto and labels')] #[DataSet(['halt.php.inc', [4, 6]], '__halt_compiler')] - #[DataSet(['heredoc.php.inc', [4, 5, 6, 8, 11]], 'heredoc and nowdoc')] - #[DataSet(['heredoc-calls.php.inc', [4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 16, 18, 20, 21, 26, 27]], 'calls interpolated into heredoc')] - #[DataSet(['hooks.php.inc', [5, 6, 11, 14, 15, 19, 20, 25, 26, 31, 37, 46, 48, 53, 55]], 'property hooks and asymmetric promotion')] + #[DataSet(['heredoc-calls.php.inc', [4, 6, 7, 8, 10, 11, 15, 18, 20, 21, 26, 27]], 'calls interpolated into heredoc')] + #[DataSet(['heredoc.php.inc', [4, 5, 8, 11]], 'heredoc and nowdoc')] + #[DataSet(['hooks.php.inc', [41, 52, 59]], 'property hooks and asymmetric promotion')] #[DataSet(['include.php.inc', [4, 5, 6]], 'include and require')] #[DataSet(['jumptable.php.inc', [4, 5, 6, 12, 13, 18, 19, 20, 21, 22, 27, 28, 29, 30, 31, 32, 37, 38, 39, 45, 46, 52, 53, 54, 55, 57, 62, 63, 64, 65, 66, 67, 68, 69, 71, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 87, 91, 92, 93]], 'jump tables')] #[DataSet(['keywords.php.inc', [4, 5, 6, 8, 9, 10, 12, 13, 14, 16, 23, 28, 33, 38]], 'keywords as names')] #[DataSet(['loops.php.inc', [4, 5, 6, 8, 9, 11, 12, 15, 16, 17]], 'loops')] - #[DataSet(['match.php.inc', [4, 5, 6, 7, 9, 10, 11, 13]], 'match and array()')] - #[DataSet(['misc.php.inc', [4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 22]], 'static, global, list, closures, goto')] + #[DataSet(['match.php.inc', [4, 5, 6, 7, 9, 11, 13]], 'match and array()')] + #[DataSet(['misc.php.inc', [4, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20]], 'static, global, list, closures, goto')] #[DataSet(['multiline.php.inc', [4, 5, 6, 8, 9, 10, 12, 13]], 'multi-line expressions')] - #[DataSet(['namespaces.php.inc', [7, 11, 12, 17, 21, 29, 30, 41, 42, 43, 45, 50, 62, 71, 72, 74]], 'several namespaces, functions and classes')] + #[DataSet(['namespaces.php.inc', [11, 12, 17, 21, 29, 30, 41, 42, 43, 45, 50, 62, 71, 72, 74]], 'several namespaces, functions and classes')] + #[DataSet(['operands.php.inc', [13, 24, 26, 27, 33, 34, 36, 38, 52, 53, 54, 56, 58, 59, 67, 69, 73, 74, 75, 76, 83, 85, 87, 93, 94, 96, 102, 108, 118, 123, 124, 130, 131, 132, 133, 135, 140, 143, 145, 150, 152, 156, 166, 171, 174, 178, 181, 186, 187, 188, 191, 196, 198, 203, 204, 205, 207, 208, 209, 210, 212, 213, 218, 220, 222, 227, 230, 231, 232, 233, 235, 241, 268, 270]], 'operands, multi-line expressions and unreachable code')] #[DataSet(['reach.php.inc', [4, 5, 7, 12, 13, 15, 16, 19, 20, 21, 22, 24, 30, 32, 38, 39, 40, 46, 47, 48, 50, 53, 54, 56]], 'reachable closing braces')] - #[DataSet(['returns.php.inc', [5, 11, 17, 18, 23, 24, 25, 29, 30, 35, 36, 38, 42, 43, 44, 46, 50, 51]], 'multi-line returns')] + #[DataSet(['returns.php.inc', [5, 11, 17, 18, 24, 25, 29, 35, 36, 38, 42, 43, 44, 46, 50]], 'multi-line returns')] #[DataSet(['switch.php.inc', [5, 6, 7, 8, 9, 10, 11, 13, 15]], 'switch')] #[DataSet(['template.php.inc', [2, 3, 4, 6, 7]], 'inline HTML')] - #[DataSet(['toplevel.php.inc', [7, 8, 10, 15, 18, 22]], 'top-level code')] + #[DataSet(['toplevel.php.inc', [8, 10, 15, 18, 22]], 'top-level code')] #[DataSet(['trycatch.php.inc', [5, 6, 7, 8, 9, 10, 11, 13]], 'try, catch, finally')] public function matchesDriverLines(string $fixture, array $expected): void { @@ -271,6 +288,39 @@ public function openAndCloseTagsAcrossTheFile(): void Assert::same(self::lines($source), $expected); } + /** + * A loaded file keeps the closing brace a driver may report: one the estimate leaves out because + * Xdebug takes the code after `?? throw` for unreachable, and one that sends a closure to a call. + */ + public function bodyEndsKeepBracesSomeDriverReports(): void + { + $source = <<<'PHP' + get('/', function () { + return 'x'; + }); + PHP; + + Assert::same(self::lines($source), [4, 9, 11, 12]); + Assert::same(\array_keys(ExecutableLines::bodyEnds($source)), [6, 13]); + } + + public function unbalancedBracketsStillGiveAnEstimate(): void + { + $source = " */ diff --git a/skills/testo-coverage/SKILL.md b/skills/testo-coverage/SKILL.md index 0dcae1cc..57690489 100644 --- a/skills/testo-coverage/SKILL.md +++ b/skills/testo-coverage/SKILL.md @@ -40,7 +40,7 @@ return new ApplicationConfig( ); ``` -`src` is the coverage scope: every `.php` file under it that holds code appears in the reports. A file no test loaded is listed with its executable lines uncovered, estimated from its tokens without loading it, so an untested class lowers the total instead of being left out. +`src` is the coverage scope: every `.php` file under it that holds code appears in the reports. A file no test loaded is listed with its executable lines uncovered, estimated from its tokens without loading it, so an untested class lowers the total instead of being left out. The estimate counts only lines every coverage driver reports, so a file's line count can grow once a test loads it, and reports of several suites merged line by line never keep a line uncovered that the suite loading the file does not report. Then enable on the CLI: