/
InitializationNormalizer.java
208 lines (189 loc) · 7.81 KB
/
InitializationNormalizer.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
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* 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.translate;
import com.google.common.collect.Lists;
import com.google.devtools.j2objc.ast.AbstractTypeDeclaration;
import com.google.devtools.j2objc.ast.AnnotationTypeDeclaration;
import com.google.devtools.j2objc.ast.Assignment;
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.ConstructorInvocation;
import com.google.devtools.j2objc.ast.EnumDeclaration;
import com.google.devtools.j2objc.ast.ExpressionStatement;
import com.google.devtools.j2objc.ast.FieldDeclaration;
import com.google.devtools.j2objc.ast.Initializer;
import com.google.devtools.j2objc.ast.MethodDeclaration;
import com.google.devtools.j2objc.ast.SimpleName;
import com.google.devtools.j2objc.ast.Statement;
import com.google.devtools.j2objc.ast.SuperConstructorInvocation;
import com.google.devtools.j2objc.ast.TreeUtil;
import com.google.devtools.j2objc.ast.TypeDeclaration;
import com.google.devtools.j2objc.ast.UnitTreeVisitor;
import com.google.devtools.j2objc.ast.VariableDeclarationFragment;
import com.google.devtools.j2objc.util.CaptureInfo;
import com.google.devtools.j2objc.util.ElementUtil;
import com.google.devtools.j2objc.util.TypeUtil;
import com.google.devtools.j2objc.util.UnicodeUtils;
import java.util.Iterator;
import java.util.List;
import javax.lang.model.element.TypeElement;
import org.eclipse.jdt.core.dom.Modifier;
/**
* Modifies initializers to be more iOS like. Static initializers are
* combined into a static initialize method, instance initializer
* statements are injected into constructors. If a class doesn't have
* any constructors but does have instance initialization statements,
* a default constructor is added to run them.
*
* @author Tom Ball
*/
public class InitializationNormalizer extends UnitTreeVisitor {
private final CaptureInfo captureInfo;
public InitializationNormalizer(CompilationUnit unit) {
super(unit);
captureInfo = unit.getEnv().captureInfo();
}
@Override
public void endVisit(TypeDeclaration node) {
normalizeMembers(node);
}
@Override
public void endVisit(EnumDeclaration node) {
normalizeMembers(node);
}
@Override
public void endVisit(AnnotationTypeDeclaration node) {
normalizeMembers(node);
}
void normalizeMembers(AbstractTypeDeclaration node) {
TypeElement type = node.getTypeElement();
List<Statement> initStatements = Lists.newArrayList();
List<Statement> classInitStatements = node.getClassInitStatements();
// Scan class, gathering initialization statements in declaration order.
Iterator<BodyDeclaration> iterator = node.getBodyDeclarations().iterator();
while (iterator.hasNext()) {
BodyDeclaration member = iterator.next();
switch (member.getKind()) {
case INITIALIZER:
addInitializer((Initializer) member, initStatements, classInitStatements);
iterator.remove();
break;
case FIELD_DECLARATION:
addFieldInitializer((FieldDeclaration) member, initStatements, classInitStatements);
break;
default:
// Fall-through.
}
}
// Update any primary constructors with init statements.
if (type.getKind().isClass()) {
for (MethodDeclaration methodDecl : TreeUtil.getMethodDeclarations(node)) {
if (isDesignatedConstructor(methodDecl)) {
TreeUtil.copyList(initStatements, getInitLocation(methodDecl));
addCaptureAssignments(methodDecl, type);
}
}
}
}
/**
* Add a static or instance init block's statements to the appropriate list
* of initialization statements.
*/
private void addInitializer(Initializer initializer, List<Statement> initStatements,
List<Statement> classInitStatements) {
List<Statement> list =
Modifier.isStatic(initializer.getModifiers()) ? classInitStatements : initStatements;
list.add(TreeUtil.remove(initializer.getBody()));
}
/**
* Strip field initializers, convert them to assignment statements, and
* add them to the appropriate list of initialization statements.
*/
private void addFieldInitializer(
FieldDeclaration field, List<Statement> initStatements, List<Statement> classInitStatements) {
for (VariableDeclarationFragment frag : field.getFragments()) {
if (frag.getInitializer() != null) {
if (ElementUtil.isInstanceVar(frag.getVariableElement())) {
// always initialize instance variables, since they can't be constants
initStatements.add(makeAssignmentStatement(frag));
} else if (requiresInitializer(frag)) {
classInitStatements.add(makeAssignmentStatement(frag));
}
}
}
}
/**
* Determines if a variable declaration requires initialization. (ie. cannot
* be assigned to a literal value in ObjC.
*/
private boolean requiresInitializer(VariableDeclarationFragment frag) {
// If the initializer is not a literal, but has a constant value, convert it
// to a literal. (as javac would do)
Object constantValue = frag.getInitializer().getConstantValue();
if (constantValue != null) {
if (constantValue instanceof String
&& !UnicodeUtils.hasValidCppCharacters((String) constantValue)) {
return true;
}
frag.setInitializer(TreeUtil.newLiteral(constantValue, typeUtil));
return false;
}
return true;
}
private ExpressionStatement makeAssignmentStatement(VariableDeclarationFragment fragment) {
return new ExpressionStatement(new Assignment(
new SimpleName(fragment.getVariableElement()), TreeUtil.remove(fragment.getInitializer())));
}
/**
* Finds the location in a constructor where init statements should be added.
*/
private List<Statement> getInitLocation(MethodDeclaration node) {
List<Statement> stmts = node.getBody().getStatements();
if (!stmts.isEmpty() && stmts.get(0) instanceof SuperConstructorInvocation) {
return stmts.subList(0, 1);
}
// java.lang.Object supertype is null. All other types should have a super() call.
assert TypeUtil.isNone(
ElementUtil.getDeclaringClass(node.getExecutableElement()).getSuperclass())
: "Constructor didn't have a super() call.";
return stmts.subList(0, 0);
}
private void addCaptureAssignments(MethodDeclaration constructor, TypeElement type) {
List<Statement> statements = constructor.getBody().getStatements().subList(0, 0);
for (CaptureInfo.Capture capture : captureInfo.getCaptures(type)) {
if (capture.hasField()) {
statements.add(new ExpressionStatement(new Assignment(
new SimpleName(capture.getField()), new SimpleName(capture.getParam()))));
}
}
}
/**
* Returns true if this is a constructor that doesn't call "this(...)". This constructors are
* skipped so initializers aren't run more than once per instance creation.
*/
public static boolean isDesignatedConstructor(MethodDeclaration node) {
if (!node.isConstructor()) {
return false;
}
Block body = node.getBody();
if (body == null) {
return false;
}
List<Statement> stmts = body.getStatements();
return (stmts.isEmpty() || !(stmts.get(0) instanceof ConstructorInvocation));
}
}