-
Notifications
You must be signed in to change notification settings - Fork 960
/
TypeImplementationGenerator.java
378 lines (347 loc) · 13.5 KB
/
TypeImplementationGenerator.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
/*
* 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.gen;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.devtools.j2objc.ast.AbstractTypeDeclaration;
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.FunctionDeclaration;
import com.google.devtools.j2objc.ast.MethodDeclaration;
import com.google.devtools.j2objc.ast.NativeDeclaration;
import com.google.devtools.j2objc.ast.SingleVariableDeclaration;
import com.google.devtools.j2objc.ast.Statement;
import com.google.devtools.j2objc.ast.VariableDeclarationFragment;
import com.google.devtools.j2objc.util.ElementUtil;
import com.google.devtools.j2objc.util.NameTable;
import com.google.devtools.j2objc.util.TypeUtil;
import com.google.j2objc.annotations.Property;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
/**
* Generates implementation code for an AbstractTypeDeclaration node.
*
* @author Tom Ball, Keith Stanger
*/
public class TypeImplementationGenerator extends TypeGenerator {
private static final ImmutableSet<String> NSNUMBER_DESIGNATED_INITIALIZERS = ImmutableSet.of(
"initWithBool:",
"initWithChar:",
"initWithDouble:",
"initWithFloat:",
"initWithInt:",
"initWithInteger:",
"initWithLong:",
"initWithLongLong:",
"initWithShort:",
"initWithUnsignedChar:",
"initWithUnsignedInt:",
"initWithUnsignedInteger:",
"initWithUnsignedLong:",
"initWithUnsignedLongLong:",
"initWithUnsignedShort:");
private TypeImplementationGenerator(SourceBuilder builder, AbstractTypeDeclaration node) {
super(builder, node);
}
public static void generate(SourceBuilder builder, AbstractTypeDeclaration node) {
new TypeImplementationGenerator(builder, node).generate();
}
protected void generate() {
if (typeNode.isDeadClass()) {
newline();
printStaticVars();
return;
}
syncFilename(compilationUnit.getSourceFilePath());
printInitFlagDefinition();
printStaticVars();
printEnumValuesArray();
if (!typeElement.getKind().isInterface() || needsCompanionClass()) {
newline();
syncLineNumbers(typeNode.getName()); // avoid doc-comment
printf("@implementation %s\n", typeName);
printProperties();
printStaticAccessors();
printInnerDeclarations();
printInitializeMethod();
println("\n@end");
}
printOuterDeclarations();
printTypeLiteralImplementation();
printNameMapping();
}
private void printInitFlagDefinition() {
if (hasInitializeMethod()) {
printf("\nJ2OBJC_INITIALIZED_DEFN(%s)\n", typeName);
}
}
private static final Predicate<VariableDeclarationFragment> PROPERTIES =
new Predicate<VariableDeclarationFragment>() {
@Override
public boolean apply(VariableDeclarationFragment fragment) {
VariableElement varElement = fragment.getVariableElement();
return ElementUtil.hasAnnotation(varElement, Property.class)
&& !ElementUtil.isStatic(varElement);
}
};
private void printProperties() {
Iterable<VariableDeclarationFragment> fields =
Iterables.filter(getInstanceFields(), PROPERTIES);
if (Iterables.isEmpty(fields)) {
return;
}
newline();
for (VariableDeclarationFragment fragment : fields) {
VariableElement varElement = fragment.getVariableElement();
String propertyName = nameTable.getVariableBaseName(varElement);
String varName = nameTable.getVariableShortName(varElement);
println("@synthesize " + propertyName + " = " + varName + ";");
}
}
private static final Predicate<VariableDeclarationFragment> NEEDS_DEFINITION =
new Predicate<VariableDeclarationFragment>() {
@Override
public boolean apply(VariableDeclarationFragment fragment) {
return !ElementUtil.isPrimitiveConstant(fragment.getVariableElement())
// Private static vars are defined in the private declaration.
&& !((FieldDeclaration) fragment.getParent()).hasPrivateDeclaration();
}
};
private void printStaticVars() {
Iterable<VariableDeclarationFragment> fields =
Iterables.filter(getStaticFields(), NEEDS_DEFINITION);
if (Iterables.isEmpty(fields)) {
return;
}
newline();
for (VariableDeclarationFragment fragment : fields) {
VariableElement varElement = fragment.getVariableElement();
Expression initializer = fragment.getInitializer();
String name = nameTable.getVariableQualifiedName(varElement);
String objcType = getDeclarationType(varElement);
objcType += objcType.endsWith("*") ? "" : " ";
if (initializer != null) {
String cast = !varElement.asType().getKind().isPrimitive()
&& ElementUtil.isVolatile(varElement) ? "(void *)" : "";
printf("%s%s = %s%s;\n", objcType, name, cast, generateExpression(initializer));
} else {
printf("%s%s;\n", objcType, name);
}
}
}
/**
* Prints the list of static variable and/or enum constant accessor methods.
*/
protected void printStaticAccessors() {
if (!options.staticAccessorMethods()) {
return;
}
for (VariableDeclarationFragment fragment : getStaticFields()) {
if (!((FieldDeclaration) fragment.getParent()).hasPrivateDeclaration()) {
VariableElement varElement = fragment.getVariableElement();
TypeMirror type = varElement.asType();
boolean isVolatile = ElementUtil.isVolatile(varElement);
boolean isPrimitive = type.getKind().isPrimitive();
String accessorName = nameTable.getStaticAccessorName(varElement);
String varName = nameTable.getVariableQualifiedName(varElement);
String objcType = nameTable.getObjCType(type);
String typeSuffix = isPrimitive ? NameTable.capitalize(TypeUtil.getName(type)) : "Id";
TypeElement declaringClass = ElementUtil.getDeclaringClass(varElement);
String baseName = nameTable.getVariableBaseName(varElement);
ExecutableElement getter = ElementUtil.findGetterMethod(baseName, type, declaringClass);
if (getter == null) {
if (isVolatile) {
printf(
"\n+ (%s)%s {\n return JreLoadVolatile%s(&%s);\n}\n",
objcType, accessorName, typeSuffix, varName);
} else {
printf("\n+ (%s)%s {\n return %s;\n}\n", objcType, accessorName, varName);
}
}
ExecutableElement setter = ElementUtil.findSetterMethod(baseName, type, declaringClass);
if (setter == null && !ElementUtil.isFinal(varElement)) {
String setterFunc = isVolatile
? (isPrimitive ? "JreAssignVolatile" + typeSuffix : "JreVolatileStrongAssign")
: (isPrimitive | options.useARC() ? null : "JreStrongAssign");
if (setterFunc == null) {
printf("\n+ (void)set%s:(%s)value {\n %s = value;\n}\n",
NameTable.capitalize(accessorName), objcType, varName);
} else {
printf("\n+ (void)set%s:(%s)value {\n %s(&%s, value);\n}\n",
NameTable.capitalize(accessorName), objcType, setterFunc, varName);
}
}
}
}
if (typeNode instanceof EnumDeclaration) {
for (EnumConstantDeclaration constant : ((EnumDeclaration) typeNode).getEnumConstants()) {
VariableElement varElement = constant.getVariableElement();
printf("\n+ (%s *)%s {\n return %s;\n}\n",
typeName, nameTable.getStaticAccessorName(varElement),
nameTable.getVariableQualifiedName(varElement));
}
}
}
private void printEnumValuesArray() {
if (typeNode instanceof EnumDeclaration) {
List<EnumConstantDeclaration> constants = ((EnumDeclaration) typeNode).getEnumConstants();
newline();
printf("%s *%s_values_[%s];\n", typeName, typeName, constants.size());
}
}
private void printTypeLiteralImplementation() {
if (needsTypeLiteral()) {
newline();
printf("J2OBJC_%s_TYPE_LITERAL_SOURCE(%s)\n",
isInterfaceType() ? "INTERFACE" : "CLASS", typeName);
}
}
private void printNameMapping() {
if (!options.stripNameMapping()) {
Optional<String> mapping = nameTable.getNameMapping(typeElement, typeName);
if (mapping.isPresent()) {
newline();
printf(mapping.get());
}
}
}
private boolean isDesignatedInitializer(ExecutableElement method) {
if (!ElementUtil.isConstructor(method)) {
return false;
}
String selector = nameTable.getMethodSelector(method);
return selector.equals("init")
|| (typeUtil.isObjcSubtype(ElementUtil.getDeclaringClass(method), TypeUtil.NS_NUMBER)
&& NSNUMBER_DESIGNATED_INITIALIZERS.contains(selector));
}
@Override
protected void printMethodDeclaration(MethodDeclaration m) {
if (Modifier.isAbstract(m.getModifiers())) {
return;
}
newline();
boolean isDesignatedInitializer = isDesignatedInitializer(m.getExecutableElement());
if (isDesignatedInitializer) {
println("J2OBJC_IGNORE_DESIGNATED_BEGIN");
}
syncLineNumbers(m); // avoid doc-comment
String methodBody = generateStatement(m.getBody());
print(getMethodSignature(m) + " " + reindent(methodBody) + "\n");
if (isDesignatedInitializer) {
println("J2OBJC_IGNORE_DESIGNATED_END");
}
}
@Override
protected void printFunctionDeclaration(FunctionDeclaration function) {
newline();
syncLineNumbers(function); // avoid doc-comment
if (Modifier.isNative(function.getModifiers())) {
printJniFunctionAndWrapper(function);
} else {
String functionBody = generateStatement(function.getBody());
println(getFunctionSignature(function, false) + " " + reindent(functionBody));
}
}
private String getJniFunctionSignature(FunctionDeclaration function) {
StringBuilder sb = new StringBuilder();
sb.append(nameTable.getJniType(function.getReturnType().getTypeMirror()));
sb.append(' ');
sb.append(function.getJniSignature()).append('(');
sb.append("JNIEnv *_env_");
if (Modifier.isStatic(function.getModifiers())) {
sb.append(", jclass _cls_");
}
if (!function.getParameters().isEmpty()) {
sb.append(", ");
}
for (Iterator<SingleVariableDeclaration> iter = function.getParameters().iterator();
iter.hasNext(); ) {
VariableElement var = iter.next().getVariableElement();
String paramType = nameTable.getJniType(var.asType());
sb.append(paramType + ' ' + nameTable.getVariableBaseName(var));
if (iter.hasNext()) {
sb.append(", ");
}
}
sb.append(')');
return sb.toString();
}
private void printJniFunctionAndWrapper(FunctionDeclaration function) {
// Declare the matching JNI function.
print("JNIEXPORT ");
print(getJniFunctionSignature(function));
println(";\n");
// Generate a wrapper function that calls the matching JNI function.
print(getFunctionSignature(function, false));
println(" {");
print(" ");
TypeMirror returnType = function.getReturnType().getTypeMirror();
if (!TypeUtil.isVoid(returnType)) {
if (returnType.getKind().isPrimitive()) {
print("return ");
} else {
printf("return (%s) ", nameTable.getObjCType(returnType));
}
}
print(function.getJniSignature());
print("(&J2ObjC_JNIEnv");
if (Modifier.isStatic(function.getModifiers())) {
printf(", %s_class_()", typeName);
}
for (SingleVariableDeclaration param : function.getParameters()) {
printf(", %s", nameTable.getVariableBaseName(param.getVariableElement()));
}
println(");");
println("}");
}
@Override
protected void printNativeDeclaration(NativeDeclaration declaration) {
String code = declaration.getImplementationCode();
if (code != null) {
newline();
println(reindent(code));
}
}
private void printInitializeMethod() {
List<Statement> initStatements = typeNode.getClassInitStatements();
if (initStatements.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("{\nif (self == [" + typeName + " class]) {\n");
for (Statement statement : initStatements) {
sb.append(generateStatement(statement));
}
sb.append("J2OBJC_SET_INITIALIZED(" + typeName + ")\n");
sb.append("}\n}");
print("\n+ (void)initialize " + reindent(sb.toString()) + "\n");
}
protected String generateStatement(Statement stmt) {
return StatementGenerator.generate(stmt, getBuilder().getCurrentLine());
}
@Override
protected String nullability(Element element) {
return "";
}
}