1 /* 2 * Copyright (c) 2012-2017 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 package org.antlr.v4.runtime.atn; 8 9 import java.util.HashMap; 10 import java.util.Map; 11 12 /** Used to cache {@link PredictionContext} objects. Its used for the shared 13 * context cash associated with contexts in DFA states. This cache 14 * can be used for both lexers and parsers. 15 */ 16 public class PredictionContextCache { 17 protected final Map<PredictionContext, PredictionContext> cache = 18 new HashMap<PredictionContext, PredictionContext>(); 19 20 /** Add a context to the cache and return it. If the context already exists, 21 * return that one instead and do not add a new context to the cache. 22 * Protect shared cache from unsafe thread access. 23 */ add(PredictionContext ctx)24 public PredictionContext add(PredictionContext ctx) { 25 if ( ctx==PredictionContext.EMPTY ) return PredictionContext.EMPTY; 26 PredictionContext existing = cache.get(ctx); 27 if ( existing!=null ) { 28 // System.out.println(name+" reuses "+existing); 29 return existing; 30 } 31 cache.put(ctx, ctx); 32 return ctx; 33 } 34 get(PredictionContext ctx)35 public PredictionContext get(PredictionContext ctx) { 36 return cache.get(ctx); 37 } 38 size()39 public int size() { 40 return cache.size(); 41 } 42 } 43