-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
JavassistUtils.java
245 lines (225 loc) · 12.3 KB
/
JavassistUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/*
* Copyright 2016 Federico Tomassetti
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.javaparser.symbolsolver.javassistmodel;
import com.github.javaparser.ast.type.PrimitiveType;
import com.github.javaparser.resolution.MethodUsage;
import com.github.javaparser.resolution.UnsolvedSymbolException;
import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration;
import com.github.javaparser.resolution.declarations.ResolvedTypeParameterDeclaration;
import com.github.javaparser.resolution.declarations.ResolvedTypeParametrizable;
import com.github.javaparser.resolution.types.*;
import com.github.javaparser.symbolsolver.core.resolution.Context;
import com.github.javaparser.symbolsolver.model.resolution.TypeSolver;
import com.github.javaparser.symbolsolver.model.typesystem.ReferenceTypeImpl;
import com.github.javaparser.symbolsolver.resolution.SymbolSolver;
import javassist.*;
import javassist.bytecode.*;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author Federico Tomassetti
*/
class JavassistUtils {
static Optional<MethodUsage> getMethodUsage(CtClass ctClass, String name, List<ResolvedType> argumentsTypes, TypeSolver typeSolver, Context invokationContext) {
// TODO avoid bridge and synthetic methods
for (CtMethod method : ctClass.getDeclaredMethods()) {
if (method.getName().equals(name)) {
// TODO check typeParametersValues
MethodUsage methodUsage = new MethodUsage(new JavassistMethodDeclaration(method, typeSolver));
if (argumentsTypes.size() < methodUsage.getNoParams()) {
// this method cannot be a good candidate (except if variadic ?)
continue;
}
try {
if (method.getGenericSignature() != null) {
SignatureAttribute.MethodSignature methodSignature = SignatureAttribute.toMethodSignature(method.getGenericSignature());
List<ResolvedType> parametersOfReturnType = parseTypeParameters(methodSignature.getReturnType().toString(), typeSolver, invokationContext);
ResolvedType newReturnType = methodUsage.returnType();
// consume one parametersOfReturnType at the time
if (newReturnType.isReferenceType() && parametersOfReturnType.size() > 0) {
newReturnType = newReturnType.asReferenceType().transformTypeParameters(tp -> parametersOfReturnType.remove(0));
}
methodUsage = methodUsage.replaceReturnType(newReturnType);
}
return Optional.of(methodUsage);
} catch (BadBytecode e) {
throw new RuntimeException(e);
}
}
}
try {
CtClass superClass = ctClass.getSuperclass();
if (superClass != null) {
Optional<MethodUsage> ref = new JavassistClassDeclaration(superClass, typeSolver).solveMethodAsUsage(name, argumentsTypes, typeSolver, invokationContext, null);
if (ref.isPresent()) {
return ref;
}
}
} catch (NotFoundException e) {
throw new RuntimeException(e);
}
try {
for (CtClass interfaze : ctClass.getInterfaces()) {
Optional<MethodUsage> ref = new JavassistInterfaceDeclaration(interfaze, typeSolver).solveMethodAsUsage(name, argumentsTypes, typeSolver, invokationContext, null);
if (ref.isPresent()) {
return ref;
}
}
} catch (NotFoundException e) {
throw new RuntimeException(e);
}
return Optional.empty();
}
private static List<ResolvedType> parseTypeParameters(String signature, TypeSolver typeSolver, Context invokationContext) {
String originalSignature = signature;
if (signature.contains("<")) {
signature = signature.substring(signature.indexOf('<') + 1);
if (!signature.endsWith(">")) {
throw new IllegalArgumentException();
}
signature = signature.substring(0, signature.length() - 1);
if (signature.contains(",")) {
throw new UnsupportedOperationException();
}
if (signature.startsWith("?")) {
// TODO: check bounds
List<ResolvedType> types = new ArrayList<>();
types.add(ResolvedWildcard.UNBOUNDED);
return types;
}
List<ResolvedType> typeParameters = parseTypeParameters(signature, typeSolver, invokationContext);
if (signature.contains("<")) {
signature = signature.substring(0, signature.indexOf('<'));
}
if (signature.contains(">")) {
throw new UnsupportedOperationException();
}
ResolvedType type = new SymbolSolver(typeSolver).solveTypeUsage(signature, invokationContext);
if (type.isReferenceType() && typeParameters.size() > 0) {
type = type.asReferenceType().transformTypeParameters(tp -> typeParameters.remove(0));
}
List<ResolvedType> types = new ArrayList<>();
types.add(type);
return types;
} else {
return Collections.emptyList();
}
}
static ResolvedType signatureTypeToType(SignatureAttribute.Type signatureType, TypeSolver typeSolver, ResolvedTypeParametrizable typeParametrizable) {
if (signatureType instanceof SignatureAttribute.ClassType) {
SignatureAttribute.ClassType classType = (SignatureAttribute.ClassType) signatureType;
List<ResolvedType> typeArguments = classType.getTypeArguments() == null ? Collections.emptyList() : Arrays.stream(classType.getTypeArguments()).map(ta -> typeArgumentToType(ta, typeSolver, typeParametrizable)).collect(Collectors.toList());
final String typeName =
classType.getDeclaringClass() != null ?
classType.getDeclaringClass().getName() + "." + classType.getName() :
classType.getName();
ResolvedReferenceTypeDeclaration typeDeclaration = typeSolver.solveType(
removeTypeArguments(internalNameToCanonicalName(typeName)));
return new ReferenceTypeImpl(typeDeclaration, typeArguments, typeSolver);
} else if (signatureType instanceof SignatureAttribute.TypeVariable) {
SignatureAttribute.TypeVariable typeVariableSignature = (SignatureAttribute.TypeVariable) signatureType;
Optional<ResolvedTypeParameterDeclaration> typeParameterDeclarationOpt = typeParametrizable.findTypeParameter(typeVariableSignature.getName());
if (!typeParameterDeclarationOpt.isPresent()) {
throw new UnsolvedSymbolException("Unable to solve TypeVariable " + typeVariableSignature);
}
ResolvedTypeParameterDeclaration typeParameterDeclaration = typeParameterDeclarationOpt.get();
return new ResolvedTypeVariable(typeParameterDeclaration);
} else if (signatureType instanceof SignatureAttribute.ArrayType) {
SignatureAttribute.ArrayType arrayType = (SignatureAttribute.ArrayType) signatureType;
return new ResolvedArrayType(signatureTypeToType(arrayType.getComponentType(), typeSolver, typeParametrizable));
} else if (signatureType instanceof SignatureAttribute.BaseType) {
SignatureAttribute.BaseType baseType = (SignatureAttribute.BaseType) signatureType;
if (baseType.toString().equals("void")) {
return ResolvedVoidType.INSTANCE;
} else {
return ResolvedPrimitiveType.byName(baseType.toString());
}
} else {
throw new RuntimeException(signatureType.getClass().getCanonicalName());
}
}
private static String removeTypeArguments(String typeName) {
if (typeName.contains("<")) {
return typeName.substring(0, typeName.indexOf('<'));
} else {
return typeName;
}
}
static String internalNameToCanonicalName(String typeName) {
return typeName.replaceAll("\\$", ".");
}
private static ResolvedType objectTypeArgumentToType(SignatureAttribute.ObjectType typeArgument, TypeSolver typeSolver, ResolvedTypeParametrizable typeParametrizable) {
if(typeArgument instanceof SignatureAttribute.ArrayType){
String baseTypeName = ((SignatureAttribute.ArrayType) typeArgument).getComponentType().jvmTypeName();
ResolvedType baseType = getGenericParameterByName(baseTypeName, typeParametrizable, typeSolver);
return new ResolvedArrayType(baseType);
} else {
String typeName = typeArgument.jvmTypeName();
return getGenericParameterByName(typeName, typeParametrizable, typeSolver);
}
}
private static ResolvedType getGenericParameterByName(String typeName, ResolvedTypeParametrizable typeParametrizable, TypeSolver typeSolver) {
if(ResolvedPrimitiveType.isPrimitive(typeName))
return ResolvedPrimitiveType.byName(typeName);
Optional<ResolvedType> type = typeParametrizable.findTypeParameter(typeName).map(ResolvedTypeVariable::new);
return type.orElseGet(() -> new ReferenceTypeImpl(
typeSolver.solveType(removeTypeArguments(internalNameToCanonicalName(typeName))),
typeSolver));
}
private static ResolvedType typeArgumentToType(SignatureAttribute.TypeArgument typeArgument, TypeSolver typeSolver, ResolvedTypeParametrizable typeParametrizable) {
if (typeArgument.isWildcard()) {
if (typeArgument.getType() == null) {
return ResolvedWildcard.UNBOUNDED;
} else if (typeArgument.getKind() == '+') {
return ResolvedWildcard.extendsBound(objectTypeArgumentToType(typeArgument.getType(), typeSolver, typeParametrizable));
} else if (typeArgument.getKind() == '-') {
return ResolvedWildcard.superBound(objectTypeArgumentToType(typeArgument.getType(), typeSolver, typeParametrizable));
} else {
throw new UnsupportedOperationException();
}
} else {
return objectTypeArgumentToType(typeArgument.getType(), typeSolver, typeParametrizable);
}
}
/**
* Returns the {@code paramNumber}th parameter of a method or constructor, if it is available.
* <p>
* The name is not available, if
* <ul>
* <li>the method is abstract, i.e. explicitly declared as abstract or it is a non-default interface method</li>
* <li>methods and constructors from jar files, which have been compiled without debug symbols</li>
* </ul>
* <p>
* The parameters are counted from 0, skipping the implicit {@code this} parameter of non-static methods.
*
* @param method the method to look into
* @param paramNumber the number of the parameter to look for
* @return the found parameter name or empty, if the name is not available
*/
static Optional<String> extractParameterName(CtBehavior method, int paramNumber) {
MethodInfo methodInfo = method.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
if (codeAttribute != null) {
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute
.tag);
if (attr != null) {
int pos = Modifier.isStatic(method.getModifiers()) ? 0 : 1;
return Optional.ofNullable(attr.variableName(paramNumber + pos));
}
}
return Optional.empty();
}
}