\Drupflare\Anachron\Php ReturnTypeRewriter

Adds the return types PHP now requires on methods that override a typed parent.

Code written before a parent gained a return type fails to load with "Declaration must be compatible". The rewriter finds class methods that a table of known signatures covers and inserts the missing return type after the parameter list. It never changes a line count, and it leaves a method alone when it cannot show the type is right.

A method is covered when the class chain reaches a class in the table, or the class implements a PHP interface from the table and every ancestor is known. A chain that leaves the file through a parent nobody indexed is not guessed at: the method is refused by name.

Summary

Methods
Properties
Constants
__construct
index
rewrite
No public properties found
No public constants found
No protected methods found
No protected properties found
No protected constants found
classes
readClass
readImport
resolve
methods
readMethod
signature
refusal
bodyConflict
returnConflict
widerThan
narrowing
narrowConflict
endsInExit
returnParts
isProvable
callName
isParentCall
closesAtEnd
isPrimary
variableConflict
literalKind
skipNested
opens
matchingBrace
matchingParen
nextNonSpace
previousNonSpace
typed
parents
INTERFACES
ARITY
ARRAY_FUNCTIONS
CASTS
NAME_TOKENS

Constant

INTERFACES

INTERFACES = ['ArrayAccess' => ['offsetexists' => 'bool', 'offsetget' => 'mixed', 'offsetset' => 'void', 'offsetunset' => 'void'], 'Iterator' => ['current' => 'mixed', 'key' => 'mixed', 'next' => 'void', 'rewind' => 'void', 'valid' => 'bool'], 'IteratorAggregate' => ['getiterator' => '\Traversable'], 'Countable' => ['count' => 'int'], 'JsonSerializable' => ['jsonserialize' => 'mixed']]

The return types PHP's own interfaces carry, for a class with no typed ancestor.

ARITY

ARITY = ['offsetexists' => 1, 'offsetget' => 1, 'offsetset' => 2, 'offsetunset' => 1, 'getiterator' => 0, 'count' => 0, 'jsonserialize' => 0, 'current' => 0, 'key' => 0, 'next' => 0, 'rewind' => 0, 'valid' => 0, 'normalize' => 3]

Parameter counts of the methods the table covers.

ARRAY_FUNCTIONS

ARRAY_FUNCTIONS = ['array_change_key_case', 'array_chunk', 'array_column', 'array_combine', 'array_count_values', 'array_diff', 'array_diff_assoc', 'array_diff_key', 'array_fill', 'array_fill_keys', 'array_filter', 'array_flip', 'array_intersect', 'array_intersect_assoc', 'array_intersect_key', 'array_keys', 'array_map', 'array_merge', 'array_merge_recursive', 'array_pad', 'array_replace', 'array_replace_recursive', 'array_reverse', 'array_slice', 'array_splice', 'array_unique', 'array_values']

Core functions whose result is always an array, which a return can rely on.

CASTS

CASTS = [T_ARRAY_CAST => 'array', T_BOOL_CAST => 'bool', T_INT_CAST => 'int', T_STRING_CAST => 'string']

Parent types a wider declared type can be narrowed to, keyed by the cast token that proves each.

NAME_TOKENS

NAME_TOKENS = [T_STRING, T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED, T_NAME_RELATIVE]

Properties

$typed

$typed : array>

The ancestor table with lowercase method names.

Type

array<string, array<string, string>> —

$parents

$parents : array

Type

array<string|int, mixed>

Methods

__construct()

__construct(array>  $typed = [], array  $parents = []) : mixed

Builds a rewriter for a table of ancestor classes.

Parameters

array> $typed

Return types that library classes declare, by fully qualified class name and method name. A subclass must return a subtype of these, so each entry names the exact type.

array $parents

Library classes that extend a table class without redeclaring its methods, mapped to their parent. A class that reaches a table class through one missing here is refused as unresolved.

Returns

mixed —

index()

index(string  $code) : array<string,array{extends: string|null, implements: list<string>}>

Lists the classes in a source string with their parent and interfaces.

Feed the result for every file of a module to rewrite() so a class that extends another class of the same module resolves through it.

Parameters

string $code

PHP source.

Returns

array}> —

Named classes keyed by fully qualified name, without a leading backslash.

rewrite()

rewrite(string  $code, array}>  $index = [], array  $refusals = []) : string

Adds the missing return types to the methods the table covers.

Parameters

string $code

PHP source.

array}> $index

Classes of the rest of the module, from index().

array $refusals

Receives one entry for each method the table names that was left alone for a reason.

Returns

string —

The source with return types added, or the same string when nothing needed one.

classes()

classes(array  $tokens) : list<array{fqn: string|null, extends: string|null, implements: list<string>, open: int, close: int}>

Finds every class body in a token list with its resolved parent and interfaces.

Parameters

array $tokens

The token list.

Returns

list, open: int, close: int}> —

One entry per class, anonymous classes included with a null name.

readClass()

readClass(array  $tokens, int  $at, string  $namespace, array  $imports) : array{fqn: string|null, extends: string|null, implements: list<string>, open: int, close: int}|null

Reads one class declaration that starts at a class keyword.

Parameters

array $tokens

The token list.

int $at

Index of the class keyword.

string $namespace

The current namespace.

array $imports

Imported names, keyed by lowercase alias.

Returns

array{fqn: string|null, extends: string|null, implements: list, open: int, close: int}|null —

The class, or null for a Name::class constant or a header that does not parse.

readImport()

readImport(array  $tokens, int  $at, array  $imports) : void

Records the names one top-level `use` statement imports.

Parameters

array $tokens

The token list.

int $at

Index of the use keyword.

array $imports

Imported names, keyed by lowercase alias; updated in place.

Returns

void —

resolve()

resolve(array{int, string, int}  $token, string  $namespace, array  $imports) : string

Resolves a class name token to a fully qualified name without a leading backslash.

Parameters

array{int, string, int} $token

A name token.

string $namespace

The current namespace.

array $imports

Imported names, keyed by lowercase alias.

Returns

string —

The resolved name.

methods()

methods(array  $tokens, array{fqn: string|null, extends: string|null, implements: list, open: int, close: int}  $class) : list<array{name: string, line: int, open: int, declared: array{int, int}|null, close: int, arity: int, public: bool, static: bool, body: array{int, int}|null, typed: bool}>

Lists the instance methods declared directly in a class body.

Parameters

array $tokens

The token list.

array{fqn: string|null, extends: string|null, implements: list, open: int, close: int} $class

The class.

Returns

list —

Each method with the index of its parameter list's closing parenthesis, its parameter count, and the indexes of its body braces. Static methods are left out.

readMethod()

readMethod(array  $tokens, int  $at) : array{name: string, line: int, open: int, declared: array{int, int}|null, close: int, arity: int, public: bool, static: bool, body: array{int, int}|null, typed: bool}|null

Reads one method that starts at a function keyword.

Parameters

array $tokens

The token list.

int $at

Index of the function keyword.

Returns

array{name: string, line: int, open: int, declared: array{int, int}|null, close: int, arity: int, public: bool, static: bool, body: array{int, int}|null, typed: bool}|null —

The method, or null when the header does not parse.

signature()

signature(array{fqn: string|null, extends: string|null, implements: list, open: int, close: int}  $class, string  $name, array}>  $known, string|null  $why, bool  $crossed = false) : string|null

Finds the return type the class chain requires for a method name.

Parameters

array{fqn: string|null, extends: string|null, implements: list, open: int, close: int} $class

The class.

string $name

Lowercase method name.

array}> $known

Every class the rewriter has seen.

string|null $why

Set to a refusal reason when the chain cannot be read, left null otherwise.

bool $crossed

Set to true when a class of the module sits between the class and the class that declares the type.

Returns

string|null —

The type to add, or null when none applies or the chain is unresolved.

refusal()

refusal(array  $tokens, array{name: string, line: int, open: int, declared: array{int, int}|null, close: int, arity: int, public: bool, static: bool, body: array{int, int}|null, typed: bool}  $method, string  $name, string|null  $type) : string|null

Checks whether a method can take the type, and names the reason when it cannot.

Parameters

array $tokens

The token list.

array{name: string, line: int, open: int, declared: array{int, int}|null, close: int, arity: int, public: bool, static: bool, body: array{int, int}|null, typed: bool} $method

The method.

string $name

Lowercase method name.

string|null $type

The type the chain requires.

Returns

string|null —

A refusal reason, or null when the type can be added.

bodyConflict()

bodyConflict(array  $tokens, array{int, int}  $body, string  $type) : string|null

Looks for a return in a method body that the type would reject.

The check is conservative. It reads return statements outside nested functions and classes, and judges only a bare return, a literal, or a body that cannot return at all.

Parameters

array $tokens

The token list.

array{int, int} $body

Indexes of the body braces.

string $type

The type to add, without a leading backslash.

Returns

string|null —

A reason, or null when nothing in the body contradicts the type.

returnConflict()

returnConflict(array  $tokens, int  $at, string  $type) : string|null

Judges one return statement against a type.

Parameters

array $tokens

The token list.

int $at

Index of the return keyword.

string $type

The type, without a leading backslash.

Returns

string|null —

A reason, or null when the statement is compatible or cannot be judged.

widerThan()

widerThan(array  $tokens, array{name: string, line: int, open: int, declared: array{int, int}|null, close: int, arity: int, public: bool, static: bool, body: array{int, int}|null, typed: bool}  $method, string  $type, string  $name) : string|null

Reads a method's declared return type and says whether it is wider than the parent's.

Only parent types that the body check can prove are judged: array, bool, int and string. A declared type is wider when it is mixed, or a union (or a nullable type) that contains the parent's type. A type that is the same, narrower or unrelated is left alone.

Parameters

array $tokens

The token list.

array{name: string, line: int, open: int, declared: array{int, int}|null, close: int, arity: int, public: bool, static: bool, body: array{int, int}|null, typed: bool} $method

The method.

string $type

The parent's type from the table.

string $name

Lowercase method name.

Returns

string|null —

The declared type as written, or null when it is not a supertype to narrow.

narrowing()

narrowing(array  $tokens, array{int, int}  $declared, string  $parent) : array<int,string>

Builds the token replacements that turn a declared type into the parent's.

Parameters

array $tokens

The token list.

array{int, int} $declared

Token range of the declared type, end exclusive.

string $parent

The parent's type.

Returns

array —

Replacement text by token index: the first type token becomes the parent's type and the rest become empty. Whitespace and comments stay where they are.

narrowConflict()

narrowConflict(array  $tokens, array{name: string, line: int, open: int, declared: array{int, int}|null, close: int, arity: int, public: bool, static: bool, body: array{int, int}|null, typed: bool}  $method, string  $name, string  $type, bool  $parentCall) : string|null

Checks that narrowing a method's declared type cannot change what it returns.

Every return must be provably of the parent's type, the body must end in a return or a throw, and the body must not be a generator.

Parameters

array $tokens

The token list.

array{name: string, line: int, open: int, declared: array{int, int}|null, close: int, arity: int, public: bool, static: bool, body: array{int, int}|null, typed: bool} $method

The method.

string $name

Lowercase method name.

string $type

The parent's type, without a leading backslash.

bool $parentCall

Whether parent::<method>() is known to return the parent's type: true when no class of the module sits between this class and the table class.

Returns

string|null —

A reason, or null when the narrowing is safe.

endsInExit()

endsInExit(array  $tokens, array{int, int}  $body) : bool

Checks that a method body ends in a statement that returns or throws.

Parameters

array $tokens

The token list.

array{int, int} $body

Indexes of the body braces.

Returns

bool —

True when the last top-level statement starts with return or throw.

returnParts()

returnParts(array  $tokens, int  $at) : list<string|array{int, string, int}>

Lists the tokens of a return statement's value, without whitespace and comments.

Parameters

array $tokens

The token list.

int $at

Index of the return keyword.

Returns

list —

The tokens up to the statement's semicolon.

isProvable()

isProvable(list  $parts, string  $type, string  $name, bool  $parentCall) : bool

Checks whether an expression is provably of a type from its tokens alone.

Provable: an array literal, a literal of a scalar type, a cast to the type of a value with no operator in it, a call to a core function that always returns an array, and a call to the method's own parent version when that returns the type.

Parameters

list $parts

The expression's tokens.

string $type

The type, without a leading backslash.

string $name

Lowercase name of the method being checked.

bool $parentCall

Whether the parent's version of the method returns the type.

Returns

bool —

True when the expression is of the type.

callName()

callName(list  $parts) : string|null

Names the function of an expression that is exactly one call, or null when it is not one.

Parameters

list $parts

The expression's tokens.

Returns

string|null —

The name as written, or null.

isParentCall()

isParentCall(list  $parts, string  $name) : bool

Checks whether an expression is a call to `parent::<method>(...)` and nothing more.

Parameters

list $parts

The expression's tokens.

string $name

Lowercase method name.

Returns

bool —

True for the call.

closesAtEnd()

closesAtEnd(list  $parts, int  $from) : bool

Checks that the bracket at an index closes at the last token.

Parameters

list $parts

The expression's tokens.

int $from

Index of the opening bracket.

Returns

bool —

True when it closes at the end and nothing follows it.

isPrimary()

isPrimary(list  $parts) : bool

Checks that an expression holds no operator outside brackets, so a cast binds all of it.

Parameters

list $parts

The expression's tokens.

Returns

bool —

True for names, variables, literals, member access and bracketed groups.

variableConflict()

variableConflict(array  $tokens, array{name: string, line: int, open: int, declared: array{int, int}|null, close: int, arity: int, public: bool, static: bool, body: array{int, int}|null, typed: bool}  $method, string  $variable, string  $type, string  $name, bool  $parentCall) : string|null

Judges a returned variable: every use of it in the method must keep it of the type.

Allowed uses are an assignment of a provable value at the start of a statement, an element access on an array, the returned value itself, and isset, empty, count and is_array. Anything else, including a parameter of the same name, might change the variable.

Parameters

array $tokens

The token list.

array{name: string, line: int, open: int, declared: array{int, int}|null, close: int, arity: int, public: bool, static: bool, body: array{int, int}|null, typed: bool} $method

The method.

string $variable

The variable, with its dollar sign.

string $type

The parent's type.

string $name

Lowercase method name.

bool $parentCall

Whether the parent's version of the method returns the type.

Returns

string|null —

A reason, or null when the variable is provably of the type.

literalKind()

literalKind(list  $parts) : string|null

Names the type of a single literal expression.

Parameters

list $parts

The expression's tokens without whitespace.

Returns

string|null —

The literal's type, or null when the expression is not one literal.

skipNested()

skipNested(array  $tokens, int  $at, int  $limit) : int

Skips a nested function, closure or class and returns the index of its closing brace.

Parameters

array $tokens

The token list.

int $at

Index of the function or class keyword.

int $limit

Index the search stops before.

Returns

int —

Index to continue from.

opens()

opens(string|array{int, string, int}  $token) : bool

Checks whether a token opens a brace level, including string interpolation.

Parameters

string|array{int, string, int} $token

The token.

Returns

bool —

True for a plain brace, a string brace, or a dollar brace.

matchingBrace()

matchingBrace(array  $tokens, int  $open) : int|null

Finds the brace that closes the one at an index.

Parameters

array $tokens

The token list.

int $open

Index of the opening brace.

Returns

int|null —

Index of the matching closing brace, or null when the braces never balance.

matchingParen()

matchingParen(array  $tokens, int  $open) : int|null

Finds the parenthesis that closes the one at an index.

Parameters

array $tokens

The token list.

int $open

Index of the opening parenthesis.

Returns

int|null —

Index of the matching closing parenthesis, or null when they never balance.

nextNonSpace()

nextNonSpace(array  $tokens, int  $index) : int|null

Finds the nearest token after an index that is not whitespace or a comment.

Parameters

array $tokens

The token list.

int $index

Index to search after.

Returns

int|null —

The index found, or null at the end of the list.

previousNonSpace()

previousNonSpace(array  $tokens, int  $index) : int

Finds the nearest token before an index that is not whitespace or a comment.

Parameters

array $tokens

The token list.

int $index

Index to search before.

Returns

int —

The index found, or -1 when only whitespace precedes it.