-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathATNConfigSet.php
More file actions
342 lines (282 loc) · 10.1 KB
/
ATNConfigSet.php
File metadata and controls
342 lines (282 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
<?php
declare(strict_types=1);
namespace Antlr\Antlr4\Runtime\Atn;
use Antlr\Antlr4\Runtime\Atn\SemanticContexts\SemanticContext;
use Antlr\Antlr4\Runtime\Comparison\Equality;
use Antlr\Antlr4\Runtime\Comparison\Equivalence;
use Antlr\Antlr4\Runtime\Comparison\Hashable;
use Antlr\Antlr4\Runtime\Comparison\Hasher;
use Antlr\Antlr4\Runtime\PredictionContexts\PredictionContext;
use Antlr\Antlr4\Runtime\Utils\BitSet;
use Antlr\Antlr4\Runtime\Utils\DoubleKeyMap;
use Antlr\Antlr4\Runtime\Utils\Set;
/**
* Specialized {@see Set} of `{@see ATNConfig}`s that can track info
* about the set, with support for combining similar configurations using
* a graph-structured stack.
*/
class ATNConfigSet implements Hashable
{
/**
* Indicates that the set of configurations is read-only. Do not
* allow any code to manipulate the set; DFA states will point at
* the sets and they must not change. This does not protect the other
* fields; in particular, conflictingAlts is set after
* we've made this readonly.
*/
protected bool $readOnly = false;
/**
* All configs but hashed by (s, i, _, pi) not including context. Wiped out
* when we go readonly as this set becomes a DFA state.
*/
public ?Set $configLookup = null;
/**
* Track the elements as they are added to the set; supports get(i).
*
* @var array<ATNConfig>
*/
public array $configs = [];
public int $uniqueAlt = 0;
/**
* Currently this is only used when we detect SLL conflict; this does
* not necessarily represent the ambiguous alternatives. In fact, I should
* also point out that this seems to include predicated alternatives that
* have predicates that evaluate to false. Computed in computeTargetState().
*/
protected ?BitSet $conflictingAlts = null;
/**
* Used in parser and lexer. In lexer, it indicates we hit a pred
* while computing a closure operation. Don't make a DFA state from this.
*/
public bool $hasSemanticContext = false;
public bool $dipsIntoOuterContext = false;
/**
* Indicates that this configuration set is part of a full context LL
* prediction. It will be used to determine how to merge $. With SLL it's
* a wildcard whereas it is not for LL context merge.
*/
public bool $fullCtx;
private ?int $cachedHashCode = null;
public function __construct(bool $fullCtx = true)
{
/*
* The reason that we need this is because we don't want the hash map to
* use the standard hash code and equals. We need all configurations with
* the same `(s,i,_,semctx)` to be equal. Unfortunately, this key
* effectively doubles the number of objects associated with ATNConfigs.
* The other solution is to use a hash table that lets us specify the
* equals/hashcode operation. All configs but hashed by (s, i, _, pi)
* not including context. Wiped out when we go readonly as this se
* becomes a DFA state.
*/
$this->configLookup = new Set(new ATNEquivalence());
$this->fullCtx = $fullCtx;
}
/**
* Adding a new config means merging contexts with existing configs for
* `(s, i, pi, _)`, where `s` is the {@see ATNConfig::$state}, `i` is the
* {@see ATNConfig::$alt}, and `pi` is the {@see ATNConfig::$semanticContext}.
* We use `(s,i,pi)` as key.
*
* This method updates {@see ATNConfigSet::$dipsIntoOuterContext} and
* {@see ATNConfigSet::$hasSemanticContext} when necessary.
*
* @throws \InvalidArgumentException
*/
public function add(ATNConfig $config, ?DoubleKeyMap $mergeCache = null): bool
{
if ($this->readOnly || $this->configLookup === null) {
throw new \InvalidArgumentException('This set is readonly.');
}
if ($config->semanticContext !== SemanticContext::none()) {
$this->hasSemanticContext = true;
}
if ($config->reachesIntoOuterContext > 0) {
$this->dipsIntoOuterContext = true;
}
/** @var ATNConfig $existing */
$existing = $this->configLookup->getOrAdd($config);
if ($existing->equals($config)) {
$this->cachedHashCode = null;
$this->configs[] = $config; // track order here
return true;
}
// A previous (s,i,pi,_), merge with it and save result
$rootIsWildcard = !$this->fullCtx;
if ($existing->context === null || $config->context === null) {
throw new \LogicException('Unexpected null context.');
}
$merged = PredictionContext::merge($existing->context, $config->context, $rootIsWildcard, $mergeCache);
// No need to check for existing->context, config->context in cache
// since only way to create new graphs is "call rule" and here. We
// cache at both places.
$existing->reachesIntoOuterContext = \max(
$existing->reachesIntoOuterContext,
$config->reachesIntoOuterContext,
);
// Make sure to preserve the precedence filter suppression during the merge
if ($config->isPrecedenceFilterSuppressed()) {
$existing->setPrecedenceFilterSuppressed(true);
}
// Replace context; no need to alt mapping
$existing->context = $merged;
return true;
}
/**
* Return a List holding list of configs.
*
* @return array<ATNConfig>
*/
public function elements(): array
{
return $this->configs;
}
public function getStates(): Set
{
$states = new Set();
foreach ($this->configs as $config) {
$states->add($config->state);
}
return $states;
}
/**
* Gets the complete set of represented alternatives for the configurationc set.
*
* @return BitSet The set of represented alternatives in this configuration set.
*/
public function getAlts(): BitSet
{
$alts = new BitSet();
foreach ($this->configs as $config) {
$alts->add($config->alt);
}
return $alts;
}
/**
* @return array<SemanticContext>
*/
public function getPredicates(): array
{
$predicates = [];
foreach ($this->configs as $config) {
if ($config->semanticContext !== SemanticContext::none()) {
$predicates[] = $config->semanticContext;
}
}
return $predicates;
}
public function get(int $index): ATNConfig
{
return $this->configs[$index];
}
public function optimizeConfigs(ATNSimulator $interpreter): void
{
if ($this->readOnly || $this->configLookup === null) {
throw new \InvalidArgumentException('This set is readonly');
}
if ($this->configLookup->isEmpty()) {
return;
}
foreach ($this->configs as $config) {
if ($config->context !== null) {
$config->context = $interpreter->getCachedContext($config->context);
}
}
}
/**
* @param array<ATNConfig> $configs
*/
public function addAll(array $configs): void
{
foreach ($configs as $config) {
$this->add($config);
}
}
public function equals(object $other): bool
{
if ($this === $other) {
return true;
}
if (!$other instanceof self) {
return false;
}
return $this->fullCtx === $other->fullCtx
&& $this->uniqueAlt === $other->uniqueAlt
&& $this->hasSemanticContext === $other->hasSemanticContext
&& $this->dipsIntoOuterContext === $other->dipsIntoOuterContext
&& Equality::equals($this->configs, $other->configs)
&& Equality::equals($this->conflictingAlts, $other->conflictingAlts);
}
public function hashCode(): int
{
if (!$this->isReadOnly()) {
return Hasher::hash($this->configs);
}
if ($this->cachedHashCode === null) {
$this->cachedHashCode = Hasher::hash($this->configs);
}
return $this->cachedHashCode;
}
public function getLength(): int
{
return \count($this->configs);
}
public function isEmpty(): bool
{
return $this->getLength() === 0;
}
public function contains(object $item): bool
{
if ($this->configLookup === null) {
throw new \InvalidArgumentException('This method is not implemented for readonly sets.');
}
return $this->configLookup->contains($item);
}
public function containsFast(ATNConfig $item): bool
{
return $this->contains($item);
}
public function getIterator(): \Iterator
{
return new \ArrayIterator($this->configs);
}
public function clear(): void
{
if ($this->readOnly) {
throw new \InvalidArgumentException('This set is readonly');
}
$this->configs = [];
$this->cachedHashCode = -1;
$this->configLookup = new Set();
}
public function isReadOnly(): bool
{
return $this->readOnly;
}
public function setReadonly(bool $readOnly): void
{
$this->readOnly = $readOnly;
if ($readOnly) {
$this->configLookup = null; // can't mod, no need for lookup cache
}
}
public function getConflictingAlts(): ?BitSet
{
return $this->conflictingAlts;
}
public function setConflictingAlts(BitSet $conflictingAlts): void
{
$this->conflictingAlts = $conflictingAlts;
}
public function __toString(): string
{
return \sprintf(
'[%s]%s%s%s%s',
\implode(', ', $this->configs),
$this->hasSemanticContext ? ',hasSemanticContext=' . $this->hasSemanticContext : '',
$this->uniqueAlt !== ATN::INVALID_ALT_NUMBER ? ',uniqueAlt=' . $this->uniqueAlt : '',
$this->conflictingAlts !== null ? ',conflictingAlts=' . $this->conflictingAlts : '',
$this->dipsIntoOuterContext ? ',dipsIntoOuterContext' : '',
);
}
}