Skip to content
15 changes: 15 additions & 0 deletions src/Domain/MemberKind.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,21 @@ public function checksAccessByFirstDeclaration(): bool
return $this === self::Method || $this === self::Property;
}

/**
* Whether PHP binds $member, brought in by a trait, before the using class
* inherits from its parent. A trait's abstract methods are bound after, so
* they only fill a name nothing else provides (`zend_do_link_class` and
* `zend_add_trait_method` in php-src).
*/
public function bindsBeforeInheritance(MemberInfoInterface $member): bool
{
if ($this !== self::Method) {
return true;
}
assert($member instanceof MethodInfo, 'a method is described by a MethodInfo');
return !$member->isAbstract;
}

/**
* Where a class-like holds the members of this kind, keyed by declared name.
*
Expand Down
120 changes: 93 additions & 27 deletions src/Repository/MemberResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -231,28 +231,76 @@ private function bind(MemberInfoInterface $member, ClassInfo $declaring, Classli
* first, each paired with the class that declares it — the class using a
* trait for a member the trait brings in. Only $wanted's when given.
*
* @param list<string> $composing Traits whose own members are being
* resolved, which bring in nothing more; PHP rejects a trait cycle
* @return list<non-empty-list<array{MemberInfoInterface, ClassInfo}>>
*/
private function declarations(ClassInfo $origin, MemberKind $kind, ?string $wanted): array
private function declarations(ClassInfo $origin, MemberKind $kind, ?string $wanted, array $composing = []): array
{
$byKey = [];
$seen = [];
foreach ($this->descend($origin, $origin, [], $seen) as [$classInfo, $declaringClass, $exclusions]) {
foreach ($kind->membersOf($classInfo) as $name => $member) {
$traitMembers = [];
// Entries are numbered as they are added; a class's level starts at its own number.
$added = 0;
$levelStart = [];
$lastAdded = [];
foreach ($this->descend($origin, $origin, [], $seen) as [$classInfo, $declaringClass, $exclusions, $binding]) {
$level = NameKind::ClassLike->normalize($declaringClass->name->qualifiedName);
if ($binding === null) {
$levelStart[$level] = $added;
$members = $kind->membersOf($classInfo);
} else {
$trait = NameKind::ClassLike->normalize($classInfo->name->qualifiedName);
$traitMembers[$trait] ??= $this->traitMembers($classInfo, $kind, $wanted, $composing);
$members = array_filter(
$traitMembers[$trait],
static fn (MemberInfoInterface $member): bool => $kind->bindsBeforeInheritance($member)
=== ($binding === TraitBinding::BeforeInheritance),
);
}
foreach ($members as $name => $member) {
$key = $kind->keyFor($name);
if ($wanted !== null && $key !== $wanted) {
continue;
}
if ($kind->isMethod() && in_array($name, $exclusions, true)) {
continue;
}
// A trait member bound after inheritance that meets one this class
// already has only has its signature checked (`zend_add_trait_method`).
if ($binding === TraitBinding::AfterInheritance && ($lastAdded[$key] ?? -1) >= $levelStart[$level]) {
continue;
}
$byKey[$key][] = [$member, $declaringClass];
$lastAdded[$key] = $added++;
}
}

return array_values($byKey);
}

/**
* What each name resolves to within a trait itself, where its own members
* win over those of the traits it uses.
*
* @param list<string> $composing
* @return array<string, MemberInfoInterface>
*/
private function traitMembers(ClassInfo $trait, MemberKind $kind, ?string $wanted, array $composing): array
{
$key = NameKind::ClassLike->normalize($trait->name->qualifiedName);
if (in_array($key, $composing, true)) {
return [];
}
$members = [];
foreach ($this->declarations($trait, $kind, $wanted, [...$composing, $key]) as $declarations) {
$member = $declarations[0][0];
$members[$member->getName()->name] = $member;
}

return $members;
}

/**
* The member one name resolves to, if code in $from may use it (PHP
* manual, Visibility; `zend_std_get_method` and `zend_verify_const_access`
Expand Down Expand Up @@ -321,10 +369,14 @@ private function isRelated(ClasslikeName $a, ClasslikeName $b): bool
}

/**
* A used trait is yielded at each binding without descending into it;
* {@see self::traitMembers()} resolves what it brings in.
*
* @param list<string> $exclusions
* @param array<string, true> $seen
* @return iterable<array{ClassInfo, ClassInfo, list<string>}> Each class-like
* with the class its members are declared in, and its excluded methods
* @return iterable<array{ClassInfo, ClassInfo, list<string>, ?TraitBinding}> Each
* class-like with the class its members are declared in, its excluded
* methods, and, for a used trait, when its members are bound
*/
private function descend(
ClassInfo $classInfo,
Expand All @@ -338,10 +390,14 @@ private function descend(
}
$seen[$key] = true;

yield [$classInfo, $declaring, $exclusions];
yield [$classInfo, $declaring, $exclusions, null];

foreach ($this->supertypes($classInfo) as [$superInfo, $isTrait, $superExclusions]) {
yield from $this->descend($superInfo, $isTrait ? $declaring : $superInfo, $superExclusions, $seen);
foreach ($this->supertypes($classInfo) as [$superInfo, $binding, $superExclusions]) {
if ($binding === null) {
yield from $this->descend($superInfo, $superInfo, $superExclusions, $seen);
} else {
yield [$superInfo, $declaring, $superExclusions, $binding];
}
}
}

Expand All @@ -359,37 +415,47 @@ private function passes(MemberInfoInterface $member, MemberFilter $filter): bool
}

/**
* The types to search after a class's own members, in PHP's resolution order:
* used traits, then the parent chain, then interfaces. A trait edge may carry
* the method names excluded from that trait by an `insteadof` clause on this
* class. Unresolvable types are skipped.
* The types to search after a class's own members, in PHP's binding order
* (`zend_do_link_class` in php-src): used traits, then the parent chain,
* then used traits again for what binds after inheritance, then
* interfaces. A trait edge may carry the method names excluded from that
* trait by an `insteadof` clause on this class. Unresolvable types are
* skipped.
*
* Every member lookup walks the type graph through this one method, so all
* member kinds see the same hierarchy.
*
* @return list<array{ClassInfo, bool, list<string>}> Supertype paired with
* whether it is a used trait, whose members are flattened into the
* using class, and any excluded method names.
* @return list<array{ClassInfo, ?TraitBinding, list<string>}> Supertype
* paired with, for a used trait whose members are flattened into
* the using class, when they are bound, and any excluded method
* names.
*/
private function supertypes(ClassInfo $classInfo): array
{
$names = [];
$traits = [];
foreach ($classInfo->traits as $trait) {
$key = NameKind::ClassLike->normalize($trait->qualifiedName);
$names[] = [$trait, true, $classInfo->traitExclusions[$key] ?? []];
}
if ($classInfo->parent !== null) {
$names[] = [$classInfo->parent, false, []];
}
foreach ($classInfo->interfaces as $interface) {
$names[] = [$interface, false, []];
$info = $this->source->lookupClassLike($trait);
if ($info !== null) {
$key = NameKind::ClassLike->normalize($trait->qualifiedName);
$traits[] = [$info, $classInfo->traitExclusions[$key] ?? []];
}
}
$parent = $classInfo->parent === null ? null : $this->source->lookupClassLike($classInfo->parent);

$supertypes = [];
foreach ($names as [$name, $isOriginClass, $exclusions]) {
$info = $this->source->lookupClassLike($name);
foreach ($traits as [$info, $exclusions]) {
$supertypes[] = [$info, TraitBinding::BeforeInheritance, $exclusions];
}
if ($parent !== null) {
$supertypes[] = [$parent, null, []];
}
foreach ($traits as [$info, $exclusions]) {
$supertypes[] = [$info, TraitBinding::AfterInheritance, $exclusions];
}
foreach ($classInfo->interfaces as $interface) {
$info = $this->source->lookupClassLike($interface);
if ($info !== null) {
$supertypes[] = [$info, $isOriginClass, $exclusions];
$supertypes[] = [$info, null, []];
}
}

Expand Down
15 changes: 15 additions & 0 deletions src/Repository/TraitBinding.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Firehed\PhpLsp\Repository;

/**
* When a used trait's members are bound into a class, relative to the class
* inheriting from its parent (`zend_do_link_class` in php-src).
*/
enum TraitBinding
{
case BeforeInheritance;
case AfterInheritance;
}
29 changes: 27 additions & 2 deletions tests/Domain/MemberKindTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,31 @@ public static function isMethodCases(): iterable
yield 'property' => [MemberKind::Property, false];
}

/**
* @return iterable<string, array{MemberKind, MemberInfoInterface, bool}>
*/
public static function traitBindingCases(): iterable
{
yield 'a concrete method' => [MemberKind::Method, self::createMethodInfo(), true];
yield 'an abstract method' => [MemberKind::Method, self::createMethodInfo(isAbstract: true), false];
yield 'a property' => [MemberKind::Property, self::createPropertyInfo(), true];
yield 'a constant' => [MemberKind::Constant, self::createConstantInfo(), true];
yield 'an enum case' => [MemberKind::EnumCase, self::createEnumCaseInfo(), true];
}

/**
* PHP binds a trait's abstract methods only after the using class inherits
* from its parent (php-src `zend_do_link_class`).
*/
#[DataProvider('traitBindingCases')]
public function testOnlyAnAbstractMethodIsBoundAfterInheritance(
MemberKind $kind,
MemberInfoInterface $member,
bool $expected,
): void {
self::assertSame($expected, $kind->bindsBeforeInheritance($member), "when a trait's {$kind->name} is bound");
}

/**
* @return iterable<string, array{MemberKind}>
*/
Expand Down Expand Up @@ -155,13 +180,13 @@ private static function createEnumCaseInfo(): EnumCaseInfo
);
}

private static function createMethodInfo(): MethodInfo
private static function createMethodInfo(bool $isAbstract = false): MethodInfo
{
return new MethodInfo(
name: new MethodName(ClasslikeName::fromFullyQualified(self::class), 'run'),
visibility: Visibility::Public,
isStatic: false,
isAbstract: false,
isAbstract: $isAbstract,
isFinal: false,
parameters: [],
returnType: null,
Expand Down
15 changes: 15 additions & 0 deletions tests/Fixtures/src/Hierarchy/AbstractBeforeConcreteTraitUser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Fixtures\Hierarchy;

/**
* Of two traits providing a method, the concrete one wins over the abstract
* one whichever is used first.
*/
class AbstractBeforeConcreteTraitUser
{
use AbstractSharedTrait;
use ConcreteSharedTrait;
}
16 changes: 16 additions & 0 deletions tests/Fixtures/src/Hierarchy/AbstractOverConcreteTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace Fixtures\Hierarchy;

/**
* A trait's own method wins over one from a trait it uses, even when its own
* is abstract.
*/
trait AbstractOverConcreteTrait
{
use ConcreteSharedTrait;

abstract public function shared(): string;
}
14 changes: 14 additions & 0 deletions tests/Fixtures/src/Hierarchy/AbstractOverConcreteTraitUser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace Fixtures\Hierarchy;

/**
* The trait it uses resolves its method to its own abstract one, so the
* parent's concrete method stays.
*/
class AbstractOverConcreteTraitUser extends SharedParent
{
use AbstractOverConcreteTrait;
}
13 changes: 13 additions & 0 deletions tests/Fixtures/src/Hierarchy/AbstractSharedTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Fixtures\Hierarchy;

/**
* Requires a method rather than providing one.
*/
trait AbstractSharedTrait
{
abstract public function shared(): string;
}
13 changes: 13 additions & 0 deletions tests/Fixtures/src/Hierarchy/AbstractTraitOnlyUser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Fixtures\Hierarchy;

/**
* With nothing else providing the method, the trait's abstract one is bound.
*/
abstract class AbstractTraitOnlyUser
{
use AbstractSharedTrait;
}
14 changes: 14 additions & 0 deletions tests/Fixtures/src/Hierarchy/AbstractTraitOverParentUser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace Fixtures\Hierarchy;

/**
* The trait's abstract method is bound only after inheritance, so the
* parent's concrete method stays.
*/
class AbstractTraitOverParentUser extends SharedParent
{
use AbstractSharedTrait;
}
13 changes: 13 additions & 0 deletions tests/Fixtures/src/Hierarchy/ConcreteSharedTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Fixtures\Hierarchy;

trait ConcreteSharedTrait
{
public function shared(): string
{
return 'trait';
}
}
13 changes: 13 additions & 0 deletions tests/Fixtures/src/Hierarchy/SharedParent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Fixtures\Hierarchy;

class SharedParent
{
public function shared(): string
{
return 'parent';
}
}
Loading
Loading