1 /* 2 * Copyright (c) 2012-2019 The ANTLR Project. All rights reserved. 3 * Use of this file is governed by the BSD 3-clause license that 4 * can be found in the LICENSE.txt file in the project root. 5 */ 6 7 module antlr.v4.runtime.atn.PredictionContextCache; 8 9 import std.conv; 10 import antlr.v4.runtime.atn.PredictionContext; 11 12 /** 13 * Used to cache {@link PredictionContext} objects. Its used for the shared 14 * context cash associated with contexts in DFA states. This cache 15 * can be used for both lexers and parsers. 16 */ 17 class PredictionContextCache 18 { 19 20 protected PredictionContext[PredictionContext] cache; 21 22 /** 23 * Add a context to the cache and return it. If the context already exists, 24 * return that one instead and do not add a new context to the cache. 25 * Protect shared cache from unsafe thread access. 26 */ 27 public PredictionContext add(PredictionContext ctx) 28 { 29 if (ctx == PredictionContext.EMPTY) 30 return ctx; 31 if (hasKey(ctx)) { 32 // System.out.println(name+" reuses "+existing); 33 return cache[ctx]; 34 } 35 cache[ctx] = ctx; 36 return ctx; 37 } 38 39 public PredictionContext get(PredictionContext ctx) 40 { 41 return cache[ctx]; 42 } 43 44 public size_t size() 45 { 46 return cache.length; 47 } 48 49 public bool hasKey(PredictionContext predictionContext) 50 { 51 if (predictionContext in cache) 52 return true; 53 return false; 54 } 55 56 }