diff --git a/src/Completion/MemberCandidates.php b/src/Completion/MemberCandidates.php index 2e58a7d3..d97cc8ba 100644 --- a/src/Completion/MemberCandidates.php +++ b/src/Completion/MemberCandidates.php @@ -29,10 +29,10 @@ public function __construct( public function find(MemberAccessContext $context): array { $members = $this->symbols->getAccessibleMembers( - $context->type, - $context->from, - $context->memberFilter, - $context->static, + $context->target->type, + $context->target->from, + $context->memberFilter(), + $context->target->static(), ); $snippetSupport = $this->capabilities->getSessionCapabilities()->snippetSupport; @@ -44,7 +44,7 @@ public function find(MemberAccessContext $context): array } } - if ($context->offersClassConstant && PrefixMatcher::matches('class', $context->prefix)) { + if ($context->offersClassConstant() && PrefixMatcher::matches('class', $context->prefix)) { $items[] = $this->itemFormatter->forClassConstant(); } diff --git a/src/Resolution/ExpressionResolver.php b/src/Resolution/ExpressionResolver.php index bf82627e..e220d2e1 100644 --- a/src/Resolution/ExpressionResolver.php +++ b/src/Resolution/ExpressionResolver.php @@ -13,11 +13,9 @@ use Firehed\PhpLsp\Domain\FunctionInfo; use Firehed\PhpLsp\Domain\FunctionName; use Firehed\PhpLsp\Domain\Location; -use Firehed\PhpLsp\Domain\MemberInfoInterface; use Firehed\PhpLsp\Domain\MethodInfo; use Firehed\PhpLsp\Domain\NameKind; use Firehed\PhpLsp\Domain\ParameterInfo; -use Firehed\PhpLsp\Domain\PropertyInfo; use Firehed\PhpLsp\Domain\ResolvedCallableInterface; use Firehed\PhpLsp\Domain\ResolvedSymbolInterface; use Firehed\PhpLsp\Domain\TypeInterface; @@ -45,7 +43,6 @@ use PhpParser\Node\Name; use PhpParser\Node\Param; use PhpParser\Node\Stmt; -use PhpParser\Node\VarLikeIdentifier; use PhpParser\PrettyPrinter\Standard as PrettyPrinter; /** @@ -77,30 +74,15 @@ public function resolve(Expr $expr, ParsedDocument $parsed): ?ResolvedSymbolInte return $this->resolveNew($expr, $parsed); } - if ($expr instanceof MethodCall || $expr instanceof NullsafeMethodCall) { - return $this->resolveMethodCall($expr, $parsed); - } - - if ($expr instanceof StaticCall) { - return $this->resolveStaticCall($expr, $parsed); + $access = MemberAccess::of($expr); + if ($access !== null) { + return $this->resolveMember($access, $parsed); } if ($expr instanceof FuncCall) { return $this->resolveFuncCall($expr, $parsed); } - if ($expr instanceof PropertyFetch || $expr instanceof NullsafePropertyFetch) { - return $this->resolvePropertyFetch($expr, $parsed); - } - - if ($expr instanceof StaticPropertyFetch) { - return $this->resolveStaticPropertyFetch($expr, $parsed); - } - - if ($expr instanceof ClassConstFetch) { - return $this->resolveClassConstFetch($expr, $parsed); - } - if ($expr instanceof Expr\ConstFetch) { return $this->resolveConstFetch($expr, $parsed); } @@ -144,22 +126,25 @@ public function resolveBinding(VariableBinding $binding, ParsedDocument $parsed) return new ResolvedVariable($binding->name, $type, $location); } - public function memberTarget(Expr|Name $receiver, ParsedDocument $parsed): ?MemberTarget + public function memberTarget(MemberAccess $access, ParsedDocument $parsed): ?MemberTarget { - $scope = Scope::at($receiver, $parsed->tree); + $kind = $access->kind(); + if ($kind === null) { + return null; + } + $scope = Scope::at($access->node, $parsed->tree); + $receiver = $access->receiver; if ($receiver instanceof Name) { $className = $scope->resolveClasslikeName($receiver); - return $className === null ? null : new MemberTarget( - new ClasslikeType($className), - $scope->getSelfName(), - $scope->staticFor($receiver), - ); + return $className === null + ? null + : new MemberTarget(new ClasslikeType($className), $scope->getSelfName(), $kind); } $type = $this->resolve($receiver, $parsed)?->getType(); if ($type === null || $type->getResolvableClasslikeNames() === []) { return null; } - return new MemberTarget($type, $scope->getSelfName(), null); + return new MemberTarget($type, $scope->getSelfName(), $kind); } public function resolveParameter(Param $param, ParsedDocument $parsed): ParameterInfo @@ -301,38 +286,43 @@ private function resolveConstructor(New_|Attribute $call, ParsedDocument $parsed if (!$classNameNode instanceof Name) { return null; } - return $this->resolveMember( - $classNameNode, - '__construct', - $this->memberResolver->findMethod(...), - $parsed, - ); + $scope = Scope::at($call, $parsed->tree); + $class = $scope->resolveClasslikeName($classNameNode); + return $class === null + ? null + : $this->memberResolver->findMethod($class, '__construct', $scope->getSelfName(), null); } - private function resolveMethodCall(MethodCall|NullsafeMethodCall $expr, ParsedDocument $parsed): ?MethodInfo + /** + * The member an access names, looked up on what it is accessed on. Only a + * member visible from where the access is written is found. + */ + private function resolveMember(MemberAccess $access, ParsedDocument $parsed): ?ResolvedSymbolInterface { - if (!$expr->name instanceof Identifier) { + if (!$access->name instanceof Identifier) { return null; } - return $this->resolveMember( - $expr->var, - $expr->name->toString(), - $this->memberResolver->findMethod(...), - $parsed, - ); - } - - private function resolveStaticCall(StaticCall $expr, ParsedDocument $parsed): ?MethodInfo - { - if (!$expr->name instanceof Identifier || !$expr->class instanceof Name) { + $target = $this->memberTarget($access, $parsed); + if ($target === null) { return null; } - return $this->resolveMember( - $expr->class, - $expr->name->toString(), - $this->memberResolver->findMethod(...), - $parsed, - ); + $name = $access->name->toString(); + $node = $access->node; + foreach ($target->type->getResolvableClasslikeNames() as $class) { + $member = match (true) { + $node instanceof MethodCall, $node instanceof NullsafeMethodCall, $node instanceof StaticCall + => $this->memberResolver->findMethod($class, $name, $target->from, $target->static()), + $node instanceof ClassConstFetch => $this->memberResolver->findEnumCase($class, $name) + ?? $this->memberResolver->findConstant($class, $name, $target->from, $target->static()), + $node instanceof PropertyFetch, $node instanceof NullsafePropertyFetch, + $node instanceof StaticPropertyFetch + => $this->memberResolver->findProperty($class, $name, $target->from, $target->static()), + }; + if ($member !== null) { + return $member; + } + } + return null; } private function resolveFuncCall(FuncCall $expr, ParsedDocument $parsed): ?FunctionInfo @@ -356,76 +346,6 @@ private function resolveFuncCall(FuncCall $expr, ParsedDocument $parsed): ?Funct return null; } - private function resolvePropertyFetch( - PropertyFetch|NullsafePropertyFetch $expr, - ParsedDocument $parsed, - ): ?PropertyInfo { - if (!$expr->name instanceof Identifier) { - return null; - } - return $this->resolveMember( - $expr->var, - $expr->name->toString(), - $this->memberResolver->findProperty(...), - $parsed, - ); - } - - private function resolveStaticPropertyFetch(StaticPropertyFetch $expr, ParsedDocument $parsed): ?PropertyInfo - { - if (!$expr->name instanceof VarLikeIdentifier || !$expr->class instanceof Name) { - return null; - } - return $this->resolveMember( - $expr->class, - $expr->name->toString(), - $this->memberResolver->findProperty(...), - $parsed, - ); - } - - /** - * Access a member on the receiver, delegating the kind-specific lookup to - * `$find`. Only a member visible from where the access is written is found. - * - * @template T of MemberInfoInterface - * @param callable(ClasslikeName, string, ?ClasslikeName, ?ClasslikeName): ?T $find - * @return ?T - */ - private function resolveMember( - Expr|Name $receiver, - string $memberName, - callable $find, - ParsedDocument $parsed, - ): ?MemberInfoInterface { - $target = $this->memberTarget($receiver, $parsed); - if ($target === null) { - return null; - } - foreach ($target->type->getResolvableClasslikeNames() as $className) { - $member = $find($className, $memberName, $target->from, $target->static); - if ($member !== null) { - return $member; - } - } - return null; - } - - private function resolveClassConstFetch(ClassConstFetch $expr, ParsedDocument $parsed): ?ResolvedSymbolInterface - { - if (!$expr->name instanceof Identifier || !$expr->class instanceof Name) { - return null; - } - return $this->resolveMember( - $expr->class, - $expr->name->toString(), - fn (ClasslikeName $class, string $name, ?ClasslikeName $from, ?ClasslikeName $static) - => $this->memberResolver->findEnumCase($class, $name) - ?? $this->memberResolver->findConstant($class, $name, $from, $static), - $parsed, - ); - } - private function resolveConstFetch(Expr\ConstFetch $expr, ParsedDocument $parsed): ?ConstantInfo { // See resolveFuncCall for why toCodeString(): the same NameResolver may diff --git a/src/Resolution/ExpressionResolverInterface.php b/src/Resolution/ExpressionResolverInterface.php index 29b59b88..8754e413 100644 --- a/src/Resolution/ExpressionResolverInterface.php +++ b/src/Resolution/ExpressionResolverInterface.php @@ -15,7 +15,6 @@ use PhpParser\Node\Expr\New_; use PhpParser\Node\Expr\NullsafeMethodCall; use PhpParser\Node\Expr\StaticCall; -use PhpParser\Node\Name; use PhpParser\Node\Param; /** @@ -35,11 +34,11 @@ public function resolveCallable( ): ?ResolvedCallableInterface; /** - * What a member accessed on $receiver is looked up on, or null when the - * receiver names no class-like. A class named as written resolves where it - * is written. + * What a member access is looked up on, or null when what it is accessed + * on names no class-like or is an expression before `::`. A class named + * as written resolves where it is written. */ - public function memberTarget(Expr|Name $receiver, ParsedDocument $parsed): ?MemberTarget; + public function memberTarget(MemberAccess $access, ParsedDocument $parsed): ?MemberTarget; /** * A parameter as its declaration declares it. diff --git a/src/Resolution/MemberAccess.php b/src/Resolution/MemberAccess.php new file mode 100644 index 00000000..078e7499 --- /dev/null +++ b/src/Resolution/MemberAccess.php @@ -0,0 +1,60 @@ +`, `?->`, or `::` with what it is accessed on + * ($receiver) and the member's name. + */ +final readonly class MemberAccess +{ + private function __construct( + public Expr\MethodCall|Expr\NullsafeMethodCall|Expr\PropertyFetch|Expr\NullsafePropertyFetch + |Expr\StaticCall|Expr\StaticPropertyFetch|Expr\ClassConstFetch $node, + public Expr|Name $receiver, + public Identifier|Expr $name, + public bool $doubleColon, + ) { + } + + /** + * The member access a node is, or null when it is none. + */ + public static function of(?Node $node): ?self + { + return match (true) { + $node instanceof Expr\MethodCall, $node instanceof Expr\NullsafeMethodCall, + $node instanceof Expr\PropertyFetch, $node instanceof Expr\NullsafePropertyFetch + => new self($node, $node->var, $node->name, false), + $node instanceof Expr\StaticCall, $node instanceof Expr\StaticPropertyFetch, + $node instanceof Expr\ClassConstFetch + => new self($node, $node->class, $node->name, true), + default => null, + }; + } + + /** + * How the access is written; null for `::` after an expression rather + * than a class name. + */ + public function kind(): ?MemberAccessKind + { + if (!$this->doubleColon) { + return MemberAccessKind::Instance; + } + if (!$this->receiver instanceof Name) { + return null; + } + return LateBindingKeyword::tryFromName($this->receiver->toString()) === LateBindingKeyword::Parent + ? MemberAccessKind::Parent + : MemberAccessKind::Static; + } +} diff --git a/src/Resolution/MemberAccessContext.php b/src/Resolution/MemberAccessContext.php index 46f873c9..b1107266 100644 --- a/src/Resolution/MemberAccessContext.php +++ b/src/Resolution/MemberAccessContext.php @@ -4,88 +4,37 @@ namespace Firehed\PhpLsp\Resolution; -use Firehed\PhpLsp\Domain\ClasslikeName; use Firehed\PhpLsp\Domain\MemberFilter; use Firehed\PhpLsp\Domain\ResolvedMemberInterface; -use Firehed\PhpLsp\Domain\TypeInterface; /** - * A member access being written: what it is on, and the class-like the access - * is written in ($from; null outside any class), which decides the members it - * may use. $static is the class `static` names when it is not what the access - * is on. + * A member access being written: what it is, and the part of the member's name + * typed so far. */ final readonly class MemberAccessContext { - private function __construct( - public TypeInterface $type, - public ?ClasslikeName $from, - public ?ClasslikeName $static, - public MemberAccessKind $kind, + public function __construct( + public MemberTarget $target, public string $prefix, - public MemberFilter $memberFilter, - public bool $offersClassConstant, - private bool $methodsOnly, ) { } - public static function forInstance( - TypeInterface $type, - ?ClasslikeName $from, - string $prefix, - ): self { - return new self( - $type, - $from, - null, - MemberAccessKind::Instance, - $prefix, - MemberFilter::Instance, - false, - false, - ); - } - - public static function forStatic( - TypeInterface $type, - ?ClasslikeName $from, - string $prefix, - ): self { - return new self( - $type, - $from, - null, - MemberAccessKind::Static, - $prefix, - MemberFilter::Static, - true, - false, - ); + public function memberFilter(): MemberFilter + { + return match ($this->target->kind) { + MemberAccessKind::Instance => MemberFilter::Instance, + MemberAccessKind::Static => MemberFilter::Static, + MemberAccessKind::Parent => MemberFilter::All, + }; } - public static function forParent( - TypeInterface $type, - ?ClasslikeName $from, - ?ClasslikeName $static, - string $prefix, - ): self { - return new self( - $type, - $from, - $static, - MemberAccessKind::Parent, - $prefix, - MemberFilter::All, - false, - true, - ); + public function offersClassConstant(): bool + { + return $this->target->kind === MemberAccessKind::Static; } public function accepts(ResolvedMemberInterface $member): bool { - if ($this->methodsOnly && !$member->getMemberKind()->isMethod()) { - return false; - } - return true; + return $this->target->kind !== MemberAccessKind::Parent || $member->getMemberKind()->isMethod(); } } diff --git a/src/Resolution/MemberTarget.php b/src/Resolution/MemberTarget.php index 06b927df..eb6870cb 100644 --- a/src/Resolution/MemberTarget.php +++ b/src/Resolution/MemberTarget.php @@ -9,15 +9,24 @@ /** * What a member access is looked up on: the type it is on, the class-like the - * access is written in ($from; null outside any class), and, for a `parent::` - * access, the class `static` names ($static). + * access is written in ($from; null outside any class), and how it is written. */ final readonly class MemberTarget { public function __construct( public TypeInterface $type, public ?ClasslikeName $from, - public ?ClasslikeName $static, + public MemberAccessKind $kind, ) { } + + /** + * The class `static` names when it is not the class accessed: a + * `parent::` access passes on the class it is written in (PHP manual, + * Late Static Bindings). + */ + public function static(): ?ClasslikeName + { + return $this->kind === MemberAccessKind::Parent ? $this->from : null; + } } diff --git a/src/Resolution/Position/ExpectedAtPosition.php b/src/Resolution/Position/ExpectedAtPosition.php index 411b4258..cef4d7f8 100644 --- a/src/Resolution/Position/ExpectedAtPosition.php +++ b/src/Resolution/Position/ExpectedAtPosition.php @@ -14,7 +14,6 @@ use Firehed\PhpLsp\Resolution\ExpressionResolverInterface; use Firehed\PhpLsp\Resolution\MemberAccessContext; use Firehed\PhpLsp\Resolution\NameQuery; -use PhpParser\Node\Name; final class ExpectedAtPosition implements ExpectedAtPositionInterface { @@ -33,7 +32,7 @@ public function expectedAt(TextDocument $document, ByteOffset $offset): Expected return match ($located->slot) { Slot::NotCode, Slot::DeclaredName => new Expected($prefix), Slot::InterpolatedString, Slot::Variable => new Expected($prefix, variables: true), - Slot::Member, Slot::StaticMember => new Expected($prefix, members: $this->memberAccess($located)), + Slot::Member => new Expected($prefix, members: $this->memberAccess($located)), Slot::ArgumentName => new Expected($prefix, argumentNames: $this->calls->callAt($document, $offset)), Slot::ClassMember => $prefix === '' ? new Expected($prefix) : new Expected( $prefix, @@ -97,19 +96,10 @@ private function memberAccess(Located $located): ?MemberAccessContext { // A static property's name is written with its `$`; a member's name is not. $prefix = ltrim($located->prefix, '$'); - $receiver = $located->receiver; - assert($receiver !== null, 'a member is accessed on something'); - if ($located->slot === Slot::StaticMember && !$receiver instanceof Name) { - return null; - } + assert($located->access !== null, 'a member is accessed on something'); - $target = $this->expressions->memberTarget($receiver, $located->parsed); - return match (true) { - $target === null => null, - $located->slot === Slot::Member => MemberAccessContext::forInstance($target->type, $target->from, $prefix), - $target->static === null => MemberAccessContext::forStatic($target->type, $target->from, $prefix), - default => MemberAccessContext::forParent($target->type, $target->from, $target->static, $prefix), - }; + $target = $this->expressions->memberTarget($located->access, $located->parsed); + return $target === null ? null : new MemberAccessContext($target, $prefix); } private static function type(Located $located, TypeHintContext $context): Expected diff --git a/src/Resolution/Position/Located.php b/src/Resolution/Position/Located.php index 2796c839..f897bbfa 100644 --- a/src/Resolution/Position/Located.php +++ b/src/Resolution/Position/Located.php @@ -6,10 +6,9 @@ use Firehed\PhpLsp\Domain\ByteOffset; use Firehed\PhpLsp\Parser\ParsedDocument; +use Firehed\PhpLsp\Resolution\MemberAccess; use Firehed\PhpLsp\Resolution\Scope; use PhpParser\Node; -use PhpParser\Node\Expr; -use PhpParser\Node\Name; /** * What a document's structure has at a position, read once, for the position @@ -20,8 +19,8 @@ /** * @param string $prefix The part of a word written before the position * @param ?Node $written The node for the word - * @param Expr|Name|null $receiver What a member is accessed on: set exactly - * when the slot is {@see Slot::Member} or {@see Slot::StaticMember} + * @param ?MemberAccess $access The member access whose name is at the + * position: set exactly when the slot is {@see Slot::Member} */ public function __construct( public ParsedDocument $parsed, @@ -29,7 +28,7 @@ public function __construct( public Slot $slot, public string $prefix, public ?Node $written, - public Expr|Name|null $receiver, + public ?MemberAccess $access, public Scope $scope, public ?CallSite $call, ) { diff --git a/src/Resolution/Position/PositionLocator.php b/src/Resolution/Position/PositionLocator.php index 71afc985..9d4f825c 100644 --- a/src/Resolution/Position/PositionLocator.php +++ b/src/Resolution/Position/PositionLocator.php @@ -9,6 +9,7 @@ use Firehed\PhpLsp\Parser\NodeAtPosition; use Firehed\PhpLsp\Parser\ParsedDocument; use Firehed\PhpLsp\Parser\SyntaxSource\SyntaxSourceInterface; +use Firehed\PhpLsp\Resolution\MemberAccess; use Firehed\PhpLsp\Resolution\Scope; use PhpParser\Node; use PhpParser\Node\Arg; @@ -53,7 +54,7 @@ public function locate(TextDocument $document, ByteOffset $offset): Located $node = self::isWord($found) ? $found : (self::emptySlotNear($found, $parsed->tree, $code, $at) ?? $found); preg_match('/\$?[\w\\\\\x80-\xff]*$/', self::text($code, max(0, $at - 256), $at), $word); $prefix = $word[0] ?? ''; - [$slot, $receiver] = match (true) { + [$slot, $access] = match (true) { self::inComment($found, $parsed->tree, $at) => [Slot::NotCode, null], $node instanceof FunctionLike => [self::headerSlot($node, $code, $at, $prefix) ?? Slot::Expression, null], $node instanceof Stmt\ClassLike => [self::memberHeaderSlot($node, $code, $at, $prefix), null], @@ -76,7 +77,7 @@ public function locate(TextDocument $document, ByteOffset $offset): Located $slot, $prefix, $written, - $receiver, + $access, Scope::at($node, $parsed->tree), $call, ); @@ -240,11 +241,12 @@ private static function punctuation(string $code, int $from, int $at, string $pr } /** - * @return array{Slot, Expr|Name|null} + * @return array{Slot, MemberAccess|null} */ private static function classify(?Node $node, int $at): array { $parent = $node?->getAttribute('parent'); + $access = MemberAccess::of($node); return match (true) { $node === null => [Slot::Expression, null], $node instanceof Scalar\String_ && $at <= $node->getEndFilePos() => [ @@ -264,14 +266,9 @@ private static function classify(?Node $node, int $at): array $parent instanceof Node\Param && $parent->var === $node ? Slot::DeclaredName : Slot::Variable, null, ], - ($node instanceof Expr\MethodCall || $node instanceof Expr\NullsafeMethodCall - || $node instanceof Expr\PropertyFetch || $node instanceof Expr\NullsafePropertyFetch) - && $at > $node->var->getEndFilePos() && $at <= $node->name->getStartFilePos() - => [Slot::Member, $node->var], - ($node instanceof Expr\StaticCall || $node instanceof Expr\ClassConstFetch - || $node instanceof Expr\StaticPropertyFetch) - && $at > $node->class->getEndFilePos() && $at <= $node->name->getStartFilePos() - => [Slot::StaticMember, $node->class], + $access !== null + && $at > $access->receiver->getEndFilePos() && $at <= $access->name->getStartFilePos() + => [Slot::Member, $access], ($node instanceof Stmt\Property || $node instanceof Stmt\ClassConst) && $at <= self::firstWrittenPart($node) => [self::memberStartSlot($node, $at), null], $node instanceof Identifier, $node instanceof Name, $node instanceof Expr\Error @@ -281,24 +278,15 @@ private static function classify(?Node $node, int $at): array } /** - * @return array{Slot, Expr|Name|null} + * @return array{Slot, MemberAccess|null} */ private static function classifyName(Identifier|Name|Expr\Error $name, mixed $parent): array { - if ( - ($parent instanceof Expr\MethodCall || $parent instanceof Expr\NullsafeMethodCall - || $parent instanceof Expr\PropertyFetch || $parent instanceof Expr\NullsafePropertyFetch) - && $parent->name === $name - ) { - return [Slot::Member, $parent->var]; + $access = MemberAccess::of($parent instanceof Node ? $parent : null); + if ($access?->name === $name) { + return [Slot::Member, $access]; } - if ( - ($parent instanceof Expr\StaticCall || $parent instanceof Expr\ClassConstFetch - || $parent instanceof Expr\StaticPropertyFetch) - ) { - if ($parent->name === $name) { - return [Slot::StaticMember, $parent->class]; - } + if ($access?->doubleColon === true && $access->receiver === $name) { return [Slot::StaticReceiver, null]; } if ($parent instanceof Arg && $parent->name === $name) { diff --git a/src/Resolution/Position/Slot.php b/src/Resolution/Position/Slot.php index e788c97c..9d0d0e21 100644 --- a/src/Resolution/Position/Slot.php +++ b/src/Resolution/Position/Slot.php @@ -18,10 +18,8 @@ enum Slot case Expression; /** The name of a function being called. */ case CalledName; - /** A member name after `->` or `?->`. */ + /** A member name after `->`, `?->`, or `::`. */ case Member; - /** A member name after `::`. */ - case StaticMember; /** The class name before `::`. */ case StaticReceiver; /** An argument's name, written with its colon. */ diff --git a/src/Resolution/Position/SymbolAtPosition.php b/src/Resolution/Position/SymbolAtPosition.php index f24444b8..7edff036 100644 --- a/src/Resolution/Position/SymbolAtPosition.php +++ b/src/Resolution/Position/SymbolAtPosition.php @@ -35,7 +35,8 @@ public function symbolAt(TextDocument $document, ByteOffset $offset): ?ResolvedS return match ($located->slot) { Slot::NotCode, Slot::InterpolatedString, Slot::ClassMember => null, Slot::Variable => $this->variable($written, $located->parsed), - Slot::Member, Slot::StaticMember, Slot::CalledName => $this->usedBy($written, $located->parsed), + Slot::Member => $this->member($located), + Slot::CalledName => $this->calledBy($written, $located->parsed), Slot::ArgumentName => $this->parameterNamed($located), Slot::DeclaredName => $parent instanceof Node\Param ? $this->expressions->resolveParameter($parent, $located->parsed) @@ -62,15 +63,27 @@ private function variable(?Node $written, ParsedDocument $parsed): ?ResolvedSymb } /** - * What the expression a member or called name is part of resolves to. + * What the access a written member name is part of resolves to. */ - private function usedBy(?Node $written, ParsedDocument $parsed): ?ResolvedSymbolInterface + private function member(Located $located): ?ResolvedSymbolInterface + { + if ($located->written === null) { + return null; + } + assert($located->access !== null, 'a member name is part of the access that uses it'); + return $this->expressions->resolve($located->access->node, $located->parsed); + } + + /** + * What the call a called name is part of resolves to. + */ + private function calledBy(?Node $written, ParsedDocument $parsed): ?ResolvedSymbolInterface { if ($written === null) { return null; } $expression = $written->getAttribute('parent'); - assert($expression instanceof Expr, 'a member or called name is part of the expression that uses it'); + assert($expression instanceof Expr, 'a called name is part of the call that uses it'); return $this->expressions->resolve($expression, $parsed); } diff --git a/src/Resolution/Scope.php b/src/Resolution/Scope.php index 763756cf..768bfbf3 100644 --- a/src/Resolution/Scope.php +++ b/src/Resolution/Scope.php @@ -163,18 +163,6 @@ public function resolveClasslikeName(Name $name): ?ClasslikeName return ClasslikeName::fromFullyQualified($name->toString()); } - /** - * The class `static` names in a member accessed on $receiver here, when it - * is not the class accessed: a `parent::` access passes on the class it is - * written in (PHP manual, Late Static Bindings). Null otherwise. - */ - public function staticFor(Name $receiver): ?ClasslikeName - { - return LateBindingKeyword::tryFromName($receiver->toString()) === LateBindingKeyword::Parent - ? $this->getSelfName() - : null; - } - /** * How a name written here resolves: the enclosing namespace and its imports. * A `use` is in effect only inside its own namespace block, so a file diff --git a/tests/Completion/CompositeCompletionSourceTest.php b/tests/Completion/CompositeCompletionSourceTest.php index f355756f..0479c7d2 100644 --- a/tests/Completion/CompositeCompletionSourceTest.php +++ b/tests/Completion/CompositeCompletionSourceTest.php @@ -26,6 +26,8 @@ use Firehed\PhpLsp\Resolution\CallContext; use Firehed\PhpLsp\Resolution\Expected; use Firehed\PhpLsp\Resolution\MemberAccessContext; +use Firehed\PhpLsp\Resolution\MemberAccessKind; +use Firehed\PhpLsp\Resolution\MemberTarget; use Firehed\PhpLsp\Resolution\NameContext; use Firehed\PhpLsp\Resolution\NameQuery; use Firehed\PhpLsp\Resolution\Position\ExpectedAtPositionInterface; @@ -50,7 +52,10 @@ public function testEachThingThePositionAdmitsIsOfferedByItsSourceInOneList(): v $items = self::source(new Expected( 'n', - members: MemberAccessContext::forInstance(new ClasslikeType(self::owner()), null, ''), + members: new MemberAccessContext( + new MemberTarget(new ClasslikeType(self::owner()), null, MemberAccessKind::Instance), + '', + ), argumentNames: new CallContext($callable, 0, []), variables: true, keywords: KeywordGroup::Expression, diff --git a/tests/Completion/MemberCandidatesTest.php b/tests/Completion/MemberCandidatesTest.php index 091cb485..0fd15bd0 100644 --- a/tests/Completion/MemberCandidatesTest.php +++ b/tests/Completion/MemberCandidatesTest.php @@ -15,6 +15,8 @@ use Firehed\PhpLsp\Domain\PropertyName; use Firehed\PhpLsp\Domain\ResolvedMemberInterface; use Firehed\PhpLsp\Resolution\MemberAccessContext; +use Firehed\PhpLsp\Resolution\MemberAccessKind; +use Firehed\PhpLsp\Resolution\MemberTarget; use Firehed\PhpLsp\Resolution\ResolvedSymbolPresenter; use Firehed\PhpLsp\Resolution\SymbolCapabilitiesInterface; use PHPUnit\Framework\Attributes\CoversClass; @@ -31,37 +33,47 @@ final class MemberCandidatesTest extends TestCase */ public static function contextCases(): iterable { - $type = new ClasslikeType(self::owner()); yield 'instance, every member' => [ - MemberAccessContext::forInstance($type, null, ''), + self::context(MemberAccessKind::Instance, ''), ['getName', 'getCount', 'name'], ]; yield 'instance, prefix' => [ - MemberAccessContext::forInstance($type, null, 'get'), + self::context(MemberAccessKind::Instance, 'get'), ['getName', 'getCount'], ]; yield 'instance, prefix that matches nothing' => [ - MemberAccessContext::forInstance($type, null, 'zzz'), + self::context(MemberAccessKind::Instance, 'zzz'), [], ]; yield 'parent, methods only' => [ - MemberAccessContext::forParent($type, self::owner(), self::owner(), ''), + self::context(MemberAccessKind::Parent, ''), ['getName', 'getCount'], ]; yield 'static adds ::class' => [ - MemberAccessContext::forStatic($type, null, ''), + self::context(MemberAccessKind::Static, ''), ['getName', 'getCount', 'name', 'class'], ]; yield 'static prefix that matches only class' => [ - MemberAccessContext::forStatic($type, null, 'cl'), + self::context(MemberAccessKind::Static, 'cl'), ['class'], ]; yield 'static prefix that misses class' => [ - MemberAccessContext::forStatic($type, null, 'get'), + self::context(MemberAccessKind::Static, 'get'), ['getName', 'getCount'], ]; } + /** + * An access on the owner, written inside it. + */ + private static function context(MemberAccessKind $kind, string $prefix): MemberAccessContext + { + return new MemberAccessContext( + new MemberTarget(new ClasslikeType(self::owner()), self::owner(), $kind), + $prefix, + ); + } + /** * @param list $expected */ @@ -71,7 +83,7 @@ public function testOffersTheResolvedMembersTheContextAccepts(MemberAccessContex $symbols = $this->createMock(SymbolCapabilitiesInterface::class); $symbols->expects(self::once()) ->method('getAccessibleMembers') - ->with($context->type, $context->from, $context->memberFilter, $context->static) + ->with($context->target->type, $context->target->from, $context->memberFilter(), $context->target->static()) ->willReturn([ self::member(new MethodName(self::owner(), 'getName'), MemberKind::Method), self::member(new MethodName(self::owner(), 'getCount'), MemberKind::Method), @@ -95,7 +107,7 @@ public function testMethodsInsertASnippetWhenTheClientSupportsIt(): void ]); $items = self::candidates($symbols, snippetSupport: true) - ->find(MemberAccessContext::forInstance(new ClasslikeType(self::owner()), null, '')); + ->find(self::context(MemberAccessKind::Instance, '')); self::assertSame( InsertTextFormat::Snippet->value, diff --git a/tests/Fixtures/src/Completion/StaticAccess.php b/tests/Fixtures/src/Completion/StaticAccess.php index e237bfcb..1e270111 100644 --- a/tests/Fixtures/src/Completion/StaticAccess.php +++ b/tests/Fixtures/src/Completion/StaticAccess.php @@ -68,4 +68,9 @@ public function triggerSelfChainPrefix(): void { self::getInstance()->get/*|self_chain_prefix*/ } + + public function triggerThisStatic(): void + { + $this::/*|this_static*/ + } } diff --git a/tests/Fixtures/src/Mixed/ProceduralWithClass.php b/tests/Fixtures/src/Mixed/ProceduralWithClass.php index 1800cf2d..4ab4737b 100644 --- a/tests/Fixtures/src/Mixed/ProceduralWithClass.php +++ b/tests/Fixtures/src/Mixed/ProceduralWithClass.php @@ -85,3 +85,8 @@ function processArrayObject(\ArrayObject $obj): void { $obj->/*|array_object_access*/ } + +function triggerNewSelfOutsideClass(): void +{ + new self(name/*|new_self_outside_class*/: 'x'); +} diff --git a/tests/Fixtures/src/TypeInference/NewKeywords.php b/tests/Fixtures/src/TypeInference/NewKeywords.php index ed5b2920..225b81d4 100644 --- a/tests/Fixtures/src/TypeInference/NewKeywords.php +++ b/tests/Fixtures/src/TypeInference/NewKeywords.php @@ -20,7 +20,7 @@ public static function createStatic(): static public function createParent(): ParentClass { - return new parent(); + return new parent(/*|parent_constructor*/); } public static function getInstance(): self diff --git a/tests/Resolution/ExpressionResolutionTest.php b/tests/Resolution/ExpressionResolutionTest.php index 164de5e6..6ea559a2 100644 --- a/tests/Resolution/ExpressionResolutionTest.php +++ b/tests/Resolution/ExpressionResolutionTest.php @@ -32,6 +32,7 @@ use Firehed\PhpLsp\Repository\MemberResolver; use Firehed\PhpLsp\Repository\MemberResolverInterface; use Firehed\PhpLsp\Resolution\ExpressionResolver; +use Firehed\PhpLsp\Resolution\MemberAccessKind; use Firehed\PhpLsp\Resolution\MemberTarget; use Firehed\PhpLsp\Resolution\Position\PositionLocator; use Firehed\PhpLsp\Resolution\Position\SymbolAtPosition; @@ -41,6 +42,10 @@ use Firehed\PhpLsp\Tests\BuildsSymbolInfoTrait; use Firehed\PhpLsp\Tests\LoadsFixturesTrait; use Firehed\PhpLsp\Tests\Parser\ProductionSyntaxSource; +use PhpParser\Node; +use PhpParser\Node\Expr\MethodCall; +use PhpParser\Node\Expr\Variable; +use PhpParser\NodeFinder; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -496,6 +501,79 @@ public function testAnArgumentsNameIsAParameterOfTheConstructorRun(): void ); } + public function testAMemberNamedByAnExpressionIsUnresolved(): void + { + $members = $this->createMock(MemberResolverInterface::class); + $members->expects(self::never())->method('findMethod'); + $expressions = new ExpressionResolver( + $members, + self::createStub(SymbolSourceInterface::class), + self::createStub(TypeSourceInterface::class), + ); + $parsed = ProductionSyntaxSource::create()->source->parse( + new TextDocument(self::uri(self::DYNAMIC), 'php', 1, $this->loadFixture(self::DYNAMIC)), + ); + $call = (new NodeFinder())->findFirst( + $parsed->tree, + static fn (Node $node): bool => $node instanceof MethodCall && $node->name instanceof Variable, + ); + assert($call instanceof MethodCall, 'the fixture calls a method named by a variable on $this'); + + self::assertNull( + $expressions->resolve($call, $parsed), + 'which member is called is only known at runtime', + ); + } + + public function testAConstructorOfAKeywordOutsideAClassIsUnresolved(): void + { + $members = $this->createMock(MemberResolverInterface::class); + $members->expects(self::never())->method('findMethod'); + $this->resolver = self::resolverOver( + self::createStub(SymbolSourceInterface::class), + self::createStub(TypeSourceInterface::class), + $members, + ); + + self::assertNull( + $this->resolveAt( + 'src/Mixed/ProceduralWithClass.php', + fn (string $content): array => $this->locateCursor($content, 'new_self_outside_class'), + ), + 'self names no class outside one, so there is no constructor to look up', + ); + } + + /** + * `new parent()` makes an instance of the parent, so `static` in its + * constructor is the parent itself, not the class it is written in. + */ + public function testAConstructorIsLookedUpWithoutForwardingStatic(): void + { + $located = (new PositionLocator(ProductionSyntaxSource::create()->source))->locate(...$this->positionIn( + 'src/TypeInference/NewKeywords.php', + fn (string $content): array => $this->locateCursor($content, 'parent_constructor'), + )); + assert($located->call !== null, 'the position is in the constructor\'s argument list'); + + $members = $this->createMock(MemberResolverInterface::class); + $members->expects(self::once()) + ->method('findMethod') + ->with( + self::className('Fixtures\Inheritance\ParentClass'), + '__construct', + self::className('Fixtures\TypeInference\NewKeywords'), + null, + ); + $expressions = new ExpressionResolver( + $members, + self::createStub(SymbolSourceInterface::class), + self::createStub(TypeSourceInterface::class), + ); + + $expressions->resolveCallable($located->call->call, $located->parsed); + } + public function testMethodCallResolvesOnTheReceiversClass(): void { $this->knowUserMembers(); @@ -567,7 +645,7 @@ public static function memberTargets(): iterable yield '$this' => [ 'MultiClass/MultiClass.php', 'this_in_second_class', - new MemberTarget(new ClasslikeType($inMultiClass), $inMultiClass, null), + new MemberTarget(new ClasslikeType($inMultiClass), $inMultiClass, MemberAccessKind::Instance), ]; yield 'parent::' => [ 'src/Completion/InheritanceCompletion.php', @@ -575,16 +653,32 @@ public static function memberTargets(): iterable new MemberTarget( new ClasslikeType(self::className('Fixtures\Inheritance\ChildClass')), $inheritance, - $inheritance, + MemberAccessKind::Parent, ), ]; yield 'a class by name, outside any class' => [ $procedural, 'standalone_static_access', - new MemberTarget(new ClasslikeType(self::className('Fixtures\Completion\StaticAccess')), null, null), + new MemberTarget( + new ClasslikeType(self::className('Fixtures\Completion\StaticAccess')), + null, + MemberAccessKind::Static, + ), + ]; + $static = self::className('Fixtures\Completion\StaticAccess'); + yield 'self::' => [ + 'src/Completion/StaticAccess.php', + 'self_empty', + new MemberTarget(new ClasslikeType($static), $static, MemberAccessKind::Static), + ]; + yield 'static::' => [ + 'src/Completion/StaticAccess.php', + 'static_keyword', + new MemberTarget(new ClasslikeType($static), $static, MemberAccessKind::Static), ]; yield 'self:: outside a class' => [$procedural, 'self_outside_class', null]; yield 'an unbound variable' => [$procedural, 'unknown_var', null]; + yield 'an expression before ::' => ['src/Completion/StaticAccess.php', 'this_static', null]; } #[DataProvider('memberTargets')] @@ -809,9 +903,9 @@ private function memberTargetAt(ExpressionResolver $expressions, string $fixture { $located = (new PositionLocator(ProductionSyntaxSource::create()->source)) ->locate(...$this->positionIn($fixture, $locate)); - assert($located->receiver !== null, "a member is accessed at the position in {$fixture}"); + assert($located->access !== null, "a member is accessed at the position in {$fixture}"); - return $expressions->memberTarget($located->receiver, $located->parsed); + return $expressions->memberTarget($located->access, $located->parsed); } /** diff --git a/tests/Resolution/MemberAccessContextTest.php b/tests/Resolution/MemberAccessContextTest.php index cacc35c6..751f0bad 100644 --- a/tests/Resolution/MemberAccessContextTest.php +++ b/tests/Resolution/MemberAccessContextTest.php @@ -9,7 +9,6 @@ use Firehed\PhpLsp\Domain\MemberFilter; use Firehed\PhpLsp\Domain\MemberKind; use Firehed\PhpLsp\Domain\ResolvedMemberInterface; -use Firehed\PhpLsp\Tests\ProvidesMemberKindsTrait; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -17,93 +16,47 @@ #[CoversClass(MemberAccessContext::class)] class MemberAccessContextTest extends TestCase { - use ProvidesMemberKindsTrait; - - private static function type(): ClasslikeType - { - return new ClasslikeType(ClasslikeName::fromFullyQualified(self::class)); - } - - public function testForInstanceSetsExpectedValues(): void - { - $ctx = MemberAccessContext::forInstance(self::type(), null, 'prefix'); - - self::assertSame(MemberAccessKind::Instance, $ctx->kind, 'kind'); - self::assertSame(MemberFilter::Instance, $ctx->memberFilter, 'memberFilter'); - self::assertFalse($ctx->offersClassConstant, 'offersClassConstant'); - self::assertSame('prefix', $ctx->prefix, 'prefix'); - } - - public function testForStaticSetsExpectedValues(): void - { - $from = ClasslikeName::fromFullyQualified('App\\Caller'); - $ctx = MemberAccessContext::forStatic(self::type(), $from, 'pre'); - - self::assertSame($from, $ctx->from, 'from'); - self::assertSame(MemberAccessKind::Static, $ctx->kind, 'kind'); - self::assertSame(MemberFilter::Static, $ctx->memberFilter, 'memberFilter'); - self::assertTrue($ctx->offersClassConstant, 'offersClassConstant'); - self::assertSame('pre', $ctx->prefix, 'prefix'); - } - - public function testOnlyAParentAccessCarriesAStatic(): void - { - $from = ClasslikeName::fromFullyQualified('App\\Caller'); - $static = ClasslikeName::fromFullyQualified('App\\Late'); - - self::assertSame($static, MemberAccessContext::forParent(self::type(), $from, $static, '')->static, 'parent::'); - self::assertNull(MemberAccessContext::forStatic(self::type(), $from, '')->static, 'a named class'); - self::assertNull(MemberAccessContext::forInstance(self::type(), $from, '')->static, 'an instance'); - } - - public function testForParentSetsExpectedValues(): void - { - $ctx = MemberAccessContext::forParent(self::type(), null, null, ''); - - self::assertSame(MemberAccessKind::Parent, $ctx->kind, 'kind'); - self::assertSame(MemberFilter::All, $ctx->memberFilter, 'memberFilter'); - self::assertFalse($ctx->offersClassConstant, 'offersClassConstant'); - self::assertSame('', $ctx->prefix, 'prefix'); - } - - #[DataProvider('allMemberKinds')] - public function testInstanceAcceptsAllKinds(MemberKind $memberKind): void - { - $ctx = MemberAccessContext::forInstance(self::type(), null, ''); - $member = self::createStub(ResolvedMemberInterface::class); - $member->method('getMemberKind')->willReturn($memberKind); - - self::assertTrue($ctx->accepts($member), "instance should accept $memberKind->name"); - } - - #[DataProvider('allMemberKinds')] - public function testStaticAcceptsAllKinds(MemberKind $memberKind): void - { - $ctx = MemberAccessContext::forStatic(self::type(), null, ''); - $member = self::createStub(ResolvedMemberInterface::class); - $member->method('getMemberKind')->willReturn($memberKind); - - self::assertTrue($ctx->accepts($member), "static should accept $memberKind->name"); - } - - #[DataProvider('parentAcceptsCases')] - public function testParentAcceptsOnlyMethods(MemberKind $memberKind, bool $expected): void + /** + * @return iterable}> + */ + public static function rules(): iterable { - $ctx = MemberAccessContext::forParent(self::type(), null, null, ''); - $member = self::createStub(ResolvedMemberInterface::class); - $member->method('getMemberKind')->willReturn($memberKind); - - self::assertSame($expected, $ctx->accepts($member), "parent accepts $memberKind->name"); + $every = MemberKind::cases(); + yield 'an instance access' => [MemberAccessKind::Instance, MemberFilter::Instance, false, $every]; + yield 'a static access' => [MemberAccessKind::Static, MemberFilter::Static, true, $every]; + yield 'a parent:: access' => [MemberAccessKind::Parent, MemberFilter::All, false, [MemberKind::Method]]; } /** - * @return iterable + * @param list $accepted */ - public static function parentAcceptsCases(): iterable - { - yield 'Method' => [MemberKind::Method, true]; - yield 'Property' => [MemberKind::Property, false]; - yield 'Constant' => [MemberKind::Constant, false]; - yield 'EnumCase' => [MemberKind::EnumCase, false]; + #[DataProvider('rules')] + public function testCompletionRulesFollowTheAccessKind( + MemberAccessKind $kind, + MemberFilter $filter, + bool $offersClassConstant, + array $accepted, + ): void { + $target = new MemberTarget( + new ClasslikeType(ClasslikeName::fromFullyQualified(self::class)), + null, + $kind, + ); + + $context = new MemberAccessContext($target, 'pre'); + + self::assertSame($target, $context->target, 'what the access is'); + self::assertSame('pre', $context->prefix, 'what is typed of the member name'); + self::assertSame($filter, $context->memberFilter(), 'which members the lookup includes'); + self::assertSame($offersClassConstant, $context->offersClassConstant(), 'whether ::class is offered'); + foreach (MemberKind::cases() as $memberKind) { + $member = self::createStub(ResolvedMemberInterface::class); + $member->method('getMemberKind')->willReturn($memberKind); + self::assertSame( + in_array($memberKind, $accepted, true), + $context->accepts($member), + "whether a {$memberKind->name} is offered", + ); + } } } diff --git a/tests/Resolution/MemberAccessTest.php b/tests/Resolution/MemberAccessTest.php new file mode 100644 index 00000000..c5ddd7be --- /dev/null +++ b/tests/Resolution/MemberAccessTest.php @@ -0,0 +1,80 @@ + + */ + public static function accesses(): iterable + { + $object = new Expr\Variable('object'); + $name = new Identifier('member'); + $class = new Name('Foo'); + $parent = new Name('parent'); + $property = new VarLikeIdentifier('property'); + $instance = MemberAccessKind::Instance; + $static = MemberAccessKind::Static; + + yield '->' => [new Expr\PropertyFetch($object, $name), $object, $name, false, $instance]; + yield '?->' => [new Expr\NullsafePropertyFetch($object, $name), $object, $name, false, $instance]; + yield '-> call' => [new Expr\MethodCall($object, $name), $object, $name, false, $instance]; + yield '?-> call' => [new Expr\NullsafeMethodCall($object, $name), $object, $name, false, $instance]; + yield ':: call' => [new Expr\StaticCall($class, $name), $class, $name, true, $static]; + yield ':: property' => [new Expr\StaticPropertyFetch($class, $property), $class, $property, true, $static]; + yield ':: constant' => [new Expr\ClassConstFetch($class, $name), $class, $name, true, $static]; + yield 'parent::' => [ + new Expr\StaticCall($parent, $name), + $parent, + $name, + true, + MemberAccessKind::Parent, + ]; + yield 'an expression before ::' => [new Expr\ClassConstFetch($object, $name), $object, $name, true, null]; + } + + #[DataProvider('accesses')] + public function testReadsTheAccessWritten( + Expr $node, + Expr|Name $receiver, + Identifier|Expr $name, + bool $doubleColon, + ?MemberAccessKind $kind, + ): void { + $access = MemberAccess::of($node); + + self::assertNotNull($access, 'the node is a member access'); + self::assertSame($node, $access->node, 'the access node itself'); + self::assertSame($receiver, $access->receiver, 'what the member is accessed on'); + self::assertSame($name, $access->name, 'the member name as written'); + self::assertSame($doubleColon, $access->doubleColon, 'whether it is written with ::'); + self::assertSame($kind, $access->kind(), 'how the access is written'); + } + + public function testParentIsMatchedWhateverItsCase(): void + { + $access = MemberAccess::of(new Expr\StaticCall(new Name('PARENT'), 'make')); + + self::assertSame(MemberAccessKind::Parent, $access?->kind(), 'PHP keywords are case-insensitive'); + } + + public function testOtherNodesAreNotAccesses(): void + { + self::assertNull(MemberAccess::of(new Expr\FuncCall(new Name('strlen'))), 'a function call'); + self::assertNull(MemberAccess::of(new Expr\New_(new Name('Foo'))), 'a constructor runs no member access'); + } +} diff --git a/tests/Resolution/MemberTargetTest.php b/tests/Resolution/MemberTargetTest.php index d0e9f158..e6e5783e 100644 --- a/tests/Resolution/MemberTargetTest.php +++ b/tests/Resolution/MemberTargetTest.php @@ -6,22 +6,41 @@ use Firehed\PhpLsp\Domain\ClasslikeName; use Firehed\PhpLsp\Domain\ClasslikeType; +use Firehed\PhpLsp\Resolution\MemberAccessKind; use Firehed\PhpLsp\Resolution\MemberTarget; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; #[CoversClass(MemberTarget::class)] final class MemberTargetTest extends TestCase { - public function testConstruction(): void + /** + * @return iterable + */ + public static function kinds(): iterable + { + yield 'an instance access' => [MemberAccessKind::Instance, false]; + yield 'a static access' => [MemberAccessKind::Static, false]; + yield 'a parent:: access' => [MemberAccessKind::Parent, true]; + } + + /** + * `parent::`, `self::`, and `static::` all forward late static binding + * (PHP manual, Late Static Bindings), but seen from where the code is + * written only `parent::` names a class other than the one looked up. + */ + #[DataProvider('kinds')] + public function testOnlyAParentAccessNamesStatic(MemberAccessKind $kind, bool $forwards): void { $type = new ClasslikeType(ClasslikeName::fromFullyQualified('Fixtures\Inheritance\ParentClass')); $from = ClasslikeName::fromFullyQualified('Fixtures\Inheritance\ChildClass'); - $target = new MemberTarget($type, $from, $from); + $target = new MemberTarget($type, $from, $kind); self::assertSame($type, $target->type, 'what the member is looked up on'); self::assertSame($from, $target->from, 'where the access is written'); - self::assertSame($from, $target->static, 'what static names'); + self::assertSame($kind, $target->kind, 'how the access is written'); + self::assertSame($forwards ? $from : null, $target->static(), 'what static names'); } } diff --git a/tests/Resolution/Position/ExpectedAtPositionTest.php b/tests/Resolution/Position/ExpectedAtPositionTest.php index 964083c8..25cc77f4 100644 --- a/tests/Resolution/Position/ExpectedAtPositionTest.php +++ b/tests/Resolution/Position/ExpectedAtPositionTest.php @@ -29,6 +29,8 @@ use Firehed\PhpLsp\Resolution\Expected; use Firehed\PhpLsp\Resolution\ExpressionResolver; use Firehed\PhpLsp\Resolution\MemberAccessContext; +use Firehed\PhpLsp\Resolution\MemberAccessKind; +use Firehed\PhpLsp\Resolution\MemberTarget; use Firehed\PhpLsp\Resolution\Position\CallAtPositionInterface; use Firehed\PhpLsp\Resolution\Position\ExpectedAtPosition; use Firehed\PhpLsp\Resolution\Position\PositionLocator; @@ -313,7 +315,7 @@ public function testAClassImportedBesideAFunctionOfTheSameNameIsTheReceiver(): v { $result = $this->membersAtMarker('src/IncompleteCode/AliasedImports.php', 'colliding_static'); self::assertNotNull($result, 'the access resolves'); - self::assertSame('Fixtures\Namespacing\Models\Widget', $result->type->format()); + self::assertSame('Fixtures\Namespacing\Models\Widget', $result->target->type->format()); } /** @@ -375,7 +377,7 @@ public function testANamedReceiverResolvesAsWrittenWhereItIsWritten( ): void { self::assertSame( $class, - $this->membersAt($fixture, $line, $character)?->type->format(), + $this->membersAt($fixture, $line, $character)?->target->type->format(), 'the name resolves through the namespace and imports in effect', ); } @@ -387,7 +389,7 @@ public function testAPrefixPastAMultibyteCharacterIsWhatIsWritten(): void $result = $this->membersAt('TopLevel/multibyte_static.php', $line, $character); self::assertNotNull($result, 'the access resolves'); - self::assertSame('Fixtures\\Domain\\User', $result->type->format()); + self::assertSame('Fixtures\\Domain\\User', $result->target->type->format()); self::assertSame('fromArray', $result->prefix, 'the position is converted to bytes once'); } @@ -584,7 +586,7 @@ public static function cursorInsideNameCases(): iterable yield 'instance property' => [ 'before_instance_property', '$this->la', - MemberAccessContext::forInstance($subject, self::className($class), 'la'), + self::instance($subject, $class, 'la'), ]; yield 'static property, whose name omits its `$`' => [ 'before_static_property', @@ -753,9 +755,9 @@ static function (MethodName $method, string $parameter) use ($methodAccess): ?Ty /** * @param ?string $from The class-like the access is written in */ - private static function instance(TypeInterface $type, ?string $from): MemberAccessContext + private static function instance(TypeInterface $type, ?string $from, string $prefix = ''): MemberAccessContext { - return MemberAccessContext::forInstance($type, $from === null ? null : self::className($from), ''); + return self::access($type, $from, MemberAccessKind::Instance, $prefix); } /** @@ -763,15 +765,24 @@ private static function instance(TypeInterface $type, ?string $from): MemberAcce */ private static function static(TypeInterface $type, ?string $from, string $prefix = ''): MemberAccessContext { - return MemberAccessContext::forStatic($type, $from === null ? null : self::className($from), $prefix); + return self::access($type, $from, MemberAccessKind::Static, $prefix); } - /** - * A `parent::` access written in $from, which `static` names. - */ private static function parent(TypeInterface $type, string $from, string $prefix = ''): MemberAccessContext { - return MemberAccessContext::forParent($type, self::className($from), self::className($from), $prefix); + return self::access($type, $from, MemberAccessKind::Parent, $prefix); + } + + private static function access( + TypeInterface $type, + ?string $from, + MemberAccessKind $kind, + string $prefix, + ): MemberAccessContext { + return new MemberAccessContext( + new MemberTarget($type, $from === null ? null : self::className($from), $kind), + $prefix, + ); } private static function className(string $fqn): ClasslikeName diff --git a/tests/Resolution/Position/LocatedTest.php b/tests/Resolution/Position/LocatedTest.php index e852559a..cac5d429 100644 --- a/tests/Resolution/Position/LocatedTest.php +++ b/tests/Resolution/Position/LocatedTest.php @@ -7,11 +7,13 @@ use Firehed\PhpLsp\Document\TextDocument; use Firehed\PhpLsp\Domain\ByteOffset; use Firehed\PhpLsp\Parser\ParsedDocument; +use Firehed\PhpLsp\Resolution\MemberAccess; use Firehed\PhpLsp\Resolution\Position\CallSite; use Firehed\PhpLsp\Resolution\Position\Located; use Firehed\PhpLsp\Resolution\Position\Slot; use Firehed\PhpLsp\Resolution\Scope; use PhpParser\Node\Expr\FuncCall; +use PhpParser\Node\Expr\PropertyFetch; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Name; use PHPUnit\Framework\Attributes\CoversClass; @@ -25,21 +27,21 @@ public function testConstruction(): void $parsed = new ParsedDocument(new TextDocument('file:///t.php', 'php', 1, 'parsed, $located->offset, $located->slot, $located->prefix, $located->written, - $located->receiver, + $located->access, $located->scope, $located->call, ], diff --git a/tests/Resolution/Position/PositionLocatorTest.php b/tests/Resolution/Position/PositionLocatorTest.php index c1378e9f..f037cf00 100644 --- a/tests/Resolution/Position/PositionLocatorTest.php +++ b/tests/Resolution/Position/PositionLocatorTest.php @@ -34,8 +34,8 @@ public static function positions(): iterable yield 'a member not typed' => [$c . 'MethodAccess.php', 'this_empty', Slot::Member, '', false]; yield 'a member being typed' => [$c . 'MethodAccess.php', 'this_prefix', Slot::Member, 'get', false]; yield 'a member of a call' => [$c . 'MethodAccess.php', 'chain_on_string', Slot::Member, '', false]; - yield 'a static member' => [$c . 'StaticAccess.php', 'self_prefix', Slot::StaticMember, 'get', false]; - yield 'an enum case' => [$c . 'EnumUsage.php', 'unit_enum_prefix', Slot::StaticMember, 'A', false]; + yield 'a static member' => [$c . 'StaticAccess.php', 'self_prefix', Slot::Member, 'get', false]; + yield 'an enum case' => [$c . 'EnumUsage.php', 'unit_enum_prefix', Slot::Member, 'A', false]; yield 'a second caught type' => [$c . 'MultiCatchCompletion.php', 'catch_multi', Slot::Catch, '', false]; yield 'an implements list' => [ $c . 'ImplementsCompletion.php', 'implements_empty', Slot::Implements, '', false, @@ -129,7 +129,7 @@ public static function positions(): iterable $c . 'NextLineParsedOnto.php', 'this_before_statement', Slot::Member, '', false, ]; yield 'a static member with the next statement parsed onto it' => [ - 'TopLevel/static_before_statement.php', 'static_before_statement', Slot::StaticMember, '', false, + 'TopLevel/static_before_statement.php', 'static_before_statement', Slot::Member, '', false, ]; yield 'a nullsafe member in a for' => [ 'src/IncompleteCode/InControlStructures.php', 'nullsafe_access_for', Slot::Member, '', false, diff --git a/tests/Resolution/Position/SymbolAtPositionTest.php b/tests/Resolution/Position/SymbolAtPositionTest.php index 04b3d317..56e70537 100644 --- a/tests/Resolution/Position/SymbolAtPositionTest.php +++ b/tests/Resolution/Position/SymbolAtPositionTest.php @@ -11,10 +11,16 @@ use Firehed\PhpLsp\Domain\ResolvedCallableInterface; use Firehed\PhpLsp\Domain\ResolvedSymbolInterface; use Firehed\PhpLsp\Knowledge\SymbolSourceInterface; +use Firehed\PhpLsp\Parser\ParsedDocument; use Firehed\PhpLsp\Resolution\ExpressionResolverInterface; +use Firehed\PhpLsp\Resolution\MemberAccess; +use Firehed\PhpLsp\Resolution\Position\Located; use Firehed\PhpLsp\Resolution\Position\PositionLocator; +use Firehed\PhpLsp\Resolution\Position\PositionLocatorInterface; +use Firehed\PhpLsp\Resolution\Position\Slot; use Firehed\PhpLsp\Resolution\Position\SymbolAtPosition; use Firehed\PhpLsp\Resolution\ResolvedVariable; +use Firehed\PhpLsp\Resolution\Scope; use Firehed\PhpLsp\Tests\BuildsSymbolInfoTrait; use Firehed\PhpLsp\Tests\LoadsFixturesTrait; use Firehed\PhpLsp\Tests\Parser\ProductionSyntaxSource; @@ -146,6 +152,47 @@ public function testNothingResolvesAtAPositionWithoutASymbol( ); } + /** + * @return iterable + */ + public static function namesNotWritten(): iterable + { + yield 'a member name' => [ + Slot::Member, + MemberAccess::of(new Expr\PropertyFetch(new Expr\Variable('user'), 'name')), + ]; + yield 'a called name' => [Slot::CalledName, null]; + } + + /** + * A slot whose word is not written yet holds nothing to resolve. + */ + #[DataProvider('namesNotWritten')] + public function testNothingResolvesForANameNotWritten(Slot $slot, ?MemberAccess $access): void + { + $document = new TextDocument('file:///t.php', 'php', 1, 'method('locate')->willReturn(new Located( + new ParsedDocument($document, []), + $offset, + $slot, + '', + null, + $access, + Scope::at(null, []), + null, + )); + $expressions = $this->createMock(ExpressionResolverInterface::class); + $expressions->expects(self::never())->method('resolve'); + + self::assertNull( + (new SymbolAtPosition($locator, $expressions, self::createStub(SymbolSourceInterface::class))) + ->symbolAt($document, $offset), + 'no word is written to name a symbol', + ); + } + public function testParentNamesTheExtendedClass(): void { $base = self::classInfo('Fixtures\LateBinding\Base'); diff --git a/tests/Resolution/ScopeTest.php b/tests/Resolution/ScopeTest.php index f2bb75f5..05cac651 100644 --- a/tests/Resolution/ScopeTest.php +++ b/tests/Resolution/ScopeTest.php @@ -485,35 +485,6 @@ public function testTheLateBindingNamesTheEnclosingClass( ); } - /** - * @return array - */ - public static function forwardedStatics(): array - { - return [ - 'parent:: passes on the class written in' => ['parent', 'Fixtures\TypeInference\NewKeywords'], - 'self:: is the class looked up anyway' => ['self', null], - 'a named class' => ['Fixtures\Inheritance\ParentClass', null], - ]; - } - - /** - * A `parent::` access forwards late static binding (PHP manual, Late - * Static Bindings), so `static` names the class the access is written in. - */ - #[DataProvider('forwardedStatics')] - public function testOnlyAParentAccessPassesOnTheClassItIsWrittenIn(string $receiver, ?string $expected): void - { - $ast = self::parseWithParents($this->loadFixture('src/TypeInference/NewKeywords.php')); - $node = self::findFirst(Node\Name::class, $ast, fn ($n) => $n->toString() === $receiver); - - self::assertSame( - $expected, - Scope::at($node, $ast)->staticFor($node)?->qualifiedName->fullyQualifiedName(), - "static for a member on {$receiver}", - ); - } - private static function className(string $fullyQualifiedName): ClasslikeName { return ClasslikeName::fromFullyQualified($fullyQualifiedName); diff --git a/tests/Resolution/ThisTypingParityTest.php b/tests/Resolution/ThisTypingParityTest.php index 225765bf..46939327 100644 --- a/tests/Resolution/ThisTypingParityTest.php +++ b/tests/Resolution/ThisTypingParityTest.php @@ -98,17 +98,17 @@ public function testHoverAndCompletionAgreeOnThisReceiverType( self::assertSame( $hover->getType()?->format(), - $access->type->format(), + $access->target->type->format(), 'hover on $this and completion on $this-> must resolve to the same enclosing class', ); self::assertSame( $expectedClass, - $access->type->format(), + $access->target->type->format(), 'the shared helper resolves the enclosing class in the fixture', ); self::assertSame( $expectedClass, - $access->from?->qualifiedName->fullyQualifiedName(), + $access->target->from?->qualifiedName->fullyQualifiedName(), 'the access is written in the enclosing class, so `$this->` reaches its private members', ); }