()
| 99 | }; |
| 100 | |
| 101 | public EvalFunc() { |
| 102 | // Resolve concrete type for T of EvalFunc<T> |
| 103 | // 1. Build map from type param to type for class hierarchy from current class to EvalFunc |
| 104 | Map<TypeVariable<?>, Type> typesByTypeVariable = new HashMap<TypeVariable<?>, Type>(); |
| 105 | Class<?> cls = getClass(); |
| 106 | Type type = cls.getGenericSuperclass(); |
| 107 | cls = cls.getSuperclass(); |
| 108 | while (EvalFunc.class.isAssignableFrom(cls)) { |
| 109 | TypeVariable<? extends Class<?>>[] typeParams = cls.getTypeParameters(); |
| 110 | if (type instanceof ParameterizedType) { |
| 111 | ParameterizedType pType = (ParameterizedType) type; |
| 112 | Type[] typeArgs = pType.getActualTypeArguments(); |
| 113 | for (int i = 0; i < typeParams.length; i++) { |
| 114 | typesByTypeVariable.put(typeParams[i], typeArgs[i]); |
| 115 | } |
| 116 | } |
| 117 | type = cls.getGenericSuperclass(); |
| 118 | cls = cls.getSuperclass(); |
| 119 | } |
| 120 | |
| 121 | // 2. Use type param to type map to determine concrete type of for T of EvalFunc<T> |
| 122 | Type targetType = EvalFunc.class.getTypeParameters()[0]; |
| 123 | while (targetType != null && targetType instanceof TypeVariable) { |
| 124 | targetType = typesByTypeVariable.get(targetType); |
| 125 | } |
| 126 | if (targetType == null |
| 127 | || targetType instanceof GenericArrayType |
| 128 | || targetType instanceof WildcardType) { |
| 129 | throw new RuntimeException(String.format( |
| 130 | "Failed to determine concrete type for type parameter T of EvalFunc<T> for derived class '%s'", |
| 131 | getClass().getName())); |
| 132 | } |
| 133 | returnType = targetType; |
| 134 | |
| 135 | // Type check the initial, intermediate, and final functions |
| 136 | if (this instanceof Algebraic){ |
| 137 | Algebraic a = (Algebraic)this; |
| 138 | |
| 139 | String errMsg = "function of " + getClass().getName() + " is not of the expected type."; |
| 140 | if (getReturnTypeFromSpec(new FuncSpec(a.getInitial())) != Tuple.class) |
| 141 | throw new RuntimeException("Initial " + errMsg); |
| 142 | if (getReturnTypeFromSpec(new FuncSpec(a.getIntermed())) != Tuple.class) |
| 143 | throw new RuntimeException("Intermediate " + errMsg); |
| 144 | if (!getReturnTypeFromSpec(new FuncSpec(a.getFinal())).equals(returnType)) |
| 145 | throw new RuntimeException("Final " + errMsg); |
| 146 | } |
| 147 | |
| 148 | } |
| 149 | |
| 150 | |
| 151 | private Type getReturnTypeFromSpec(FuncSpec funcSpec){ |
nothing calls this directly
no test coverage detected