1 /* 2 * Copyright (C) 2009 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.mkstubs.sourcer; 18 19 import org.objectweb.asm.AnnotationVisitor; 20 import org.objectweb.asm.Opcodes; 21 22 /** 23 * An annotation visitor that generates Java source for an annotation. 24 */ 25 class AnnotationSourcer extends AnnotationVisitor { 26 27 private final String mOpenChar; 28 private final String mCloseChar; 29 private final Output mOutput; 30 private boolean mNeedClose; 31 AnnotationSourcer(Output output)32 public AnnotationSourcer(Output output) { 33 this(output, false /*isArray*/); 34 } 35 AnnotationSourcer(Output output, boolean isArray)36 public AnnotationSourcer(Output output, boolean isArray) { 37 super(Opcodes.ASM4); 38 mOutput = output; 39 mOpenChar = isArray ? "[" : "("; 40 mCloseChar = isArray ? "]" : ")"; 41 } 42 43 @Override visit(String name, Object value)44 public void visit(String name, Object value) { 45 startOpen(); 46 47 if (name != null) { 48 mOutput.write("%s=", name); 49 } 50 if (value != null) { 51 mOutput.write(name.toString()); 52 } 53 } 54 startOpen()55 private void startOpen() { 56 if (!mNeedClose) { 57 mNeedClose = true; 58 mOutput.write(mOpenChar); 59 } 60 } 61 62 @Override visitEnd()63 public void visitEnd() { 64 if (mNeedClose) { 65 mOutput.write(mCloseChar); 66 } 67 mOutput.write("\n"); 68 } 69 70 @Override visitAnnotation(String name, String desc)71 public AnnotationVisitor visitAnnotation(String name, String desc) { 72 startOpen(); 73 74 mOutput.write("@%s", name); 75 return this; 76 } 77 78 @Override visitArray(String name)79 public AnnotationVisitor visitArray(String name) { 80 startOpen(); 81 return new AnnotationSourcer(mOutput, true /*isArray*/); 82 } 83 84 @Override visitEnum(String name, String desc, String value)85 public void visitEnum(String name, String desc, String value) { 86 mOutput.write("/* annotation enum not supported: %s */\n", name); 87 } 88 89 } 90