summaryrefslogtreecommitdiff
path: root/dx/src/com/android/dx/command/annotool/AnnotationLister.java
blob: 6584b6032eed977cc9cb3bea30b7a92c5a4f13e8 (plain)
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
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * 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.android.dx.command.annotool;

import com.android.dx.cf.direct.ClassPathOpener;
import com.android.dx.cf.direct.DirectClassFile;
import com.android.dx.cf.direct.StdAttributeFactory;
import com.android.dx.cf.iface.AttributeList;
import com.android.dx.cf.iface.Attribute;
import com.android.dx.cf.attrib.AttRuntimeInvisibleAnnotations;
import com.android.dx.cf.attrib.BaseAnnotations;
import com.android.dx.cf.attrib.AttRuntimeVisibleAnnotations;
import com.android.dx.util.ByteArray;
import com.android.dx.rop.annotation.Annotation;

import java.io.File;
import java.lang.annotation.ElementType;
import java.util.HashSet;

/**
 * Greps annotations on a set of class files and prints matching elements
 * to stdout. What counts as a match and what should be printed is controlled
 * by the {@code Main.Arguments} instance.
 */
class AnnotationLister {
    /**
     * The string name of the pseudo-class that
     * contains package-wide annotations
     */
    private static final String PACKAGE_INFO = "package-info";

    /** current match configuration */
    private final Main.Arguments args;

    /** Set of classes whose inner classes should be considered matched */
    HashSet<String> matchInnerClassesOf = new HashSet<String>();

    /** set of packages whose classes should be considered matched */
    HashSet<String> matchPackages = new HashSet<String>();

    AnnotationLister (Main.Arguments args) {
        this.args = args;
    }

    /** Processes based on configuration specified in constructor. */
    void process() {
        for (String path : args.files) {
            ClassPathOpener opener;

            opener = new ClassPathOpener(path, true,
                    new ClassPathOpener.Consumer() {
                public boolean processFileBytes(String name, long lastModified, byte[] bytes) {
                    if (!name.endsWith(".class")) {
                        return true;
                    }

                    ByteArray ba = new ByteArray(bytes);
                    DirectClassFile cf
                        = new DirectClassFile(ba, name, true);

                    cf.setAttributeFactory(StdAttributeFactory.THE_ONE);
                    AttributeList attributes = cf.getAttributes();
                    Attribute att;

                    String cfClassName
                            = cf.getThisClass().getClassType().getClassName();

                    if (cfClassName.endsWith(PACKAGE_INFO)) {
                        att = attributes.findFirst(
                                AttRuntimeInvisibleAnnotations.ATTRIBUTE_NAME);

                        for (;att != null; att = attributes.findNext(att)) {
                            BaseAnnotations ann = (BaseAnnotations)att;
                            visitPackageAnnotation(cf, ann);
                        }

                        att = attributes.findFirst(
                                AttRuntimeVisibleAnnotations.ATTRIBUTE_NAME);

                        for (;att != null; att = attributes.findNext(att)) {
                            BaseAnnotations ann = (BaseAnnotations)att;
                            visitPackageAnnotation(cf, ann);
                        }
                    } else if (isMatchingInnerClass(cfClassName)
                            || isMatchingPackage(cfClassName)) {
                        printMatch(cf);
                    } else {
                        att = attributes.findFirst(
                                AttRuntimeInvisibleAnnotations.ATTRIBUTE_NAME);

                        for (;att != null; att = attributes.findNext(att)) {
                            BaseAnnotations ann = (BaseAnnotations)att;
                            visitClassAnnotation(cf, ann);
                        }

                        att = attributes.findFirst(
                                AttRuntimeVisibleAnnotations.ATTRIBUTE_NAME);

                        for (;att != null; att = attributes.findNext(att)) {
                            BaseAnnotations ann = (BaseAnnotations)att;
                            visitClassAnnotation(cf, ann);
                        }
                    }

                    return true;
                }

                public void onException(Exception ex) {
                    throw new RuntimeException(ex);
                }

                public void onProcessArchiveStart(File file) {

                }

            });

            opener.process();
        }
    }

    /**
     * Inspects a class annotation.
     *
     * @param cf {@code non-null;} class file
     * @param ann {@code non-null;} annotation
     */
    private void visitClassAnnotation(DirectClassFile cf,
            BaseAnnotations ann) {

        if (!args.eTypes.contains(ElementType.TYPE)) {
            return;
        }

        for (Annotation anAnn : ann.getAnnotations().getAnnotations()) {
            String annClassName
                    = anAnn.getType().getClassType().getClassName();
            if (args.aclass.equals(annClassName)) {
                printMatch(cf);
            }
        }
    }

    /**
     * Inspects a package annotation
     *
     * @param cf {@code non-null;} class file of "package-info" pseudo-class
     * @param ann {@code non-null;} annotation
     */
    private void visitPackageAnnotation(
            DirectClassFile cf, BaseAnnotations ann) {

        if (!args.eTypes.contains(ElementType.PACKAGE)) {
            return;
        }

        String packageName = cf.getThisClass().getClassType().getClassName();

        int slashIndex = packageName.lastIndexOf('/');

        if (slashIndex == -1) {
            packageName = "";
        } else {
            packageName
                    = packageName.substring(0, slashIndex);
        }


        for (Annotation anAnn : ann.getAnnotations().getAnnotations()) {
            String annClassName
                    = anAnn.getType().getClassType().getClassName();
            if (args.aclass.equals(annClassName)) {
                printMatchPackage(packageName);
            }
        }
    }


    /**
     * Prints, or schedules for printing, elements related to a
     * matching package.
     *
     * @param packageName {@code non-null;} name of package
     */
    private void printMatchPackage(String packageName) {
        for (Main.PrintType pt : args.printTypes) {
            switch (pt) {
                case CLASS:
                case INNERCLASS:
                case METHOD:
                    matchPackages.add(packageName);
                    break;
                case PACKAGE:
                    System.out.println(packageName.replace('/','.'));
                    break;
            }
        }
    }

    /**
     * Prints, or schedules for printing, elements related to a matching
     * class.
     *
     * @param cf {@code non-null;} matching class
     */
    private void printMatch(DirectClassFile cf) {
        for (Main.PrintType pt : args.printTypes) {
            switch (pt) {
                case CLASS:
                    String classname;
                    classname =
                        cf.getThisClass().getClassType().getClassName();
                    classname = classname.replace('/','.');
                    System.out.println(classname);
                    break;
                case INNERCLASS:
                    matchInnerClassesOf.add(
                            cf.getThisClass().getClassType().getClassName());
                    break;
                case METHOD:
                    //TODO
                    break;
                case PACKAGE:
                    break;
            }
        }
    }

    /**
     * Checks to see if a specified class name should be considered a match
     * due to previous matches.
     *
     * @param s {@code non-null;} class name
     * @return true if this class should be considered a match
     */
    private boolean isMatchingInnerClass(String s) {
        int i;

        while (0 < (i = s.lastIndexOf('$'))) {
            s = s.substring(0, i);
            if (matchInnerClassesOf.contains(s)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Checks to see if a specified package should be considered a match due
     * to previous matches.
     *
     * @param s {@code non-null;} package name
     * @return true if this package should be considered a match
     */
    private boolean isMatchingPackage(String s) {
        int slashIndex = s.lastIndexOf('/');

        String packageName;
        if (slashIndex == -1) {
            packageName = "";
        } else {
            packageName
                    = s.substring(0, slashIndex);
        }

        return matchPackages.contains(packageName);
    }
}