Skip to content

Commit

Permalink
Missing attributes for array shapes
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Apr 24, 2023
1 parent 3416dc6 commit cff97e9
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 3 deletions.
26 changes: 23 additions & 3 deletions src/Parser/TypeParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,8 @@ private function parseArrayShape(TokenIterator $tokens, Ast\Type\TypeNode $type,
/** @phpstan-impure */
private function parseArrayShapeItem(TokenIterator $tokens): Ast\Type\ArrayShapeItemNode
{
$startLine = $tokens->currentTokenLine();
$startIndex = $tokens->currentTokenIndex();
try {
$tokens->pushSavePoint();
$key = $this->parseArrayShapeKey($tokens);
Expand All @@ -619,12 +621,22 @@ private function parseArrayShapeItem(TokenIterator $tokens): Ast\Type\ArrayShape
$value = $this->parse($tokens);
$tokens->dropSavePoint();

return new Ast\Type\ArrayShapeItemNode($key, $optional, $value);
return $this->enrichWithAttributes(
$tokens,
new Ast\Type\ArrayShapeItemNode($key, $optional, $value),
$startLine,
$startIndex
);
} catch (ParserException $e) {
$tokens->rollback();
$value = $this->parse($tokens);

return new Ast\Type\ArrayShapeItemNode(null, false, $value);
return $this->enrichWithAttributes(
$tokens,
new Ast\Type\ArrayShapeItemNode(null, false, $value),
$startLine,
$startIndex
);
}
}

Expand All @@ -634,6 +646,9 @@ private function parseArrayShapeItem(TokenIterator $tokens): Ast\Type\ArrayShape
*/
private function parseArrayShapeKey(TokenIterator $tokens)
{
$startIndex = $tokens->currentTokenIndex();
$startLine = $tokens->currentTokenLine();

if ($tokens->isCurrentTokenType(Lexer::TOKEN_INTEGER)) {
$key = new Ast\ConstExpr\ConstExprIntegerNode($tokens->currentTokenValue());
$tokens->next();
Expand All @@ -660,7 +675,12 @@ private function parseArrayShapeKey(TokenIterator $tokens)
$tokens->consumeTokenType(Lexer::TOKEN_IDENTIFIER);
}

return $key;
return $this->enrichWithAttributes(
$tokens,
$key,
$startLine,
$startIndex
);
}

/**
Expand Down
42 changes: 42 additions & 0 deletions tests/PHPStan/Parser/TypeParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2069,6 +2069,48 @@ static function (TypeNode $typeNode): TypeNode {
],
],
];

yield [
'array{foo: int}',
[
[
static function (TypeNode $typeNode): TypeNode {
return $typeNode;
},
'array{foo: int}',
1,
1,
0,
6,
],
[
static function (ArrayShapeNode $typeNode): TypeNode {
return $typeNode->items[0];
},
'foo: int',
1,
1,
2,
5,
],
],
];

yield [
'array{}',
[
[
static function (TypeNode $typeNode): TypeNode {
return $typeNode;
},
'array{}',
1,
1,
0,
2,
],
],
];
}

/**
Expand Down

0 comments on commit cff97e9

Please sign in to comment.