Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/Resolution/ExpressionResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Firehed\PhpLsp\Domain\MethodInfo;
use Firehed\PhpLsp\Domain\NameKind;
use Firehed\PhpLsp\Domain\ParameterInfo;
use Firehed\PhpLsp\Domain\PrimitiveType;
use Firehed\PhpLsp\Domain\ResolvedCallableInterface;
use Firehed\PhpLsp\Domain\ResolvedSymbolInterface;
use Firehed\PhpLsp\Domain\TypeInterface;
Expand All @@ -42,6 +43,7 @@
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Param;
use PhpParser\Node\Scalar;
use PhpParser\Node\Stmt;
use PhpParser\PrettyPrinter\Standard as PrettyPrinter;

Expand Down Expand Up @@ -83,6 +85,11 @@ public function resolve(Expr $expr, ParsedDocument $parsed): ?ResolvedSymbolInte
return $this->resolveFuncCall($expr, $parsed);
}

$literal = self::literalType($expr);
if ($literal !== null) {
return new ResolvedTypeOnly($literal);
}

if ($expr instanceof Expr\ConstFetch) {
return $this->resolveConstFetch($expr, $parsed);
}
Expand Down Expand Up @@ -363,6 +370,30 @@ private function resolveConstFetch(Expr\ConstFetch $expr, ParsedDocument $parsed
return null;
}

/**
* PHP reads `true`, `false`, and `null` as literals in any letter case, but
* only once aliases and namespaces are applied to the name: `B\true` and a
* `use const` alias named `true` are constants.
*/
private static function literalType(Expr $expr): ?PrimitiveType
{
return match (true) {
$expr instanceof Scalar\Int_, $expr instanceof Scalar\MagicConst\Line => PrimitiveType::Int,
$expr instanceof Scalar\Float_ => PrimitiveType::Float,
$expr instanceof Scalar\String_,
$expr instanceof Scalar\InterpolatedString,
$expr instanceof Scalar\MagicConst => PrimitiveType::String,
$expr instanceof Expr\ConstFetch => self::literalConstant($expr->name),
default => null,
};
}

private static function literalConstant(Name $name): ?PrimitiveType
{
$type = PrimitiveType::tryFromName($name->toString());
return in_array($type, [PrimitiveType::True, PrimitiveType::False, PrimitiveType::Null], true) ? $type : null;
}

private static function locationFor(Node $node, TextDocument $document): Location
{
$start = $document->positionAt($node->getStartFilePos());
Expand Down
4 changes: 2 additions & 2 deletions src/Resolution/ResolvedTypeOnly.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@

/**
* A ResolvedSymbolInterface that carries only a type — used when an expression's value
* type is known but there is no persistent symbol to point at: a `new` of a
* class nothing declares.
* type is known but there is no persistent symbol to point at: a literal, or a
* `new` of a class nothing declares.
*
* @internal
*/
Expand Down
22 changes: 22 additions & 0 deletions tests/EndToEnd/defects/896-null-first-ternary.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Firehed\PhpLsp\Tests\EndToEnd;

// `$c ? null : new User()` is `?User` in PHP; the server takes only the first branch.
$user = 'src/Domain/User.php';

return [
'a member of the object a ternary produces after null' => new Session\Script(
project: 'tests/Fixtures',
steps: [
new Step\Open($user),
new Step\Definition(
$user,
new Marker\SymbolMarker('null_first_ternary'),
expect: new Expectation\LandsOn($user, line: 48),
),
],
),
];
18 changes: 18 additions & 0 deletions tests/Fixtures/Namespacing/LiteralNames.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace Fixtures\Namespacing\Shadowed {
const BAR = 5;
}

namespace Fixtures\Namespacing\LiteralNames {
use const Fixtures\Namespacing\Shadowed\BAR as true;

$aliased = true;
$aliased; //jtd:aliased aliased
$otherCase = TRUE;
$otherCase; //jtd:other_case otherCase
$qualified = Sub\false;
$qualified; //jtd:qualified qualified
}
6 changes: 6 additions & 0 deletions tests/Fixtures/src/Domain/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -335,4 +335,10 @@ public function triggerHoverUndefinedConstant(): void
{
echo TOTALLY_UNDEFINED_CONSTANT; //hover:undefined_constant
}

public static function triggerDefNullFirstTernary(): void
{
$user = rand() ? null : new User('1', 'name', 'email');
$user?->setName('new'); //hover:null_first_ternary
}
}
49 changes: 49 additions & 0 deletions tests/Fixtures/src/TypeInference/Literals.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

namespace Fixtures\TypeInference;

class Literals
{
public function assignments(string $name): void
{
$decimal = 1_000;
$decimal; //jtd:decimal decimal
$hex = 0x1F;
$hex; //jtd:hex hex
$overflow = 9223372036854775808;
$overflow; //jtd:overflow overflow
$float = 1.5;
$float; //jtd:float float
$single = 'single';
$single; //jtd:single single
$interpolated = "hello {$name}";
$interpolated; //jtd:interpolated interpolated
$heredoc = <<<EOT
hello {$name}
EOT;
$heredoc; //jtd:heredoc heredoc
$nowdoc = <<<'EOT'
hello
EOT;
$nowdoc; //jtd:nowdoc nowdoc
$line = __LINE__;
$line; //jtd:line line
$class = __CLASS__;
$class; //jtd:class class
$true = true;
$true; //jtd:true true
$false = False;
$false; //jtd:false false
$null = NULL;
$null; //jtd:null null
$qualifiedTrue = \true;
$qualifiedTrue; //jtd:qualified_true qualifiedTrue
}

public function hoverOnTrue(): void
{
echo TRUE; //hover:upper_true
}
}
76 changes: 75 additions & 1 deletion tests/Resolution/ExpressionResolutionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ final class ExpressionResolutionTest extends TestCase

private const string FOREACH = 'src/Hover/ForeachElement.php';

private const string LITERALS = 'src/TypeInference/Literals.php';

private const string LITERAL_NAMES = 'Namespacing/LiteralNames.php';

private const string TOP_LEVEL = 'TopLevel/top_level_closures.php';

private const string SYMBOLS = 'src/Position/Symbols.php';
Expand All @@ -90,7 +94,7 @@ protected function setUp(): void
public function testArrowFunctionResolvesThroughToItsEnclosingFunction(): void
{
self::assertEquals(
new ResolvedVariable('outer', null, self::bindingAt(self::BINDINGS, 72, 8)),
new ResolvedVariable('outer', PrimitiveType::Int, self::bindingAt(self::BINDINGS, 72, 8)),
$this->resolveVariableAt(self::BINDINGS, 'arrow_fallthrough'),
'an arrow function captures an unbound name from the enclosing function',
);
Expand Down Expand Up @@ -224,6 +228,76 @@ public function testNullCoalesceTakesItsLeftSide(): void
);
}

/**
* @return iterable<string, array{string, PrimitiveType}>
*/
public static function literals(): iterable
{
yield 'decimal int' => ['decimal', PrimitiveType::Int];
yield 'hexadecimal int' => ['hex', PrimitiveType::Int];
yield 'int too large for int' => ['overflow', PrimitiveType::Float];
yield 'float' => ['float', PrimitiveType::Float];
yield 'single-quoted string' => ['single', PrimitiveType::String];
yield 'interpolated string' => ['interpolated', PrimitiveType::String];
yield 'heredoc' => ['heredoc', PrimitiveType::String];
yield 'nowdoc' => ['nowdoc', PrimitiveType::String];
yield '__LINE__' => ['line', PrimitiveType::Int];
yield '__CLASS__' => ['class', PrimitiveType::String];
yield 'true' => ['true', PrimitiveType::True];
yield 'false in mixed case' => ['false', PrimitiveType::False];
yield 'null in upper case' => ['null', PrimitiveType::Null];
yield 'fully qualified true' => ['qualified_true', PrimitiveType::True];
}

#[DataProvider('literals')]
public function testAVariableAssignedALiteralTakesTheLiteralsType(string $marker, PrimitiveType $expected): void
{
self::assertSame(
$expected,
$this->resolveVariableAt(self::LITERALS, $marker)?->getType(),
'a literal has the narrowest type naming its value',
);
}

public function testTrueIsALiteralEvenWhereAConstantNamesIt(): void
{
$symbols = self::createStub(SymbolSourceInterface::class);
$symbols->method('lookupConstant')->willReturnCallback(
static fn (ConstantName $name): ConstantInfo => self::constantInfo($name->qualifiedName),
);
$this->resolver = self::resolverOver(
$symbols,
self::createStub(TypeSourceInterface::class),
self::createStub(MemberResolverInterface::class),
);

self::assertSame(
PrimitiveType::True,
$this->resolveSymbolAt(self::LITERALS, 'upper_true')?->getType(),
'PHP reads TRUE as a literal before looking up any constant',
);
}

/**
* @return iterable<string, array{string, ?PrimitiveType}>
*/
public static function literalNames(): iterable
{
yield 'true imported as a constant alias' => ['aliased', null];
yield 'TRUE, which the case-sensitive alias does not match' => ['other_case', PrimitiveType::True];
yield 'qualified name ending in false' => ['qualified', null];
}

#[DataProvider('literalNames')]
public function testOnlyANameResolvingToTrueFalseOrNullIsALiteral(string $marker, ?PrimitiveType $expected): void
{
self::assertSame(
$expected,
$this->resolveVariableAt(self::LITERAL_NAMES, $marker)?->getType(),
'true, false, and null are literals only where no alias or namespace makes them name a constant',
);
}

public function testThisIsTheEnclosingClass(): void
{
self::assertEquals(
Expand Down
Loading