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. 14 * 15 * Its used for the shared 16 * context objects associated with contexts in DFA states. This cache 17 * can be used for both lexers and parsers. 18 */ 19 class PredictionContextCache 20 { 21 22 protected PredictionContext[PredictionContext] cache; 23 24 /** 25 * Add a context to the cache and return it. 26 * 27 * If the context already exists, 28 * return that one instead and do not add a new context to the cache. 29 * Protect shared cache from unsafe thread access. 30 */ 31 public PredictionContext add(PredictionContext predictionContext) 32 { 33 if (predictionContext == PredictionContext.EMPTY) 34 return predictionContext; 35 if (hasKey(predictionContext)) { 36 // System.out.println(name+" reuses "+existing); 37 return cache[predictionContext]; 38 } 39 cache[predictionContext] = predictionContext; 40 return predictionContext; 41 } 42 43 /** 44 * Get the predictionContext from cache. 45 */ 46 public PredictionContext get(PredictionContext predictionContext) 47 { 48 return cache[predictionContext]; 49 } 50 51 /** 52 * Contains the cache the predictionContext? 53 */ 54 public bool hasKey(PredictionContext predictionContext) 55 { 56 return (predictionContext in cache) !is null; 57 } 58 59 /** 60 * Size of current cache. 61 */ 62 public size_t size() 63 { 64 return cache.length; 65 } 66 67 }