Issues (67)

src/PredictionContexts/PredictionContextCache.php (1 issue)

Severity
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Antlr\Antlr4\Runtime\PredictionContexts;
6
7
use Antlr\Antlr4\Runtime\Utils\Map;
8
9
/**
10
 * Used to cache {@see PredictionContext} objects. Its used for the shared
11
 * context cash associated with contexts in DFA states. This cache
12
 * can be used for both lexers and parsers.
13
 */
14
class PredictionContextCache
15
{
16
    /** @var Map */
17
    protected $cache;
18
19 1
    public function __construct()
20
    {
21 1
        $this->cache = new Map();
22 1
    }
23
24
    /**
25
     * Add a context to the cache and return it. If the context already exists,
26
     * return that one instead and do not add a new context to the cache.
27
     * Protect shared cache from unsafe thread access.
28
     */
29 1
    public function add(PredictionContext $ctx) : PredictionContext
30
    {
31 1
        if ($ctx === PredictionContext::empty()) {
0 ignored issues
show
The condition $ctx === Antlr\Antlr4\Ru...dictionContext::empty() is always false.
Loading history...
32
            return $ctx;
33
        }
34
35 1
        $existing = $this->cache->get($ctx);
36
37 1
        if ($existing !== null) {
38
            return $existing;
39
        }
40
41 1
        $this->cache->put($ctx, $ctx);
42
43 1
        return $ctx;
44
    }
45
46 2
    public function get(PredictionContext $ctx) : ?PredictionContext
47
    {
48 2
        return $this->cache->get($ctx);
49
    }
50
51
    public function length() : int
52
    {
53
        return $this->cache->count();
54
    }
55
}
56