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 public class SingletonPredictionContext extends PredictionContext { 10 public final PredictionContext parent; 11 public final int returnState; 12 SingletonPredictionContext(PredictionContext parent, int returnState)13 SingletonPredictionContext(PredictionContext parent, int returnState) { 14 super(parent != null ? calculateHashCode(parent, returnState) : calculateEmptyHashCode()); 15 assert returnState!=ATNState.INVALID_STATE_NUMBER; 16 this.parent = parent; 17 this.returnState = returnState; 18 } 19 create(PredictionContext parent, int returnState)20 public static SingletonPredictionContext create(PredictionContext parent, int returnState) { 21 if ( returnState == EMPTY_RETURN_STATE && parent == null ) { 22 // someone can pass in the bits of an array ctx that mean $ 23 return EMPTY; 24 } 25 return new SingletonPredictionContext(parent, returnState); 26 } 27 28 @Override size()29 public int size() { 30 return 1; 31 } 32 33 @Override getParent(int index)34 public PredictionContext getParent(int index) { 35 assert index == 0; 36 return parent; 37 } 38 39 @Override getReturnState(int index)40 public int getReturnState(int index) { 41 assert index == 0; 42 return returnState; 43 } 44 45 @Override equals(Object o)46 public boolean equals(Object o) { 47 if (this == o) { 48 return true; 49 } 50 else if ( !(o instanceof SingletonPredictionContext) ) { 51 return false; 52 } 53 54 if ( this.hashCode() != o.hashCode() ) { 55 return false; // can't be same if hash is different 56 } 57 58 SingletonPredictionContext s = (SingletonPredictionContext)o; 59 return returnState == s.returnState && 60 (parent!=null && parent.equals(s.parent)); 61 } 62 63 @Override toString()64 public String toString() { 65 String up = parent!=null ? parent.toString() : ""; 66 if ( up.length()==0 ) { 67 if ( returnState == EMPTY_RETURN_STATE ) { 68 return "$"; 69 } 70 return String.valueOf(returnState); 71 } 72 return String.valueOf(returnState)+" "+up; 73 } 74 } 75