| 1 |
/* |
| 2 |
* Copyright (C) 2015 The Android Open Source Project |
| 3 |
* |
| 4 |
* Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
* you may not use this file except in compliance with the License. |
| 6 |
* You may obtain a copy of the License at |
| 7 |
* |
| 8 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
* |
| 10 |
* Unless required by applicable law or agreed to in writing, software |
| 11 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
* See the License for the specific language governing permissions and |
| 14 |
* limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package com.android.tools.chunkio.processor; |
| 18 |
|
| 19 |
import com.android.tools.chunkio.Chunk; |
| 20 |
import com.android.tools.chunkio.ChunkUtils; |
| 21 |
import com.android.tools.chunkio.RangedInputStream; |
| 22 |
import com.android.tools.chunkio.codegen.ClassDef; |
| 23 |
import com.android.tools.chunkio.codegen.JavaFile; |
| 24 |
import com.android.tools.chunkio.reader.ArrayChunkReader; |
| 25 |
import com.android.tools.chunkio.reader.ChunkReader; |
| 26 |
import com.android.tools.chunkio.reader.CollectionChunkReader; |
| 27 |
import com.android.tools.chunkio.reader.DynamicTypeChunkReader; |
| 28 |
import com.android.tools.chunkio.reader.EnumChunkReader; |
| 29 |
import com.android.tools.chunkio.codegen.MethodDef; |
| 30 |
import com.android.tools.chunkio.codegen.TypeDef; |
| 31 |
import com.android.tools.chunkio.reader.PrimitiveChunkReader; |
| 32 |
|
| 33 |
import javax.annotation.processing.Filer; |
| 34 |
import javax.lang.model.element.Modifier; |
| 35 |
import javax.lang.model.element.TypeElement; |
| 36 |
import javax.lang.model.type.MirroredTypeException; |
| 37 |
import javax.lang.model.type.MirroredTypesException; |
| 38 |
import javax.lang.model.type.TypeMirror; |
| 39 |
import javax.lang.model.type.TypeVisitor; |
| 40 |
import javax.lang.model.util.Elements; |
| 41 |
import javax.tools.JavaFileObject; |
| 42 |
import java.io.IOException; |
| 43 |
import java.io.Writer; |
| 44 |
import java.util.Arrays; |
| 45 |
import java.util.EnumSet; |
| 46 |
import java.util.LinkedList; |
| 47 |
import java.util.List; |
| 48 |
|
| 49 |
public class ClassEmitter { |
| 50 |
private final TypeElement typeElement; |
| 51 |
|
| 52 |
private final Elements elementUtils; |
| 53 |
private final ErrorHandler errorHandler; |
| 54 |
private final Filer filer; |
| 55 |
private final TypeVisitor<ChunkReader, Void> typeVisitor; |
| 56 |
|
| 57 |
public ClassEmitter(TypeElement typeElement, Environment environment) { |
| 58 |
this.typeElement = typeElement; |
| 59 |
elementUtils = environment.elementUtils; |
| 60 |
errorHandler = environment.errorHandler; |
| 61 |
filer = environment.filer; |
| 62 |
typeVisitor = environment.typeElementVisitor; |
| 63 |
} |
| 64 |
|
| 65 |
public void emit() { |
| 66 |
// Find all annotated fields in the class |
| 67 |
List<FieldChunk> chunks = new ChunksCollector(typeElement, errorHandler).collect(); |
| 68 |
ClassName className = ClassName.from(typeElement, elementUtils); |
| 69 |
emitCode(chunks, className); |
| 70 |
} |
| 71 |
|
| 72 |
private void emitCode(List<FieldChunk> chunks, ClassName className) { |
| 73 |
try { |
| 74 |
ClassDef classDef = createClass(chunks, className); |
| 75 |
JavaFile javaFile = JavaFile.builder(className.packageName, classDef).build(); |
| 76 |
writeCodeToFile(className, javaFile); |
| 77 |
} catch (Exception e) { |
| 78 |
errorHandler.error(typeElement, |
| 79 |
"Code generation failed with exception: %s", Utils.stackTraceToString(e)); |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
private void writeCodeToFile(ClassName className, JavaFile javaFile) |
| 84 |
throws IOException { |
| 85 |
JavaFileObject sourceFile = filer.createSourceFile(className.qualifiedName); |
| 86 |
Writer writer = sourceFile.openWriter(); |
| 87 |
javaFile.emit(writer); |
| 88 |
writer.close(); |
| 89 |
} |
| 90 |
|
| 91 |
private ClassDef createClass(List<FieldChunk> chunks, ClassName className) { |
| 92 |
return ClassDef.builder(className.className) |
| 93 |
.modifiers(EnumSet.of(Modifier.FINAL)) |
| 94 |
.addMethod(generateMethod(typeElement, chunks, className)) |
| 95 |
.build(); |
| 96 |
} |
| 97 |
|
| 98 |
/** |
| 99 |
* Creates the read() method that will be emitted in the generated source file. |
| 100 |
* The method has the following signature: |
| 101 |
* <pre> |
| 102 |
* static T read(DataInputStream in, LinkedList<Object> stack) |
| 103 |
* </pre> |
| 104 |
* Where T is an actual type. |
| 105 |
*/ |
| 106 |
private static MethodDef.Builder createReadMethod(TypeDef type) { |
| 107 |
return MethodDef.builder("read") |
| 108 |
.modifiers(EnumSet.of(Modifier.STATIC)) |
| 109 |
.addParameter(RangedInputStream.class, "in") |
| 110 |
.addParameter(StackType.class.getGenericSuperclass(), "stack") |
| 111 |
.throwsException(IOException.class) |
| 112 |
.returns(type); |
| 113 |
} |
| 114 |
|
| 115 |
private MethodDef generateMethod(TypeElement typeElement, List<FieldChunk> chunks, |
| 116 |
ClassName className) { |
| 117 |
TypeDef type = TypeDef.fromClass(className.packageName, className.sourceName); |
| 118 |
String name = Utils.variableName(typeElement.getSimpleName().toString()); |
| 119 |
|
| 120 |
MethodDef.Builder builder = createReadMethod(type); |
| 121 |
emitMethodPrologue(type, builder, name); |
| 122 |
|
| 123 |
for (FieldChunk chunk : chunks) { |
| 124 |
ChunkReader reader = chunk.type.accept(typeVisitor, null); |
| 125 |
if (reader == null) { |
| 126 |
errorReaderNotFound(typeElement, chunk); |
| 127 |
continue; |
| 128 |
} |
| 129 |
|
| 130 |
boolean hasReadCondition = emitReadConditionStart(builder, chunk); |
| 131 |
if (hasTypeSwitch(chunk, reader)) { |
| 132 |
emitSwitchedRead(builder, name, chunk, reader, typeElement); |
| 133 |
} else { |
| 134 |
emitRead(builder, name, chunk, reader); |
| 135 |
} |
| 136 |
emitDebug(type, builder, name, chunk); |
| 137 |
emitMatchTest(builder, name, chunk, reader); |
| 138 |
emitStopCondition(builder, name, chunk); |
| 139 |
emitReadConditionEnd(builder, hasReadCondition); |
| 140 |
} |
| 141 |
|
| 142 |
emitMethodEpilogue(builder, name); |
| 143 |
return builder.build(); |
| 144 |
} |
| 145 |
|
| 146 |
private void emitSwitchedRead(MethodDef.Builder builder, String name, |
| 147 |
FieldChunk chunk, ChunkReader reader, TypeElement typeElement) { |
| 148 |
boolean first = true; |
| 149 |
Chunk.Case[] tests = chunk.chunk.switchType(); |
| 150 |
|
| 151 |
String dottedName = name + '.'; |
| 152 |
if (chunk.hasDynamicByteCount()) { |
| 153 |
emitDynamicByteCount(builder, chunk); |
| 154 |
} |
| 155 |
reader.emitPrologue(builder, dottedName, chunk); |
| 156 |
|
| 157 |
for (Chunk.Case test : tests) { |
| 158 |
TypeMirror typeMirror = typeFromTest(test); |
| 159 |
|
| 160 |
ChunkReader switchedReader = typeMirror.accept(typeVisitor, null); |
| 161 |
if (switchedReader == null) { |
| 162 |
errorReaderNotFound(typeElement, chunk); |
| 163 |
continue; |
| 164 |
} |
| 165 |
|
| 166 |
if (first) { |
| 167 |
builder.beginControlStatement("if ($L)", test.test()); |
| 168 |
first = false; |
| 169 |
} else { |
| 170 |
builder.continueControlStatement("else if ($L)", test.test()); |
| 171 |
} |
| 172 |
|
| 173 |
if (chunk.hasDynamicByteCount()) { |
| 174 |
switchedReader.emitDynamicRead(builder, dottedName, chunk); |
| 175 |
} else { |
| 176 |
switchedReader.emitRead(builder, dottedName, chunk); |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
if (!first) { |
| 181 |
builder.endControlStatement(); |
| 182 |
} |
| 183 |
reader.emitEpilogue(builder, dottedName, chunk); |
| 184 |
} |
| 185 |
|
| 186 |
private static void emitReadConditionEnd(MethodDef.Builder builder, boolean hasReadCondition) { |
| 187 |
if (hasReadCondition) { |
| 188 |
builder.endControlStatement(); |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
private static boolean emitReadConditionStart(MethodDef.Builder builder, FieldChunk chunk) { |
| 193 |
boolean readIf = !chunk.readIf().isEmpty(); |
| 194 |
if (readIf) { |
| 195 |
Object[] params; |
| 196 |
try { |
| 197 |
params = chunk.readIfParams(); |
| 198 |
} catch (MirroredTypesException e) { |
| 199 |
params = typesFromException(e); |
| 200 |
} |
| 201 |
builder.beginControlStatement("if (" + chunk.readIf() + ")", params); |
| 202 |
} |
| 203 |
return readIf; |
| 204 |
} |
| 205 |
private void emitRead(MethodDef.Builder builder, String name, FieldChunk chunk, |
| 206 |
ChunkReader reader) { |
| 207 |
if (reader instanceof CollectionChunkReader) { |
| 208 |
emitCollectionRead(name, builder, chunk, reader); |
| 209 |
} else { |
| 210 |
emitSingleRead(name, builder, chunk, reader); |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
private static void emitSingleRead(String name, MethodDef.Builder builder, |
| 215 |
FieldChunk chunk, ChunkReader reader) { |
| 216 |
String dottedName = name + '.'; |
| 217 |
if (chunk.hasDynamicByteCount()) { |
| 218 |
emitDynamicByteCount(builder, chunk); |
| 219 |
|
| 220 |
reader.emitPrologue(builder, dottedName, chunk); |
| 221 |
reader.emitDynamicRead(builder, dottedName, chunk); |
| 222 |
reader.emitEpilogue(builder, dottedName, chunk); |
| 223 |
} else { |
| 224 |
reader.emitPrologue(builder, dottedName, chunk); |
| 225 |
reader.emitRead(builder, dottedName, chunk); |
| 226 |
reader.emitEpilogue(builder, dottedName, chunk); |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
private void emitCollectionRead(String name, MethodDef.Builder builder, |
| 231 |
FieldChunk chunk, ChunkReader reader) { |
| 232 |
String dottedName = name + '.'; |
| 233 |
CollectionChunkReader collectionReader = (CollectionChunkReader) reader; |
| 234 |
|
| 235 |
TypeMirror elementType = collectionReader.getElementType(); |
| 236 |
String elementName = Utils.variableName(TypeDef.of(elementType).getSimpleName()); |
| 237 |
ChunkReader elementReader = elementType.accept(typeVisitor, null); |
| 238 |
|
| 239 |
reader.emitRead(builder, dottedName, chunk); |
| 240 |
|
| 241 |
if (chunk.hasSize()) { |
| 242 |
emitSize(builder, chunk); |
| 243 |
} else { |
| 244 |
emitByteCount(builder, chunk); |
| 245 |
} |
| 246 |
|
| 247 |
reader.emitPrologue(builder, "", chunk); |
| 248 |
builder.addStatement("$T $L", elementType, elementName); |
| 249 |
|
| 250 |
if (chunk.hasSize()) { |
| 251 |
builder.beginControlStatement("for (int i = 0; i < size; i++)"); |
| 252 |
} else { |
| 253 |
builder.beginControlStatement("while (in.available() > 0)"); |
| 254 |
} |
| 255 |
|
| 256 |
elementReader.emitRead(builder, "", chunk.derive(elementName)); |
| 257 |
|
| 258 |
collectionReader.pushElement(builder, dottedName, chunk, elementName); |
| 259 |
builder.endControlStatement(); |
| 260 |
|
| 261 |
reader.emitEpilogue(builder, "", chunk); |
| 262 |
} |
| 263 |
|
| 264 |
private static void emitByteCount(MethodDef.Builder builder, FieldChunk chunk) { |
| 265 |
if (chunk.hasDynamicByteCount()) { |
| 266 |
emitDynamicByteCount(builder, chunk); |
| 267 |
} else if (chunk.byteCount() > 0) { |
| 268 |
builder.addStatement("byteCount = $L", chunk.byteCount()); |
| 269 |
} |
| 270 |
} |
| 271 |
|
| 272 |
private static void emitDynamicByteCount(MethodDef.Builder builder, FieldChunk chunk) { |
| 273 |
Object[] params; |
| 274 |
try { |
| 275 |
params = chunk.byteCountParams(); |
| 276 |
} catch (MirroredTypesException e) { |
| 277 |
params = typesFromException(e); |
| 278 |
} |
| 279 |
emitAssignment(builder, chunk.dynamicByteCount(), params, "byteCount = "); |
| 280 |
} |
| 281 |
|
| 282 |
private static void emitSize(MethodDef.Builder builder, FieldChunk chunk) { |
| 283 |
if (chunk.hasDynamicSize()) { |
| 284 |
emitDynamicSize(builder, chunk); |
| 285 |
} else { |
| 286 |
builder.addStatement("size = $L", chunk.size()); |
| 287 |
} |
| 288 |
} |
| 289 |
|
| 290 |
private static void emitDynamicSize(MethodDef.Builder builder, FieldChunk chunk) { |
| 291 |
Object[] params; |
| 292 |
try { |
| 293 |
params = chunk.sizeParams(); |
| 294 |
} catch (MirroredTypesException e) { |
| 295 |
params = typesFromException(e); |
| 296 |
} |
| 297 |
emitAssignment(builder, chunk.dynamicSize(), params, "size = "); |
| 298 |
} |
| 299 |
|
| 300 |
private static void emitAssignment(MethodDef.Builder builder, String dynamic, |
| 301 |
Object[] params, String name) { |
| 302 |
if (Utils.isMultiline(dynamic)) { |
| 303 |
builder.beginBlock(); |
| 304 |
builder.addStatement(dynamic, params); |
| 305 |
builder.endBlock(); |
| 306 |
} else { |
| 307 |
builder.add(name); |
| 308 |
builder.addStatement(dynamic, params); |
| 309 |
} |
| 310 |
} |
| 311 |
|
| 312 |
/** |
| 313 |
* Emits a simple System.out.println() for a given field. |
| 314 |
*/ |
| 315 |
private static void emitDebug(TypeDef type, MethodDef.Builder builder, String name, |
| 316 |
FieldChunk chunk) { |
| 317 |
if (chunk.debug()) { |
| 318 |
builder.addStatement("System.out.println(\"$T.$L = \" + $L.$L)", |
| 319 |
type, chunk.name, name, chunk.name); |
| 320 |
} |
| 321 |
} |
| 322 |
|
| 323 |
/** |
| 324 |
* Emits the code that compares the read field to a given expression |
| 325 |
* and throws an exception in case of failure. |
| 326 |
*/ |
| 327 |
private static void emitMatchTest(MethodDef.Builder builder, String name, |
| 328 |
FieldChunk chunk, ChunkReader reader) { |
| 329 |
if (!chunk.match().isEmpty()) { |
| 330 |
builder.add("$T.checkState(", ChunkUtils.class); |
| 331 |
emitMatchExpression(builder, name, chunk, reader); |
| 332 |
builder.addStatement(",\n$S)", |
| 333 |
"Value read in " + chunk.name + " does not match expected value"); |
| 334 |
} |
| 335 |
} |
| 336 |
|
| 337 |
/** |
| 338 |
* Emits the match expression for the specified reader. |
| 339 |
* An array will match using Arrays.equals(), primitives and enums using == |
| 340 |
* and other types with Object.equals(). |
| 341 |
*/ |
| 342 |
private static void emitMatchExpression(MethodDef.Builder builder, String name, |
| 343 |
FieldChunk chunk, ChunkReader reader) { |
| 344 |
if (reader instanceof PrimitiveChunkReader || reader instanceof EnumChunkReader) { |
| 345 |
builder.add("$L.$L == ($L)", name, chunk.name, chunk.match()); |
| 346 |
} else if (reader instanceof ArrayChunkReader) { |
| 347 |
builder.add("$T.equals($L.$L, ($L))", Arrays.class, name, |
| 348 |
chunk.name, chunk.match()); |
| 349 |
} else { |
| 350 |
builder.add("$L.$L.equals($L)", name, chunk.name, chunk.match()); |
| 351 |
} |
| 352 |
} |
| 353 |
|
| 354 |
/** |
| 355 |
* Emits the code that stops reading from the stream if a condition |
| 356 |
* is met. |
| 357 |
*/ |
| 358 |
private static void emitStopCondition(MethodDef.Builder builder, String name, |
| 359 |
FieldChunk chunk) { |
| 360 |
if (!chunk.stopIf().isEmpty()) { |
| 361 |
Object[] params; |
| 362 |
try { |
| 363 |
params = chunk.stopIfParams(); |
| 364 |
} catch (MirroredTypesException e) { |
| 365 |
params = typesFromException(e); |
| 366 |
} |
| 367 |
builder.beginControlStatement("if (" + chunk.stopIf() + ")", params); |
| 368 |
builder.addStatement("stack.removeFirst()"); |
| 369 |
builder.addStatement("return $L", name); |
| 370 |
builder.endControlStatement(); |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
/** |
| 375 |
* Emits the read() method epilogue. It pops the instance we created |
| 376 |
* off the stack and returns that instance. |
| 377 |
*/ |
| 378 |
private static void emitMethodEpilogue(MethodDef.Builder builder, String name) { |
| 379 |
builder.add("\n"); |
| 380 |
builder.addStatement("stack.removeFirst()"); |
| 381 |
builder.addStatement("return $L", name); |
| 382 |
} |
| 383 |
|
| 384 |
/** |
| 385 |
* Emits the read() method prologue. It creates an instance of the class |
| 386 |
* to read from the input stream, initializes the stack if necessary and |
| 387 |
* declares a couple of variables. |
| 388 |
*/ |
| 389 |
private static void emitMethodPrologue(TypeDef type, MethodDef.Builder builder, String name) { |
| 390 |
builder.addStatement("$T $L = new $T()", type, name, type); |
| 391 |
builder.addStatement("stack.addFirst($L)", name); |
| 392 |
builder.add("\n"); |
| 393 |
builder.addStatement("int size = 0"); |
| 394 |
builder.addStatement("long byteCount = 0"); |
| 395 |
builder.add("\n"); |
| 396 |
} |
| 397 |
|
| 398 |
private void errorReaderNotFound(TypeElement typeElement, FieldChunk chunk) { |
| 399 |
errorHandler.error(typeElement, "Could not generate code for field %s", chunk.name); |
| 400 |
} |
| 401 |
|
| 402 |
private static boolean hasTypeSwitch(FieldChunk chunk, ChunkReader reader) { |
| 403 |
return reader instanceof DynamicTypeChunkReader && chunk.switchType().length > 0; |
| 404 |
} |
| 405 |
|
| 406 |
private TypeMirror typeFromTest(Chunk.Case test) { |
| 407 |
TypeMirror typeMirror; |
| 408 |
try { |
| 409 |
String canonicalName = test.type().getCanonicalName(); |
| 410 |
TypeElement switchedElement = elementUtils.getTypeElement(canonicalName); |
| 411 |
typeMirror = switchedElement.asType(); |
| 412 |
} catch (MirroredTypeException e) { |
| 413 |
typeMirror = e.getTypeMirror(); |
| 414 |
} |
| 415 |
return typeMirror; |
| 416 |
} |
| 417 |
|
| 418 |
private static Object[] typesFromException(MirroredTypesException e) { |
| 419 |
Object[] params;List<? extends TypeMirror> typeMirrors = e.getTypeMirrors(); |
| 420 |
params = typeMirrors.toArray(new TypeMirror[typeMirrors.size()]); |
| 421 |
return params; |
| 422 |
} |
| 423 |
|
| 424 |
/** |
| 425 |
* This class only exist so we can get the type parameters for code generation. |
| 426 |
*/ |
| 427 |
private static class StackType extends LinkedList<Object> { |
| 428 |
} |
| 429 |
} |