/
ClassFileConverter.java
397 lines (371 loc) · 16.7 KB
/
ClassFileConverter.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*
* 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.google.devtools.j2objc.javac;
import com.google.devtools.j2objc.Options;
import com.google.devtools.j2objc.ast.AbstractTypeDeclaration;
import com.google.devtools.j2objc.ast.Annotation;
import com.google.devtools.j2objc.ast.AnnotationTypeDeclaration;
import com.google.devtools.j2objc.ast.AnnotationTypeMemberDeclaration;
import com.google.devtools.j2objc.ast.Block;
import com.google.devtools.j2objc.ast.BodyDeclaration;
import com.google.devtools.j2objc.ast.CompilationUnit;
import com.google.devtools.j2objc.ast.EnumConstantDeclaration;
import com.google.devtools.j2objc.ast.EnumDeclaration;
import com.google.devtools.j2objc.ast.Expression;
import com.google.devtools.j2objc.ast.FieldDeclaration;
import com.google.devtools.j2objc.ast.MarkerAnnotation;
import com.google.devtools.j2objc.ast.MemberValuePair;
import com.google.devtools.j2objc.ast.MethodDeclaration;
import com.google.devtools.j2objc.ast.Name;
import com.google.devtools.j2objc.ast.NormalAnnotation;
import com.google.devtools.j2objc.ast.PackageDeclaration;
import com.google.devtools.j2objc.ast.PropertyAnnotation;
import com.google.devtools.j2objc.ast.QualifiedName;
import com.google.devtools.j2objc.ast.SimpleName;
import com.google.devtools.j2objc.ast.SingleMemberAnnotation;
import com.google.devtools.j2objc.ast.SingleVariableDeclaration;
import com.google.devtools.j2objc.ast.TreeNode;
import com.google.devtools.j2objc.ast.TreeUtil;
import com.google.devtools.j2objc.ast.Type;
import com.google.devtools.j2objc.ast.TypeDeclaration;
import com.google.devtools.j2objc.file.InputFile;
import com.google.devtools.j2objc.types.GeneratedVariableElement;
import com.google.devtools.j2objc.util.ClassFile;
import com.google.devtools.j2objc.util.ElementUtil;
import com.google.devtools.j2objc.util.ErrorUtil;
import com.google.devtools.j2objc.util.TranslationEnvironment;
import com.google.j2objc.annotations.Property;
import com.strobel.decompiler.languages.java.ast.AstType;
import com.strobel.decompiler.languages.java.ast.EntityDeclaration;
import com.strobel.decompiler.languages.java.ast.ParameterDeclaration;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.tools.StandardLocation;
/**
* Converts a JVM classfile into a CompilationUnit. The resulting unit
* is different from one created from the same source, because several
* modifications made on source files during translation are already
* present in a classfile. These include moving initializers into
* constructors and the class initializer method, extracting inner
* classes, and adding enum support fields and methods.
*
* @author Manvith Narahari
* @author Tom Ball
*/
public class ClassFileConverter {
private final JavacEnvironment parserEnv;
private final TranslationEnvironment translationEnv;
private final InputFile file;
private final ClassFile classFile;
private final String typeName;
public static CompilationUnit convertClassFile(
Options options, JavacEnvironment env, InputFile file) {
try {
env.saveParameterNames();
ClassFileConverter converter = new ClassFileConverter(
env, new TranslationEnvironment(options, env), file);
converter.setClassPath();
return converter.createUnit();
} catch (IOException e) {
ErrorUtil.error(e.getMessage());
return null;
}
}
private ClassFileConverter(JavacEnvironment parserEnv, TranslationEnvironment translationEnv,
InputFile file) throws IOException {
this.parserEnv = parserEnv;
this.translationEnv = translationEnv;
this.file = file;
this.classFile = ClassFile.create(file);
this.typeName = classFile.getFullName();
}
/**
* Set classpath to the root path of the input file, to support typeElement lookup.
*/
private void setClassPath() throws IOException {
String fullPath = file.getAbsolutePath();
String relativePath = classFile.getFullName().replace('.', '/') + ".class";
String rootPath = fullPath.substring(0, fullPath.lastIndexOf(relativePath));
List<File> classPath = new ArrayList<>();
classPath.add(new File(rootPath));
parserEnv.fileManager().setLocation(StandardLocation.CLASS_PATH, classPath);
}
private CompilationUnit createUnit() {
TypeElement typeElement = parserEnv.elementUtilities().getTypeElement(typeName);
if (typeElement == null) {
ErrorUtil.error("Invalid class file: " + file.getOriginalLocation());
}
PackageElement pkgElement = parserEnv.elementUtilities().getPackageOf(typeElement);
if (pkgElement == null) {
pkgElement = parserEnv.defaultPackage();
}
String mainTypeName = typeElement.getSimpleName().toString();
CompilationUnit compUnit = new CompilationUnit(translationEnv, mainTypeName);
compUnit.setPackage((PackageDeclaration) convert(pkgElement, compUnit));
compUnit.addType((AbstractTypeDeclaration) convert(typeElement, compUnit));
return compUnit;
}
@SuppressWarnings("fallthrough")
private TreeNode convert(Element element, TreeNode parent) {
TreeNode node;
switch (element.getKind()) {
case ANNOTATION_TYPE:
node = convertAnnotationTypeDeclaration((TypeElement) element);
break;
case CLASS:
case INTERFACE:
node = convertTypeDeclaration((TypeElement) element);
break;
case CONSTRUCTOR:
case METHOD:
node = convertMethodDeclaration((ExecutableElement) element, (TypeDeclaration) parent);
break;
case ENUM:
node = convertEnumDeclaration((TypeElement) element);
break;
case ENUM_CONSTANT:
node = convertEnumConstantDeclaration((VariableElement) element);
break;
case FIELD:
node = convertFieldDeclaration((VariableElement) element);
break;
case PACKAGE:
node = convertPackage((PackageElement) element);
break;
case PARAMETER:
node = convertParameter((VariableElement) element);
break;
case STATIC_INIT:
node = convertMethodDeclaration((ExecutableElement) element, (TypeDeclaration) parent);
break;
default:
throw new AssertionError("Unsupported element kind: " + element.getKind());
}
return node;
}
private Name convertName(Symbol symbol) {
if (symbol.owner == null || symbol.owner.name.isEmpty()) {
return new SimpleName(symbol);
}
return new QualifiedName(symbol, symbol.asType(), convertName(symbol.owner));
}
private TreeNode convertPackage(PackageElement element) {
return new PackageDeclaration()
.setPackageElement(element)
.setName(convertName((PackageSymbol) element));
}
private BodyDeclaration convertBodyDeclaration(BodyDeclaration newNode, Element element) {
return newNode.setAnnotations(convertAnnotations(element));
}
private void removeInterfaceModifiers(AbstractTypeDeclaration typeDecl) {
typeDecl.removeModifiers(Modifier.PUBLIC | Modifier.ABSTRACT);
for (BodyDeclaration bodyDecl : typeDecl.getBodyDeclarations()) {
bodyDecl.removeModifiers(Modifier.PUBLIC | Modifier.ABSTRACT);
}
}
private AnnotationTypeMemberDeclaration convertAnnotationTypeMemberDeclaration(
ExecutableElement element) {
AnnotationValue annotValue = element.getDefaultValue();
Expression expr = annotValue != null
? convertAnnotationValue(element.getReturnType(), annotValue) : null;
AnnotationTypeMemberDeclaration memberDeclaration =
new AnnotationTypeMemberDeclaration(element).setDefault(expr);
convertBodyDeclaration(memberDeclaration, element);
return memberDeclaration;
}
private TreeNode convertAnnotationTypeDeclaration(TypeElement element) {
AnnotationTypeDeclaration annotTypeDecl = new AnnotationTypeDeclaration(element);
convertBodyDeclaration(annotTypeDecl, element);
for (Element elem : element.getEnclosedElements()) {
BodyDeclaration bodyDecl = elem.getKind() == ElementKind.METHOD
? convertAnnotationTypeMemberDeclaration((ExecutableElement) elem)
: (BodyDeclaration) convert(elem, annotTypeDecl);
annotTypeDecl.addBodyDeclaration(bodyDecl);
}
removeInterfaceModifiers(annotTypeDecl);
return annotTypeDecl;
}
private Expression convertAnnotationValue(TypeMirror type, AnnotationValue annot) {
/* TODO(user): see if the method implements the AnnotationMirror branch correctly */
return translationEnv.translationUtil().createAnnotationValue(type, annot);
}
private Annotation convertAnnotation(AnnotationMirror mirror) {
Map<? extends ExecutableElement, ? extends AnnotationValue> args = mirror.getElementValues();
String annotationName = mirror.getAnnotationType().toString();
Annotation annotation;
if (annotationName.equals(Property.class.getSimpleName())
|| annotationName.equals(Property.class.getName())) {
PropertyAnnotation propAnnot = new PropertyAnnotation();
for (String attr : ElementUtil.parsePropertyAttribute(mirror)) {
propAnnot.addAttribute(attr);
}
annotation = propAnnot;
} else if (args.isEmpty()) {
annotation = new MarkerAnnotation();
} else if (args.size() == 1) {
Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry =
args.entrySet().iterator().next();
annotation = new SingleMemberAnnotation()
.setValue(convertAnnotationValue(entry.getKey().getReturnType(), entry.getValue()));
} else {
NormalAnnotation normalAnnot = new NormalAnnotation();
args.forEach((exec, annot) -> {
MemberValuePair memberPair = new MemberValuePair()
.setName(new SimpleName(exec))
.setValue(convertAnnotationValue(exec.getReturnType(), annot));
normalAnnot.addValue(memberPair);
});
annotation = normalAnnot;
}
return annotation.setAnnotationMirror(mirror)
.setTypeName(new SimpleName(mirror.getAnnotationType().asElement()));
}
private List<Annotation> convertAnnotations(Element element) {
List<Annotation> annotations = new ArrayList<>();
/* TODO(user): inheritance; consider Elements.getAllAnnotationMirrors() */
for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
annotations.add(convertAnnotation(annotationMirror));
}
return annotations;
}
private TreeNode convertTypeDeclaration(TypeElement element) {
TypeDeclaration typeDecl = new TypeDeclaration(element);
convertBodyDeclaration(typeDecl, element);
for (Element elem : element.getEnclosedElements()) {
typeDecl.addBodyDeclaration((BodyDeclaration) convert(elem, typeDecl));
}
if (typeDecl.isInterface()) {
removeInterfaceModifiers(typeDecl);
}
return typeDecl;
}
private String getMethodDescriptor(ExecutableElement exec) {
return translationEnv.typeUtil().getMethodDescriptor((ExecutableType) exec.asType());
}
private TreeNode convertMethodDeclaration(ExecutableElement element, TypeDeclaration node) {
MethodDeclaration methodDecl = new MethodDeclaration(element);
convertBodyDeclaration(methodDecl, element);
List<SingleVariableDeclaration> parameters = methodDecl.getParameters();
String name = element.getSimpleName().toString();
String descriptor = getMethodDescriptor(element);
if (element.getParameters().size() > 0) {
Iterator<ParameterDeclaration> paramsIterator = methodDecl.isConstructor()
? classFile.getConstructor(descriptor).getParameters().iterator()
: classFile.getMethod(name, descriptor).getParameters().iterator();
// If classfile was compiled with -parameters flag; use the MethodNode
// to work around potential javac8 bug iterating over parameter names.
for (VariableElement param : element.getParameters()) {
SingleVariableDeclaration varDecl = (SingleVariableDeclaration) convert(param, methodDecl);
String nameDef = paramsIterator.next().getName();
// If element's name doesn't match the ParameterNode's name, use the latter.
if (!nameDef.equals(param.getSimpleName().toString())) {
param = GeneratedVariableElement.newParameter(nameDef, param.asType(),
param.getEnclosingElement());
varDecl.setVariableElement(param);
}
parameters.add(varDecl);
}
}
if (element.isVarArgs()) {
SingleVariableDeclaration lastParam = parameters.get(parameters.size() - 1);
TypeMirror paramType = lastParam.getType().getTypeMirror();
assert paramType.getKind() == TypeKind.ARRAY;
TypeMirror varArgType = ((ArrayType) paramType).getComponentType();
lastParam.setType(Type.newType(varArgType));
lastParam.setIsVarargs(true);
}
if (!ElementUtil.isAbstract(element)) {
EntityDeclaration decl = methodDecl.isConstructor()
? classFile.getConstructor(descriptor)
: classFile.getMethod(name, descriptor);
MethodTranslator translator = new MethodTranslator(parserEnv, translationEnv, element, node);
methodDecl.setBody((Block) decl.acceptVisitor(translator, null));
}
return methodDecl;
}
private TreeNode convertParameter(VariableElement element) {
return new SingleVariableDeclaration(element).setAnnotations(convertAnnotations(element));
}
private TreeNode convertFieldDeclaration(VariableElement element) {
Object constantValue = element.getConstantValue();
Expression initializer = constantValue != null
? TreeUtil.newLiteral(constantValue, translationEnv.typeUtil()) : null;
FieldDeclaration fieldDecl = new FieldDeclaration(element, initializer);
convertBodyDeclaration(fieldDecl, element);
return fieldDecl;
}
private boolean isEnumSynthetic(Element e, TypeMirror enumType) {
if (e.getKind() == ElementKind.STATIC_INIT) {
return true;
} else if (e.getKind() == ElementKind.METHOD) {
ExecutableElement method = (ExecutableElement) e;
String enumSig = translationEnv.typeUtil().getSignatureName(enumType);
String valueOfDesc = "(Ljava/lang/String;)" + enumSig;
String valuesDesc = "()[" + enumSig;
String name = method.getSimpleName().toString();
String methodDesc = getMethodDescriptor(method);
boolean isValueOf = name.equals("valueOf") && methodDesc.equals(valueOfDesc);
boolean isValues = name.equals("values") && methodDesc.equals(valuesDesc);
return isValueOf || isValues;
}
return false;
}
private TreeNode convertEnumDeclaration(TypeElement element){
EnumDeclaration enumDecl = new EnumDeclaration(element);
convertBodyDeclaration(enumDecl, element);
for (Element elem : element.getEnclosedElements()) {
TreeNode encElem = convert(elem, enumDecl);
if (encElem.getKind() == TreeNode.Kind.ENUM_CONSTANT_DECLARATION) {
enumDecl.addEnumConstant((EnumConstantDeclaration) encElem);
} else if (!isEnumSynthetic(elem, element.asType())) {
enumDecl.addBodyDeclaration((BodyDeclaration) encElem);
}
}
enumDecl.removeModifiers(Modifier.FINAL);
return enumDecl;
}
private TreeNode convertEnumConstantDeclaration(VariableElement element) {
EnumConstantDeclaration enumConstDecl = new EnumConstantDeclaration(element);
convertBodyDeclaration(enumConstDecl, element);
/* TODO(user): set ExecutablePair */
return enumConstDecl;
}
private TypeElement resolve(AstType type) {
String fqn = type.toTypeReference().getErasedSignature();
Element element = parserEnv.resolve(fqn);
if (element == null || !(element instanceof TypeElement)) {
throw new AssertionError("failed resolving type: " + fqn);
}
return (TypeElement) element;
}
}