Skip to content

Commit a2f5214

Browse files
committed
Generate the lexer pattern from doc/grammars/lexemes.pp3
Lexer::tokenize() now classifies the tokens for the generated parser while lexing, so the parsers no longer rebuild the stream on every read. Amp-Thread-ID: https://ampcode.com/threads/T-01a17820-94d1-75c8-9206-2e802d9c0556
1 parent 8073569 commit a2f5214

9 files changed

Lines changed: 424 additions & 235 deletions

File tree

‎doc/grammars/README.md‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -125,16 +125,19 @@ most of them:
125125
- **A rule reads exactly the tokens its method reads**, down to the line breaks
126126
around it.
127127

128-
### The tokens are not read by phplrt
129-
130-
A grammar of this directory is not read by the lexer it declares: it is read by
131-
the very tokens `PHPStan\PhpDocParser\Lexer\Lexer` produces, handed over by
132-
`tools/phplrt/Fuzzer/TokenStream.php`.
133-
134-
The `%token` declarations therefore name the tokens and document the language
135-
without being what reads it. Some of them describe something the lexer never
136-
reads as a token of its own, and `TokenStream` is what tells those apart in the
137-
stream:
128+
### The lexer is written out of the `%token` declarations
129+
130+
`tools/phplrt/build.php` writes the pattern of `PHPStan\PhpDocParser\Lexer\Lexer`
131+
out of the `%token` declarations of `lexemes.pp3`, in the order they are
132+
declared, into `GeneratedParser::LEXER_PATTERN`. Each token is marked by the
133+
identifier the grammar gives it, and `GeneratedParser::LEXER_TYPES` maps it back
134+
to the `Lexer::TOKEN_*` type `tokenize()` returns, so the tokens are the very
135+
ones they always were.
136+
137+
Some declarations describe something the lexer never reads as a token of its
138+
own. They are left out of the pattern, and `src/Parser/Phplrt/TokenStream.php`
139+
tells them apart in the stream the parser reads, while the PHPDoc is being
140+
lexed:
138141

139142
- a word the parser compares by value (`is`, `array`, `covariant`, `static`, …)
140143
— every one of them is still an ordinary name as well, which is why they are

‎doc/grammars/lexemes.pp3‎

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,25 @@
33
* The Lexemes Of The PHPDoc Language
44
* -----------------------------------------------------------------------------
55
*
6-
* Every token the PHPDoc language is read into, written the way
7-
* "PHPStan\PhpDocParser\Lexer\Lexer" reads it.
6+
* Every token the PHPDoc language is read into.
87
*
9-
* A grammar of this directory is not read by the lexer it declares: it is read
10-
* by the very tokens "Lexer" produces, handed over by
11-
* "tools/phplrt/Fuzzer/TokenStream.php". The declarations below therefore
12-
* serve three purposes:
8+
* "PHPStan\PhpDocParser\Lexer\Lexer" is written out of these declarations by
9+
* "tools/phplrt/build.php": every token that is not classified below becomes
10+
* an alternative of its pattern, tried in the order written here, so the
11+
* order is the one that decides between two tokens matching at one place.
12+
* The declarations also serve the grammar-driven fuzzer, which writes its
13+
* inputs out of them.
1314
*
14-
* - they name the tokens the rules are written in terms of;
15-
* - they document the language down to its lexical level;
16-
* - they are what the grammar-driven fuzzer writes its inputs from.
15+
* Every group of a pattern is non-capturing: "preg_match_all()" collects
16+
* every capturing group for every token the lexer reads.
1717
*
18-
* A block of tokens marked "classified" is not read as a token of its own by
19-
* the lexer. Such a token is a T_IDENTIFIER (or a bracket, or an asterisk)
20-
* whose surroundings or whose very value the hand-written parser asks about,
21-
* and telling those apart in the token stream is what lets a grammar written
22-
* without semantic predicates say the same thing.
18+
* A classified token is not an alternative of the pattern: the keywords, the
19+
* tags read by a rule of their own, the tokens ending in "_WS" and the "<" of
20+
* an HTML tag. Such a token is a T_IDENTIFIER (or a tag, a bracket, or an
21+
* asterisk) whose surroundings or whose very value the grammar asks about.
22+
* The lexer reads it as that token, and tells it apart only in the stream it
23+
* hands to the parser ("src/Parser/Phplrt/TokenStream.php"), which is what
24+
* lets a grammar written without semantic predicates say the same thing.
2325
*/
2426

2527
%pragma lexer.pcre.disable u
@@ -79,8 +81,8 @@
7981
// Literals and names
8082
// -----------------------------------------------------------------------------
8183

82-
%token T_FLOAT [+\-]?(?:(?:[0-9]++(_[0-9]++)*\.[0-9]*+(_[0-9]++)*(?:e[+\-]?[0-9]++(_[0-9]++)*)?)|(?:[0-9]*+(_[0-9]++)*\.[0-9]++(_[0-9]++)*(?:e[+\-]?[0-9]++(_[0-9]++)*)?)|(?:[0-9]++(_[0-9]++)*e[+\-]?[0-9]++(_[0-9]++)*))
83-
%token T_INTEGER [+\-]?(?:(?:0b[0-1]++(_[0-1]++)*)|(?:0o[0-7]++(_[0-7]++)*)|(?:0x[0-9a-f]++(_[0-9a-f]++)*)|(?:[0-9]++(_[0-9]++)*))
84+
%token T_FLOAT [+\-]?(?:(?:[0-9]++(?:_[0-9]++)*\.[0-9]*+(?:_[0-9]++)*(?:e[+\-]?[0-9]++(?:_[0-9]++)*)?)|(?:[0-9]*+(?:_[0-9]++)*\.[0-9]++(?:_[0-9]++)*(?:e[+\-]?[0-9]++(?:_[0-9]++)*)?)|(?:[0-9]++(?:_[0-9]++)*e[+\-]?[0-9]++(?:_[0-9]++)*))
85+
%token T_INTEGER [+\-]?(?:(?:0b[0-1]++(?:_[0-1]++)*)|(?:0o[0-7]++(?:_[0-7]++)*)|(?:0x[0-9a-f]++(?:_[0-9a-f]++)*)|(?:[0-9]++(?:_[0-9]++)*))
8486
%token T_SINGLE_QUOTED_STRING '(?:\\[^\r\n]|[^'\r\n\\])*+'
8587
%token T_DOUBLE_QUOTED_STRING "(?:\\[^\r\n]|[^"\r\n\\])*+"
8688
%token T_DOCTRINE_ANNOTATION_STRING "(?:""|[^"])*+"
@@ -120,14 +122,14 @@
120122
%token T_ARROW ->
121123
%token T_EQUAL =
122124
%token T_COLON :
123-
%token T_WILDCARD \*
124125

125126
// -----------------------------------------------------------------------------
126127
// PHPDoc structure
127128
// -----------------------------------------------------------------------------
128129

129130
%token T_OPEN_PHPDOC /\*\*(?=\s)\x20?+
130131
%token T_CLOSE_PHPDOC \*/
132+
%token T_WILDCARD \*
131133

132134
/**
133135
* The tags whose value is read by a rule of its own, told apart from one

‎src/Lexer/Lexer.php‎

Lines changed: 11 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@
22

33
namespace PHPStan\PhpDocParser\Lexer;
44

5+
use PHPStan\PhpDocParser\Parser\Phplrt\TokenStream;
56
use PHPStan\PhpDocParser\ParserConfig;
6-
use function implode;
7-
use function preg_match_all;
87

98
/**
109
* Implementation based on Nette Tokenizer (New BSD License; https://github.com/nette/tokenizer)
10+
*
11+
* The pattern is written out of "doc/grammars/lexemes.pp3" by "tools/phplrt/build.php".
1112
*/
1213
class Lexer
1314
{
@@ -99,110 +100,23 @@ class Lexer
99100

100101
private ParserConfig $config; // @phpstan-ignore property.onlyWritten
101102

102-
private ?string $regexp = null;
103-
104103
public function __construct(ParserConfig $config)
105104
{
106105
$this->config = $config;
107106
}
108107

109108
/**
110-
* @return list<array{string, int, int}>
109+
* The tokens of the pattern written out of "doc/grammars/lexemes.pp3",
110+
* ending with TOKEN_END.
111+
*
112+
* The last token carries what the parsers read along: keep the tokens
113+
* together when handing them over to a {@see TokenIterator}.
114+
*
115+
* @return list<array{0: string, 1: int, 2: int, 3?: array<int, int>, 4?: list<int>}>
111116
*/
112117
public function tokenize(string $s): array
113118
{
114-
if ($this->regexp === null) {
115-
$this->regexp = $this->generateRegexp();
116-
}
117-
118-
// PREG_PATTERN_ORDER, not PREG_SET_ORDER: it collects the whole PHPDoc
119-
// into two arrays instead of allocating one array per token. This only
120-
// pays off while the token patterns have no capturing groups, because
121-
// every group would get an array of its own, one entry per token.
122-
preg_match_all($this->regexp, $s, $matches);
123-
124-
$values = $matches[0];
125-
if ($values === []) {
126-
return [['', self::TOKEN_END, 1]];
127-
}
128-
129-
$marks = $matches['MARK'];
130-
131-
$tokens = [];
132-
$line = 1;
133-
foreach ($values as $i => $value) {
134-
$type = (int) $marks[$i];
135-
$tokens[] = [$value, $type, $line];
136-
if ($type !== self::TOKEN_PHPDOC_EOL) {
137-
continue;
138-
}
139-
140-
$line++;
141-
}
142-
143-
$tokens[] = ['', self::TOKEN_END, $line];
144-
145-
return $tokens;
146-
}
147-
148-
private function generateRegexp(): string
149-
{
150-
// every group in here must be non-capturing, see tokenize()
151-
$patterns = [
152-
self::TOKEN_HORIZONTAL_WS => '[\\x09\\x20]++',
153-
154-
self::TOKEN_IDENTIFIER => '(?:[\\\\]?+[a-z_\\x80-\\xFF][0-9a-z_\\x80-\\xFF-]*+)++',
155-
self::TOKEN_THIS_VARIABLE => '\\$this(?![0-9a-z_\\x80-\\xFF])',
156-
self::TOKEN_VARIABLE => '\\$[a-z_\\x80-\\xFF][0-9a-z_\\x80-\\xFF]*+',
157-
158-
// '&' followed by TOKEN_VARIADIC, TOKEN_VARIABLE, TOKEN_EQUAL, TOKEN_EQUAL or TOKEN_CLOSE_PARENTHESES
159-
self::TOKEN_REFERENCE => '&(?=\\s*+(?:[,=)]|\\.\\.\\.|(?:\\$(?!this(?![0-9a-z_\\x80-\\xFF])))))',
160-
self::TOKEN_UNION => '\\|',
161-
self::TOKEN_INTERSECTION => '&',
162-
self::TOKEN_NULLABLE => '\\?',
163-
self::TOKEN_NEGATED => '!',
164-
165-
self::TOKEN_OPEN_PARENTHESES => '\\(',
166-
self::TOKEN_CLOSE_PARENTHESES => '\\)',
167-
self::TOKEN_OPEN_ANGLE_BRACKET => '<',
168-
self::TOKEN_CLOSE_ANGLE_BRACKET => '>',
169-
self::TOKEN_OPEN_SQUARE_BRACKET => '\\[',
170-
self::TOKEN_CLOSE_SQUARE_BRACKET => '\\]',
171-
self::TOKEN_OPEN_CURLY_BRACKET => '\\{',
172-
self::TOKEN_CLOSE_CURLY_BRACKET => '\\}',
173-
174-
self::TOKEN_COMMA => ',',
175-
self::TOKEN_COMMENT => '\/\/[^\\r\\n]*(?=\n|\r|\*/)',
176-
self::TOKEN_VARIADIC => '\\.\\.\\.',
177-
self::TOKEN_DOUBLE_COLON => '::',
178-
self::TOKEN_DOUBLE_ARROW => '=>',
179-
self::TOKEN_ARROW => '->',
180-
self::TOKEN_EQUAL => '=',
181-
self::TOKEN_COLON => ':',
182-
183-
self::TOKEN_OPEN_PHPDOC => '/\\*\\*(?=\\s)\\x20?+',
184-
self::TOKEN_CLOSE_PHPDOC => '\\*/',
185-
self::TOKEN_PHPDOC_TAG => '@(?:[a-z][a-z0-9-\\\\]+:)?[a-z][a-z0-9-\\\\]*+',
186-
self::TOKEN_DOCTRINE_TAG => '@[a-z_\\\\][a-z0-9_\:\\\\]*[a-z_][a-z0-9_]*',
187-
self::TOKEN_PHPDOC_EOL => '\\r?+\\n[\\x09\\x20]*+(?:\\*(?!/)\\x20?+)?',
188-
189-
self::TOKEN_FLOAT => '[+\-]?(?:(?:[0-9]++(?:_[0-9]++)*\\.[0-9]*+(?:_[0-9]++)*(?:e[+\-]?[0-9]++(?:_[0-9]++)*)?)|(?:[0-9]*+(?:_[0-9]++)*\\.[0-9]++(?:_[0-9]++)*(?:e[+\-]?[0-9]++(?:_[0-9]++)*)?)|(?:[0-9]++(?:_[0-9]++)*e[+\-]?[0-9]++(?:_[0-9]++)*))',
190-
self::TOKEN_INTEGER => '[+\-]?(?:(?:0b[0-1]++(?:_[0-1]++)*)|(?:0o[0-7]++(?:_[0-7]++)*)|(?:0x[0-9a-f]++(?:_[0-9a-f]++)*)|(?:[0-9]++(?:_[0-9]++)*))',
191-
self::TOKEN_SINGLE_QUOTED_STRING => '\'(?:\\\\[^\\r\\n]|[^\'\\r\\n\\\\])*+\'',
192-
self::TOKEN_DOUBLE_QUOTED_STRING => '"(?:\\\\[^\\r\\n]|[^"\\r\\n\\\\])*+"',
193-
self::TOKEN_DOCTRINE_ANNOTATION_STRING => '"(?:""|[^"])*+"',
194-
195-
self::TOKEN_WILDCARD => '\\*',
196-
197-
// anything but TOKEN_CLOSE_PHPDOC or TOKEN_HORIZONTAL_WS or TOKEN_EOL
198-
self::TOKEN_OTHER => '(?:(?!\\*/)[^\\s])++',
199-
];
200-
201-
foreach ($patterns as $type => &$pattern) {
202-
$pattern = '(?:' . $pattern . ')(*MARK:' . $type . ')';
203-
}
204-
205-
return '~' . implode('|', $patterns) . '~Asi';
119+
return TokenStream::tokenize($s);
206120
}
207121

208122
}

‎src/Parser/AstBuilder.php‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -249,15 +249,27 @@ public function read(TokenIterator $tokens, string $rule, ?string $tag = null)
249249
$lexerTokens = $tokens->getTokens();
250250
$index = $tokens->currentTokenIndex();
251251

252-
$ids = [];
253-
$indexes = [];
254-
if ($tag !== null) {
255-
// the value of a tag is read along with the tag it belongs to
256-
$ids[] = TokenStream::tagId($tag);
257-
$indexes[] = $index - 1;
258-
}
252+
$stream = TokenStream::fromTokens($lexerTokens, $index);
253+
if ($stream !== null && $tag === null) {
254+
[$ids, $indexes] = $stream;
255+
} else {
256+
$ids = [];
257+
$indexes = [];
258+
if ($tag !== null) {
259+
// the value of a tag is read along with the tag it belongs to
260+
$ids[] = TokenStream::tagId($tag);
261+
$indexes[] = $index - 1;
262+
}
259263

260-
TokenStream::create($lexerTokens, $index, $ids, $indexes);
264+
if ($stream !== null) {
265+
foreach ($stream[0] as $position => $id) {
266+
$ids[] = $id;
267+
$indexes[] = $stream[1][$position];
268+
}
269+
} else {
270+
TokenStream::create($lexerTokens, $index, $ids, $indexes);
271+
}
272+
}
261273

262274
$previous = [$this->tokens, $this->ids, $this->indexes, $this->tag, $this->positions, $this->comments, $this->byteOffsets, $this->v, $this->n, $this->saveReading()];
263275

0 commit comments

Comments
 (0)