Skip to content

Commit 4b96083

Browse files
gselzerctrueden
authored andcommitted
Add utility methods for checking type satisfaction
1 parent e4e5ed6 commit 4b96083

1 file changed

Lines changed: 367 additions & 0 deletions

File tree

Lines changed: 367 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,367 @@
1+
/*
2+
* #%L
3+
* SciJava Operations: a framework for reusable algorithms.
4+
* %%
5+
* Copyright (C) 2016 - 2019 SciJava Ops developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.ops.types;
31+
32+
import java.lang.reflect.GenericArrayType;
33+
import java.lang.reflect.InvocationTargetException;
34+
import java.lang.reflect.Method;
35+
import java.lang.reflect.ParameterizedType;
36+
import java.lang.reflect.Type;
37+
import java.lang.reflect.TypeVariable;
38+
import java.lang.reflect.WildcardType;
39+
import java.util.ArrayList;
40+
import java.util.Arrays;
41+
import java.util.HashMap;
42+
import java.util.List;
43+
import java.util.Map;
44+
import java.util.Optional;
45+
46+
import org.scijava.util.Types;
47+
48+
/**
49+
* Additional functions beyond {@link Types} for working with generic types,
50+
* fields and methods.
51+
*
52+
* @author Gabe Selzer
53+
*/
54+
public final class TypeTools {
55+
56+
private TypeTools() {
57+
// NB: Prevent instantiation of utility class.
58+
}
59+
60+
/**
61+
* Discerns whether it would be legal to pass a sequence of references of the
62+
* given source types to a method with parameters typed according to the
63+
* specified sequence of destination types.
64+
* <p>
65+
* An example: suppose you have a method
66+
* {@code <T extends Number> mergeLists(List<T> list1, List<T> list2)}. It is
67+
* legal to pass two {@code List<Integer>} instances to the method, but
68+
* illegal to pass a {@code List<Integer>} and {@code List<Double>} because
69+
* {@code T} cannot be both {@code Integer} and {@code Double} simultaneously.
70+
* </p>
71+
*/
72+
public static boolean satisfies(final Type[] args, final Type[] params) {
73+
// create a HashMap to monitor the restrictions of the type variables.
74+
final HashMap<TypeVariable<?>, TypeVarInfo> typeBounds = new HashMap<>();
75+
76+
return satisfies(args, params, typeBounds);
77+
78+
}
79+
80+
public static boolean satisfies(final Type[] args, final Type[] params,
81+
final HashMap<TypeVariable<?>, TypeVarInfo> typeBounds)
82+
{
83+
if (args.length != params.length) {
84+
throw new IllegalArgumentException("src and dest lengths differ");
85+
}
86+
87+
for (int i = 0; i < params.length; i++) {
88+
// First, check raw type assignability.
89+
if (!satisfiesRawTypes(args[i], params[i])) return false;
90+
91+
if (params[i] instanceof ParameterizedType) {
92+
if (!satisfiesParameterizedTypes(args[i], (ParameterizedType) params[i],
93+
typeBounds)) return false;
94+
}
95+
else if (params[i] instanceof TypeVariable) {
96+
if (!satisfiesTypeVariable(args[i], (TypeVariable<?>) params[i],
97+
typeBounds)) return false;
98+
}
99+
else if (params[i] instanceof WildcardType) {
100+
if (!satisfiesWildcardType(args[i], (WildcardType) params[i]))
101+
return false;
102+
}
103+
else if (params[i] instanceof GenericArrayType) {
104+
if (!satisfiesGenericArrayType(args[i], (GenericArrayType) params[i],
105+
typeBounds)) return false;
106+
}
107+
//final Type t = TypeToken.of(params[i]).resolveType(args[i]).getType();
108+
// System.out.println("src[" + i + "] = " + t);
109+
}
110+
return true;
111+
}
112+
113+
// TODO: Expose this functionality in org.scijava.util.Types.
114+
private static Method typesSatisfyVariables;
115+
116+
public static boolean satisfies(
117+
final Map<TypeVariable<?>, Type> typeVarAssigns)
118+
{
119+
//return Types.TypeUtils.typesSatisfyVariables(typeVarAssigns);
120+
try {
121+
if (typesSatisfyVariables == null) {
122+
final Class<?> typeUtilsClass = //
123+
Arrays.stream(Types.class.getDeclaredClasses())//
124+
.filter(c -> c.getSimpleName().equals("TypeUtils"))//
125+
.findFirst().get();
126+
typesSatisfyVariables = //
127+
typeUtilsClass.getMethod("typesSatisfyVariables", Map.class);
128+
}
129+
return (Boolean) typesSatisfyVariables.invoke(null, typeVarAssigns);
130+
}
131+
catch (NoSuchMethodException | SecurityException | IllegalAccessException
132+
| IllegalArgumentException | InvocationTargetException exc)
133+
{
134+
throw new RuntimeException(exc);
135+
}
136+
}
137+
138+
private static boolean satisfiesRawTypes(final Type arg, final Type param) {
139+
final List<Class<?>> srcClasses = Types.raws(arg);
140+
final List<Class<?>> destClasses = Types.raws(param);
141+
for (final Class<?> destClass : destClasses) {
142+
final Optional<Class<?>> first = srcClasses.stream().filter(
143+
srcClass -> destClass.isAssignableFrom(srcClass)).findFirst();
144+
if (!first.isPresent()) {
145+
// TODO can we remove this?
146+
// throw new IllegalArgumentException("Argument #" + i + //
147+
// " (" + Types.name(src[i]) + ") is not assignable to " + //
148+
// "destination type (" + Types.name(dest[i]) + ")");
149+
return false;
150+
}
151+
}
152+
return true;
153+
}
154+
155+
private static boolean satisfiesParameterizedTypes(final Type arg,
156+
final ParameterizedType param,
157+
final HashMap<TypeVariable<?>, TypeVarInfo> typeBounds)
158+
{
159+
// get an array of the destination parameter types
160+
final Type[] destTypes = param.getActualTypeArguments();
161+
162+
// get an array of the source argument types
163+
final Type[] srcTypes = new Type[destTypes.length];
164+
for (int i = 0; i < srcTypes.length; i++) {
165+
srcTypes[i] = Types.param(arg, Types.raw(arg), i);
166+
}
167+
// check to see if any of the Types of this ParameterizedType are
168+
// TypeVariables, if so restrict them to the type parameter of the argument.
169+
for (int i = 0; i < destTypes.length; i++) {
170+
final Type destType = destTypes[i];
171+
if (destType instanceof TypeVariable<?>) {
172+
final Type srcType = srcTypes[i];
173+
final TypeVariable<?> destTypeVar = (TypeVariable<?>) destType;
174+
if (!satisfiesTypeParameter(srcType, destTypeVar, typeBounds))
175+
return false;
176+
}
177+
}
178+
// recursively run satisfies on these arrays
179+
return satisfies(srcTypes, destTypes, typeBounds);
180+
}
181+
182+
/**
183+
* Determines whether or not the {@link Type} {@code arg} can satisfy the
184+
* {@link TypeVariable} {@code param} given the preexisting limitations of
185+
* {@code param}. If it is determined that this replacement is allowed the
186+
* {@link TypeVariable} is then restriced to the {@link Type} of {@code arg}
187+
* (if this is not desired use {@link #satisfiesTypeVariable} instead}.
188+
*
189+
* @param arg - a Type Parameter for a given {@link ParameterizedType}
190+
* @param param - a {@link TypeVariable} that could potentially be replaced
191+
* with {@code arg}
192+
* @param typeBounds - a {@link HashMap} containing the current restrictions
193+
* of the {@link TypeVariable}s
194+
* @return {@code boolean} - true if the replacement of {@code param} with
195+
* {@code arg} is allowed.
196+
*/
197+
private static boolean satisfiesTypeParameter(final Type arg,
198+
final TypeVariable<?> param,
199+
final HashMap<TypeVariable<?>, TypeVarInfo> typeBounds)
200+
{
201+
// add the type variable to the HashMap if it does not yet exist.
202+
if (!typeBounds.containsKey(param)) {
203+
final TypeVariable<?> newTypeVar = param;
204+
typeBounds.put(newTypeVar, new TypeVarInfo(newTypeVar));
205+
}
206+
// attempt to restrict the bounds of the type variable to the argument.
207+
if (!typeBounds.get(param).fixBounds(arg)) return false;
208+
209+
// TODO do we need type parameter recursion here as we do in
210+
// satisfiesTypeVariable?
211+
212+
return true;
213+
}
214+
215+
private static boolean satisfiesTypeVariable(final Type arg,
216+
final TypeVariable<?> param,
217+
final HashMap<TypeVariable<?>, TypeVarInfo> typeBounds)
218+
{
219+
// if the TypeVariable is not already in the hashMap add it.
220+
if (!typeBounds.containsKey(param)) typeBounds.put(param, new TypeVarInfo(
221+
param));
222+
// check to make sure that arg is a viable replacement for the type
223+
// variable.
224+
if (!typeBounds.get(param).allowType(arg)) return false;
225+
226+
// if the type variable refers to some parameterized type (e.g. T extends
227+
// List<?>), call satisfiesTypeParameters on the bounds of param that
228+
// are ParameterizedTypes.
229+
final Type[] paramBounds = typeBounds.get(param).upperBounds;
230+
for (final Type paramBound : paramBounds) {
231+
// only have to check the bounds of the
232+
if (paramBound instanceof ParameterizedType) {
233+
234+
final ParameterizedType paramBoundType = (ParameterizedType) paramBound;
235+
final Type[] paramBoundTypes = paramBoundType.getActualTypeArguments();
236+
for (int i = 0; i < paramBoundTypes.length; i++) {
237+
final Type argType = Types.param(arg, Types.raw(param), i);
238+
if (paramBoundTypes[i] instanceof TypeVariable<?> &&
239+
!satisfiesTypeParameter(argType,
240+
(TypeVariable<?>) paramBoundTypes[i], typeBounds)) return false;
241+
else if (!satisfies(new Type[] { argType }, new Type[] {
242+
paramBoundTypes[i] }, typeBounds)) return false;
243+
}
244+
}
245+
}
246+
247+
return true;
248+
}
249+
250+
private static boolean satisfiesWildcardType(final Type arg,
251+
final WildcardType param)
252+
{
253+
final Type[] upperBounds = param.getUpperBounds();
254+
final Type[] lowerBounds = param.getLowerBounds();
255+
final Class<?> argType = Types.raw(arg);
256+
for (final Type upperBound : upperBounds) {
257+
// check that the argument can satisfy the parameter
258+
final Class<?> upperType = Types.raw(upperBound);
259+
if (!upperType.isAssignableFrom(argType)) return false;
260+
}
261+
for (final Type lowerBound : lowerBounds) {
262+
final Class<?> lowerType = Types.raw(lowerBound);
263+
// check that the argument can satisfy the parameter
264+
if (!argType.isAssignableFrom(lowerType)) return false;
265+
}
266+
267+
return true;
268+
}
269+
270+
private static boolean satisfiesGenericArrayType(final Type arg,
271+
final GenericArrayType param,
272+
final HashMap<TypeVariable<?>, TypeVarInfo> typeBounds)
273+
{
274+
// get a class object of the component type of each array
275+
final Type argComponent = Types.component(arg);
276+
final Type paramComponent = Types.component(param);
277+
278+
if (paramComponent instanceof ParameterizedType) {
279+
// TODO are these casts safe?
280+
final ParameterizedType argType = (ParameterizedType) argComponent;
281+
final ParameterizedType paramType = (ParameterizedType) paramComponent;
282+
283+
if (!satisfiesParameterizedTypes(argType, paramType, typeBounds))
284+
return false;
285+
}
286+
287+
else if (paramComponent instanceof TypeVariable) {
288+
// TODO are these casts safe?
289+
final TypeVariable<?> paramType = (TypeVariable<?>) paramComponent;
290+
291+
if (!satisfiesTypeVariable(argComponent, paramType, typeBounds))
292+
return false;
293+
}
294+
295+
// TODO is this necessary? It is only necessary if the component is allowed
296+
// to be
297+
// something other than a ParameterizedType or a TypeVariable.
298+
final Class<?> argClass = Types.raw(argComponent);
299+
final Class<?> paramClass = Types.raw(paramComponent);
300+
if (!paramClass.isAssignableFrom(argClass)) return false;
301+
return true;
302+
}
303+
304+
/**
305+
* Maintains info about an {@link TypeVariable}.
306+
*/
307+
private static class TypeVarInfo {
308+
309+
private final TypeVariable<?> var;
310+
private final Type[] upperBounds;
311+
private List<Type> types;
312+
313+
public TypeVarInfo(final TypeVariable<?> var) {
314+
this.var = var;
315+
this.upperBounds = var.getBounds();
316+
this.types = new ArrayList<>();
317+
}
318+
319+
/**
320+
* Sets the type of this {@link TypeVarInfo} to the type parameter, if it is
321+
* allowed. If the type parameter is not contained within the bounds of the
322+
* {@link TypeVariable}, then we return false, and the type of the
323+
* {@code TypeVariable} is not changed. N.B. if this {@code TypeVariable} is
324+
* being used in an {@link ParameterizedType} then
325+
* {@link TypeVarInfo#fixBounds} should be used instead.
326+
*
327+
* @param type - the {@link Type} we are trying to assign to this
328+
* {@link TypeVarInfo}.
329+
* @return {@code boolean} - false if the {@code Type} is not assignable to
330+
* this {@code TypeVarInfo}
331+
*/
332+
public boolean allowType(final Type type) {
333+
final Class<?> typeClass = Types.raw(type);
334+
// make sure that type extends all of the bounds of the type variable
335+
for (final Type upperBound : upperBounds) {
336+
if (!Types.raw(upperBound).isAssignableFrom(typeClass)) return false;
337+
}
338+
339+
types.add(type);
340+
return true;
341+
}
342+
343+
/**
344+
* If a {@link TypeVariable} is used in a {@link ParameterizedType}, the
345+
* bounds have to be fixed such that the upperBound is the {@link Type}
346+
* parameterizing that {@link ParameterizedType}.
347+
*/
348+
public boolean fixBounds(final Type bound) {
349+
for (int i = 0; i < upperBounds.length; i++) {
350+
if (Types.raw(upperBounds[i]).isAssignableFrom(Types.raw(bound)))
351+
upperBounds[i] = bound;
352+
else return false;
353+
}
354+
355+
// make sure that all of the types that already fit in this variable
356+
// before the variable was fixed still are allowed by the type variable.
357+
final List<Type> temp = types;
358+
temp.add(bound);
359+
types = new ArrayList<>();
360+
for (final Type type : temp) {
361+
if (!allowType(type)) return false;
362+
}
363+
364+
return true;
365+
}
366+
}
367+
}

0 commit comments

Comments
 (0)