summaryrefslogtreecommitdiffstats
path: root/src/com/google/doclava/AndroidAuxSource.java
blob: ca1fbd0855868bc3c01dc17f62860ebd0ddb9c69 (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
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
/*
 * Copyright (C) 2017 Google Inc.
 *
 * 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.doclava;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class AndroidAuxSource implements AuxSource {
  private static final int TYPE_CLASS = 0;
  private static final int TYPE_FIELD = 1;
  private static final int TYPE_METHOD = 2;
  private static final int TYPE_PARAM = 3;
  private static final int TYPE_RETURN = 4;

  @Override
  public TagInfo[] classAuxTags(ClassInfo clazz) {
    if (hasSuppress(clazz.annotations())) return TagInfo.EMPTY_ARRAY;
    ArrayList<TagInfo> tags = new ArrayList<>();
    for (AnnotationInstanceInfo annotation : clazz.annotations()) {
      // Document system services
      if (annotation.type().qualifiedNameMatches("android", "annotation.SystemService")) {
        ArrayList<TagInfo> valueTags = new ArrayList<>();
        valueTags
            .add(new ParsedTagInfo("", "",
                "{@link android.content.Context#getSystemService(Class)"
                    + " Context.getSystemService(Class)}",
                null, SourcePositionInfo.UNKNOWN));
        valueTags.add(new ParsedTagInfo("", "",
            "{@code " + clazz.name() + ".class}", null,
            SourcePositionInfo.UNKNOWN));

        ClassInfo contextClass = annotation.type().findClass("android.content.Context");
        for (AnnotationValueInfo val : annotation.elementValues()) {
          switch (val.element().name()) {
            case "value":
              final String expected = String.valueOf(val.value());
              for (FieldInfo field : contextClass.fields()) {
                if (field.isHiddenOrRemoved()) continue;
                if (String.valueOf(field.constantValue()).equals(expected)) {
                  valueTags.add(new ParsedTagInfo("", "",
                      "{@link android.content.Context#getSystemService(String)"
                          + " Context.getSystemService(String)}",
                      null, SourcePositionInfo.UNKNOWN));
                  valueTags.add(new ParsedTagInfo("", "",
                      "{@link android.content.Context#" + field.name()
                          + " Context." + field.name() + "}",
                      null, SourcePositionInfo.UNKNOWN));
                }
              }
              break;
          }
        }

        Map<String, String> args = new HashMap<>();
        tags.add(new AuxTagInfo("@service", "@service", SourcePositionInfo.UNKNOWN, args,
            valueTags.toArray(TagInfo.getArray(valueTags.size()))));
      }
    }
    auxTags(TYPE_CLASS, clazz.annotations(), toString(clazz.inlineTags()), tags);
    return tags.toArray(TagInfo.getArray(tags.size()));
  }

  @Override
  public TagInfo[] fieldAuxTags(FieldInfo field) {
    if (hasSuppress(field)) return TagInfo.EMPTY_ARRAY;
    return auxTags(TYPE_FIELD, field.annotations(), toString(field.inlineTags()));
  }

  @Override
  public TagInfo[] methodAuxTags(MethodInfo method) {
    if (hasSuppress(method)) return TagInfo.EMPTY_ARRAY;
    return auxTags(TYPE_METHOD, method.annotations(), toString(method.inlineTags().tags()));
  }

  @Override
  public TagInfo[] paramAuxTags(MethodInfo method, ParameterInfo param, String comment) {
    if (hasSuppress(method)) return TagInfo.EMPTY_ARRAY;
    if (hasSuppress(param.annotations())) return TagInfo.EMPTY_ARRAY;
    return auxTags(TYPE_PARAM, param.annotations(), new String[] { comment });
  }

  @Override
  public TagInfo[] returnAuxTags(MethodInfo method) {
    if (hasSuppress(method)) return TagInfo.EMPTY_ARRAY;
    return auxTags(TYPE_RETURN, method.annotations(), toString(method.returnTags().tags()));
  }

  private static TagInfo[] auxTags(int type, List<AnnotationInstanceInfo> annotations,
      String[] comment) {
    ArrayList<TagInfo> tags = new ArrayList<>();
    auxTags(type, annotations, comment, tags);
    return tags.toArray(TagInfo.getArray(tags.size()));
  }

  private static void auxTags(int type, List<AnnotationInstanceInfo> annotations,
      String[] comment, ArrayList<TagInfo> tags) {
    for (AnnotationInstanceInfo annotation : annotations) {
      // Ignore null-related annotations when docs already mention
      if (annotation.type().qualifiedNameMatches("android", "annotation.NonNull")
          || annotation.type().qualifiedNameMatches("android", "annotation.Nullable")) {
        boolean mentionsNull = false;
        for (String c : comment) {
          mentionsNull |= Pattern.compile("\\bnull\\b").matcher(c).find();
        }
        if (mentionsNull) {
          continue;
        }
      }

      // Blindly include docs requested by annotations
      ParsedTagInfo[] docTags = ParsedTagInfo.EMPTY_ARRAY;
      switch (type) {
        case TYPE_METHOD:
        case TYPE_FIELD:
        case TYPE_CLASS:
          docTags = annotation.type().comment().memberDocTags();
          break;
        case TYPE_PARAM:
          docTags = annotation.type().comment().paramDocTags();
          break;
        case TYPE_RETURN:
          docTags = annotation.type().comment().returnDocTags();
          break;
      }
      for (ParsedTagInfo docTag : docTags) {
        tags.add(docTag);
      }

      // Document required permissions
      if ((type == TYPE_CLASS || type == TYPE_METHOD || type == TYPE_FIELD)
          && annotation.type().qualifiedNameMatches("android", "annotation.RequiresPermission")) {
        ArrayList<AnnotationValueInfo> values = new ArrayList<>();
        boolean any = false;
        for (AnnotationValueInfo val : annotation.elementValues()) {
          switch (val.element().name()) {
            case "value":
              values.add(val);
              break;
            case "allOf":
              values = (ArrayList<AnnotationValueInfo>) val.value();
              break;
            case "anyOf":
              any = true;
              values = (ArrayList<AnnotationValueInfo>) val.value();
              break;
          }
        }
        if (values.isEmpty()) continue;

        ClassInfo permClass = annotation.type().findClass("android.Manifest.permission");
        ArrayList<TagInfo> valueTags = new ArrayList<>();
        for (AnnotationValueInfo value : values) {
          final String expected = String.valueOf(value.value());
          for (FieldInfo field : permClass.fields()) {
            if (field.isHiddenOrRemoved()) continue;
            if (String.valueOf(field.constantValue()).equals(expected)) {
              valueTags.add(new ParsedTagInfo("", "",
                  "{@link " + permClass.qualifiedName() + "#" + field.name() + "}", null,
                  SourcePositionInfo.UNKNOWN));
            }
          }
        }

        Map<String, String> args = new HashMap<>();
        if (any) args.put("any", "true");
        tags.add(new AuxTagInfo("@permission", "@permission", SourcePositionInfo.UNKNOWN, args,
            valueTags.toArray(TagInfo.getArray(valueTags.size()))));
      }

      // Document required features
      if ((type == TYPE_CLASS || type == TYPE_METHOD || type == TYPE_FIELD)
          && annotation.type().qualifiedNameMatches("android", "annotation.RequiresFeature")) {
        AnnotationValueInfo value = null;
        for (AnnotationValueInfo val : annotation.elementValues()) {
          switch (val.element().name()) {
            case "value":
              value = val;
              break;
          }
        }
        if (value == null) continue;

        ClassInfo pmClass = annotation.type().findClass("android.content.pm.PackageManager");
        ArrayList<TagInfo> valueTags = new ArrayList<>();
        final String expected = String.valueOf(value.value());
        for (FieldInfo field : pmClass.fields()) {
          if (field.isHiddenOrRemoved()) continue;
          if (String.valueOf(field.constantValue()).equals(expected)) {
            valueTags.add(new ParsedTagInfo("", "",
                "{@link " + pmClass.qualifiedName() + "#" + field.name() + "}", null,
                SourcePositionInfo.UNKNOWN));
          }
        }

        valueTags.add(new ParsedTagInfo("", "",
            "{@link android.content.pm.PackageManager#hasSystemFeature(String)"
                + " PackageManager.hasSystemFeature(String)}",
            null, SourcePositionInfo.UNKNOWN));

        Map<String, String> args = new HashMap<>();
        tags.add(new AuxTagInfo("@feature", "@feature", SourcePositionInfo.UNKNOWN, args,
            valueTags.toArray(TagInfo.getArray(valueTags.size()))));
      }

      // Document provider columns
      if ((type == TYPE_FIELD) && annotation.type().qualifiedNameMatches("android", "Column")) {
        String value = null;
        boolean readOnly = false;
        for (AnnotationValueInfo val : annotation.elementValues()) {
          switch (val.element().name()) {
            case "value":
              value = String.valueOf(val.value());
              break;
            case "readOnly":
              readOnly = Boolean.parseBoolean(String.valueOf(val.value()));
              break;
          }
        }

        ArrayList<TagInfo> valueTags = new ArrayList<>();
        valueTags.add(new ParsedTagInfo("", "",
            "{@link android.content.ContentProvider}", null, SourcePositionInfo.UNKNOWN));
        valueTags.add(new ParsedTagInfo("", "",
            "{@link android.content.ContentValues}", null, SourcePositionInfo.UNKNOWN));
        valueTags.add(new ParsedTagInfo("", "",
            "{@link android.database.Cursor}", null, SourcePositionInfo.UNKNOWN));

        ClassInfo cursorClass = annotation.type().findClass("android.database.Cursor");
        for (FieldInfo field : cursorClass.fields()) {
          if (field.isHiddenOrRemoved()) continue;
          if (String.valueOf(field.constantValue()).equals(value)) {
            valueTags.add(new ParsedTagInfo("", "",
                "{@link android.database.Cursor#" + field.name() + "}",
                null, SourcePositionInfo.UNKNOWN));
          }
        }
        if (valueTags.size() < 4) continue;

        Map<String, String> args = new HashMap<>();
        if (readOnly) args.put("readOnly", "true");
        tags.add(new AuxTagInfo("@column", "@column", SourcePositionInfo.UNKNOWN, args,
            valueTags.toArray(TagInfo.getArray(valueTags.size()))));
      }

      // The remaining annotations below always appear on return docs, and
      // should not be included in the method body
      if (type == TYPE_METHOD) continue;

      // Document value ranges
      if (annotation.type().qualifiedNameMatches("android", "annotation.IntRange")
          || annotation.type().qualifiedNameMatches("android", "annotation.FloatRange")) {
        String from = null;
        String to = null;
        for (AnnotationValueInfo val : annotation.elementValues()) {
          switch (val.element().name()) {
            case "from": from = String.valueOf(val.value()); break;
            case "to": to = String.valueOf(val.value()); break;
          }
        }
        if (from != null || to != null) {
          Map<String, String> args = new HashMap<>();
          if (from != null) args.put("from", from);
          if (to != null) args.put("to", to);
          tags.add(new AuxTagInfo("@range", "@range", SourcePositionInfo.UNKNOWN, args,
              TagInfo.EMPTY_ARRAY));
        }
      }

      // Document integer values
      for (AnnotationInstanceInfo inner : annotation.type().annotations()) {
        boolean intDef = inner.type().qualifiedNameMatches("android", "annotation.IntDef");
        boolean stringDef = inner.type().qualifiedNameMatches("android", "annotation.StringDef");
        if (intDef || stringDef) {
          ArrayList<AnnotationValueInfo> prefixes = null;
          ArrayList<AnnotationValueInfo> suffixes = null;
          ArrayList<AnnotationValueInfo> values = null;
          final String kind = intDef ? "@intDef" : "@stringDef";
          boolean flag = false;

          for (AnnotationValueInfo val : inner.elementValues()) {
            switch (val.element().name()) {
              case "prefix": prefixes = (ArrayList<AnnotationValueInfo>) val.value(); break;
              case "suffix": suffixes = (ArrayList<AnnotationValueInfo>) val.value(); break;
              case "value": values = (ArrayList<AnnotationValueInfo>) val.value(); break;
              case "flag": flag = Boolean.parseBoolean(String.valueOf(val.value())); break;
            }
          }

          // Sadly we can only generate docs when told about a prefix/suffix
          if (prefixes == null) prefixes = new ArrayList<>();
          if (suffixes == null) suffixes = new ArrayList<>();
          if (prefixes.isEmpty() && suffixes.isEmpty()) continue;

          final ClassInfo clazz = annotation.type().containingClass();
          final HashMap<String, FieldInfo> candidates = new HashMap<>();
          for (FieldInfo field : clazz.fields()) {
            if (field.isHiddenOrRemoved()) continue;
            for (AnnotationValueInfo prefix : prefixes) {
              if (field.name().startsWith(String.valueOf(prefix.value()))) {
                candidates.put(String.valueOf(field.constantValue()), field);
              }
            }
            for (AnnotationValueInfo suffix : suffixes) {
              if (field.name().endsWith(String.valueOf(suffix.value()))) {
                candidates.put(String.valueOf(field.constantValue()), field);
              }
            }
          }

          ArrayList<TagInfo> valueTags = new ArrayList<>();
          for (AnnotationValueInfo value : values) {
            final String expected = String.valueOf(value.value());
            final FieldInfo field = candidates.remove(expected);
            if (field != null) {
              valueTags.add(new ParsedTagInfo("", "",
                  "{@link " + clazz.qualifiedName() + "#" + field.name() + "}", null,
                  SourcePositionInfo.UNKNOWN));
            }
          }

          if (!valueTags.isEmpty()) {
            Map<String, String> args = new HashMap<>();
            if (flag) args.put("flag", "true");
            tags.add(new AuxTagInfo(kind, kind, SourcePositionInfo.UNKNOWN, args,
                valueTags.toArray(TagInfo.getArray(valueTags.size()))));
          }
        }
      }
    }
  }

  private static String[] toString(TagInfo[] tags) {
    final String[] res = new String[tags.length];
    for (int i = 0; i < res.length; i++) {
      res[i] = tags[i].text();
    }
    return res;
  }

  private static boolean hasSuppress(MemberInfo member) {
    return hasSuppress(member.annotations())
        || hasSuppress(member.containingClass().annotations());
  }

  private static boolean hasSuppress(List<AnnotationInstanceInfo> annotations) {
    for (AnnotationInstanceInfo annotation : annotations) {
      if (annotation.type().qualifiedNameMatches("android", "annotation.SuppressAutoDoc")) {
        return true;
      }
    }
    return false;
  }
}