summaryrefslogtreecommitdiffstats
path: root/mobile/android/annotations/src/main/java/org/mozilla/gecko/annotationProcessors/AnnotationProcessor.java
blob: 8db77eed0bf6a06bdc7d9e947179d99772fdd533 (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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.gecko.annotationProcessors;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.util.Arrays;
import java.util.Iterator;
import org.mozilla.gecko.annotationProcessors.classloader.AnnotatableEntity;
import org.mozilla.gecko.annotationProcessors.classloader.ClassWithOptions;
import org.mozilla.gecko.annotationProcessors.classloader.IterableJarLoadingURLClassLoader;
import org.mozilla.gecko.annotationProcessors.utils.GeneratableElementIterator;

public class AnnotationProcessor {
  private static final String NATIVES_NAME = "Natives";
  private static final String WRAPPERS_NAME = "Wrappers";
  private static final String EXPORT_PREFIX = "mozilla/java/";

  public static final String GENERATED_COMMENT =
      "// GENERATED CODE\n"
          + "// Generated by the Java program at /build/annotationProcessors at compile time\n"
          + "// from annotations on Java methods. To update, change the annotations on the\n"
          + "// corresponding Java methods and rerun the build. Manually updating this file\n"
          + "// will cause your build to fail.\n"
          + "\n";

  public static void main(String[] args) {
    // We expect a list of jars on the commandline. If missing, whinge about it.
    if (args.length < 2) {
      System.err.println("Usage: java AnnotationProcessor outprefix jarfiles ...");
      System.exit(1);
    }

    final String OUTPUT_PREFIX = args[0];
    final String QUALIFIER = OUTPUT_PREFIX + "JNI";

    (new File(QUALIFIER)).mkdir();

    System.out.println("Processing annotations...");

    // We want to produce the same output as last time as often as possible. Ordering of
    // generated statements, therefore, needs to be consistent.
    final String[] jars = Arrays.copyOfRange(args, 1, args.length);
    Arrays.sort(jars);

    // Start the clock!
    long s = System.currentTimeMillis();

    int ret = 0;

    // Get an iterator over the classes in the jar files given...
    Iterator<ClassWithOptions> jarClassIterator =
        IterableJarLoadingURLClassLoader.getIteratorOverJars(jars);

    while (jarClassIterator.hasNext()) {
      final ClassWithOptions annotatedClass = jarClassIterator.next();
      if (!annotatedClass.hasGenerated()) {
        continue;
      }

      final String sourceFileName =
          QUALIFIER + annotatedClass.generatedName + WRAPPERS_NAME + ".cpp";
      final String headerFileName =
          QUALIFIER + File.separator + annotatedClass.generatedName + WRAPPERS_NAME + ".h";
      final String headerExportedFileName =
          EXPORT_PREFIX + annotatedClass.generatedName + WRAPPERS_NAME + ".h";
      final String nativesFileName =
          QUALIFIER + File.separator + annotatedClass.generatedName + NATIVES_NAME + ".h";
      final String nativesExportedFileName =
          EXPORT_PREFIX + annotatedClass.generatedName + NATIVES_NAME + ".h";

      final StringBuilder headerFile = new StringBuilder(GENERATED_COMMENT);
      final StringBuilder implementationFile = new StringBuilder(GENERATED_COMMENT);
      final StringBuilder nativesFile = new StringBuilder(GENERATED_COMMENT);

      headerFile.append(
          "#ifndef "
              + getHeaderGuardName(headerExportedFileName)
              + "\n"
              + "#define "
              + getHeaderGuardName(headerExportedFileName)
              + "\n"
              + "\n"
              + "#ifndef MOZ_PREPROCESSOR\n"
              + "#include \"mozilla/jni/Refs.h\"\n"
              + "#endif\n"
              + "\n"
              + "namespace mozilla {\n"
              + "namespace java {\n"
              + "\n");

      implementationFile.append(
          "#ifndef MOZ_PREPROCESSOR\n"
              + "#include \""
              + headerExportedFileName
              + "\"\n"
              + "#include \"mozilla/jni/Accessors.h\"\n"
              + "#endif\n"
              + "\n"
              + "namespace mozilla {\n"
              + "namespace java {\n"
              + "\n");

      nativesFile.append(
          "#ifndef "
              + getHeaderGuardName(nativesExportedFileName)
              + "\n"
              + "#define "
              + getHeaderGuardName(nativesExportedFileName)
              + "\n"
              + "\n"
              + "#ifndef MOZ_PREPROCESSOR\n"
              + "#include \""
              + headerExportedFileName
              + "\"\n"
              + "#include \"mozilla/jni/Natives.h\"\n"
              + "#endif\n"
              + "\n"
              + "namespace mozilla {\n"
              + "namespace java {\n"
              + "\n");

      generateClass(annotatedClass, headerFile, implementationFile, nativesFile);

      implementationFile.append("} /* java */\n" + "} /* mozilla */\n");

      headerFile.append(
          "} /* java */\n"
              + "} /* mozilla */\n\n"
              + "#endif // "
              + getHeaderGuardName(headerExportedFileName)
              + "\n");

      nativesFile.append(
          "} /* java */\n"
              + "} /* mozilla */\n\n"
              + "#endif // "
              + getHeaderGuardName(nativesExportedFileName)
              + "\n");

      ret |= writeOutputFile(sourceFileName, implementationFile);
      ret |= writeOutputFile(headerFileName, headerFile);
      ret |= writeOutputFile(nativesFileName, nativesFile);
    }
    long e = System.currentTimeMillis();
    System.out.println("Annotation processing complete in " + (e - s) + "ms");

    System.exit(ret);
  }

  private static void generateClass(
      final ClassWithOptions annotatedClass,
      final StringBuilder headerFile,
      final StringBuilder implementationFile,
      final StringBuilder nativesFile) {
    // Get an iterator over the appropriately generated methods of this class
    final GeneratableElementIterator methodIterator =
        new GeneratableElementIterator(annotatedClass);
    final ClassWithOptions[] innerClasses = methodIterator.getInnerClasses();

    final CodeGenerator generatorInstance = new CodeGenerator(annotatedClass);
    generatorInstance.generateClasses(innerClasses);

    // Iterate all annotated members in this class..
    while (methodIterator.hasNext()) {
      AnnotatableEntity aElementTuple = methodIterator.next();
      switch (aElementTuple.mEntityType) {
        case METHOD:
          generatorInstance.generateMethod(aElementTuple);
          break;
        case NATIVE:
          generatorInstance.generateNative(aElementTuple);
          break;
        case FIELD:
          generatorInstance.generateField(aElementTuple);
          break;
        case CONSTRUCTOR:
          generatorInstance.generateConstructor(aElementTuple);
          break;
      }
    }

    headerFile.append(generatorInstance.getHeaderFileContents());
    implementationFile.append(generatorInstance.getWrapperFileContents());
    nativesFile.append(generatorInstance.getNativesFileContents());

    for (ClassWithOptions innerClass : innerClasses) {
      generateClass(innerClass, headerFile, implementationFile, nativesFile);
    }
  }

  private static String getHeaderGuardName(final String name) {
    return name.replaceAll("\\W", "_");
  }

  private static int writeOutputFile(final String name, final StringBuilder content) {
    final byte[] contentBytes = content.toString().getBytes(StandardCharsets.UTF_8);

    try {
      final byte[] existingBytes = Files.readAllBytes(new File(name).toPath());
      if (Arrays.equals(contentBytes, existingBytes)) {
        return 0;
      }
    } catch (FileNotFoundException e) {
      // Pass.
    } catch (NoSuchFileException e) {
      // Pass.
    } catch (IOException e) {
      System.err.println("Unable to read " + name + ". Perhaps a permissions issue?");
      e.printStackTrace(System.err);
      return 1;
    }

    try (FileOutputStream outStream = new FileOutputStream(name)) {
      outStream.write(contentBytes);
    } catch (IOException e) {
      System.err.println("Unable to write " + name + ". Perhaps a permissions issue?");
      e.printStackTrace(System.err);
      return 1;
    }

    return 0;
  }
}