33namespace PHPStan \Parser ;
44
55use PhpParser \Node ;
6+ use PhpParser \Token ;
67use PHPStan \File \FileReader ;
78use function array_slice ;
89
@@ -12,6 +13,11 @@ final class CachedParser implements Parser
1213 /** @var array<string, Node\Stmt[]>*/
1314 private array $ cachedNodesByString = [];
1415
16+ /** @var array<string, Token[]>*/
17+ private array $ cachedTokensByString = [];
18+
19+ private ?string $ lastParsedSourceCode ;
20+
1521 private int $ cachedNodesByStringCount = 0 ;
1622
1723 /** @var array<string, true> */
@@ -36,17 +42,24 @@ public function parseFile(string $file): array
3642 1 ,
3743 preserve_keys: true ,
3844 );
45+ $ this ->cachedTokensByString = array_slice (
46+ $ this ->cachedTokensByString ,
47+ 1 ,
48+ preserve_keys: true ,
49+ );
3950
4051 --$ this ->cachedNodesByStringCount ;
4152 }
4253
4354 $ sourceCode = FileReader::read ($ file );
4455 if (!isset ($ this ->cachedNodesByString [$ sourceCode ]) || isset ($ this ->parsedByString [$ sourceCode ])) {
4556 $ this ->cachedNodesByString [$ sourceCode ] = $ this ->originalParser ->parseFile ($ file );
57+ $ this ->cachedTokensByString [$ sourceCode ] = $ this ->originalParser ->getTokens ();
4658 $ this ->cachedNodesByStringCount ++;
4759 unset($ this ->parsedByString [$ sourceCode ]);
4860 }
4961
62+ $ this ->lastParsedSourceCode = $ sourceCode ;
5063 return $ this ->cachedNodesByString [$ sourceCode ];
5164 }
5265
@@ -61,19 +74,34 @@ public function parseString(string $sourceCode): array
6174 1 ,
6275 preserve_keys: true ,
6376 );
77+ $ this ->cachedTokensByString = array_slice (
78+ $ this ->cachedTokensByString ,
79+ 1 ,
80+ preserve_keys: true ,
81+ );
6482
6583 --$ this ->cachedNodesByStringCount ;
6684 }
6785
6886 if (!isset ($ this ->cachedNodesByString [$ sourceCode ])) {
6987 $ this ->cachedNodesByString [$ sourceCode ] = $ this ->originalParser ->parseString ($ sourceCode );
88+ $ this ->cachedTokensByString [$ sourceCode ] = $ this ->originalParser ->getTokens ();
7089 $ this ->cachedNodesByStringCount ++;
7190 $ this ->parsedByString [$ sourceCode ] = true ;
7291 }
7392
93+ $ this ->lastParsedSourceCode = $ sourceCode ;
7494 return $ this ->cachedNodesByString [$ sourceCode ];
7595 }
7696
97+ public function getTokens (): array
98+ {
99+ if (isset ($ this ->cachedTokensByString [$ this ->lastParsedSourceCode ])) {
100+ return $ this ->cachedTokensByString [$ this ->lastParsedSourceCode ];
101+ }
102+ return [];
103+ }
104+
77105 public function getCachedNodesByStringCount (): int
78106 {
79107 return $ this ->cachedNodesByStringCount ;
0 commit comments