001/*
002 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004 *
005 * This code is free software; you can redistribute it and/or modify it
006 * under the terms of the GNU General Public License version 2 only, as
007 * published by the Free Software Foundation.
008 *
009 * This code is distributed in the hope that it will be useful, but WITHOUT
010 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
011 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
012 * version 2 for more details (a copy is included in the LICENSE file that
013 * accompanied this code).
014 *
015 * You should have received a copy of the GNU General Public License version
016 * 2 along with this work; if not, write to the Free Software Foundation,
017 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
018 *
019 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
020 * or visit www.oracle.com if you need additional information or have any
021 * questions.
022 */
023package jdk.internal.jvmci.options.processor;
024
025import java.io.*;
026import java.util.*;
027
028import javax.annotation.processing.*;
029import javax.lang.model.*;
030import javax.lang.model.element.*;
031import javax.lang.model.type.*;
032import javax.lang.model.util.*;
033import javax.tools.Diagnostic.Kind;
034import javax.tools.*;
035
036import jdk.internal.jvmci.options.*;
037
038/**
039 * Processes static fields annotated with {@link Option}. An {@link Options} service is generated
040 * for each top level class containing at least one such field. The name of the generated class for
041 * top level class {@code com.foo.Bar} is {@code com.foo.Bar_Options}.
042 *
043 * The build system is expected to create the appropriate entries in {@code META-INF/services/} such
044 * that these service objects can be retrieved as follows:
045 *
046 * <pre>
047 * ServiceLoader&lt;Options&gt; sl = ServiceLoader.load(Options.class);
048 * for (Options opts : sl) {
049 *     for (OptionDescriptor desc : sl) {
050 *         // use desc
051 *     }
052 * }
053 * </pre>
054 */
055@SupportedAnnotationTypes({"jdk.internal.jvmci.options.Option"})
056public class OptionProcessor extends AbstractProcessor {
057
058    @Override
059    public SourceVersion getSupportedSourceVersion() {
060        return SourceVersion.latest();
061    }
062
063    private final Set<Element> processed = new HashSet<>();
064
065    private void processElement(Element element, OptionsInfo info) {
066
067        if (!element.getModifiers().contains(Modifier.STATIC)) {
068            processingEnv.getMessager().printMessage(Kind.ERROR, "Option field must be static", element);
069            return;
070        }
071
072        Option annotation = element.getAnnotation(Option.class);
073        assert annotation != null;
074        assert element instanceof VariableElement;
075        assert element.getKind() == ElementKind.FIELD;
076        VariableElement field = (VariableElement) element;
077        String fieldName = field.getSimpleName().toString();
078
079        Elements elements = processingEnv.getElementUtils();
080        Types types = processingEnv.getTypeUtils();
081
082        TypeMirror fieldType = field.asType();
083        if (fieldType.getKind() != TypeKind.DECLARED) {
084            processingEnv.getMessager().printMessage(Kind.ERROR, "Option field must be of type " + OptionValue.class.getName(), element);
085            return;
086        }
087        DeclaredType declaredFieldType = (DeclaredType) fieldType;
088
089        TypeMirror optionValueType = elements.getTypeElement(OptionValue.class.getName()).asType();
090        if (!types.isSubtype(fieldType, types.erasure(optionValueType))) {
091            String msg = String.format("Option field type %s is not a subclass of %s", fieldType, optionValueType);
092            processingEnv.getMessager().printMessage(Kind.ERROR, msg, element);
093            return;
094        }
095
096        if (!field.getModifiers().contains(Modifier.STATIC)) {
097            processingEnv.getMessager().printMessage(Kind.ERROR, "Option field must be static", element);
098            return;
099        }
100
101        String help = annotation.help();
102        if (help.length() != 0) {
103            char firstChar = help.charAt(0);
104            if (!Character.isUpperCase(firstChar)) {
105                processingEnv.getMessager().printMessage(Kind.ERROR, "Option help text must start with upper case letter", element);
106                return;
107            }
108        }
109
110        String optionName = annotation.name();
111        if (optionName.equals("")) {
112            optionName = fieldName;
113        }
114
115        DeclaredType declaredOptionValueType = declaredFieldType;
116        while (!types.isSameType(types.erasure(declaredOptionValueType), types.erasure(optionValueType))) {
117            List<? extends TypeMirror> directSupertypes = types.directSupertypes(declaredFieldType);
118            assert !directSupertypes.isEmpty();
119            declaredOptionValueType = (DeclaredType) directSupertypes.get(0);
120        }
121
122        assert !declaredOptionValueType.getTypeArguments().isEmpty();
123        String optionType = declaredOptionValueType.getTypeArguments().get(0).toString();
124        if (optionType.startsWith("java.lang.")) {
125            optionType = optionType.substring("java.lang.".length());
126        }
127
128        Element enclosing = element.getEnclosingElement();
129        String declaringClass = "";
130        String separator = "";
131        Set<Element> originatingElementsList = info.originatingElements;
132        originatingElementsList.add(field);
133        while (enclosing != null) {
134            if (enclosing.getKind() == ElementKind.CLASS || enclosing.getKind() == ElementKind.INTERFACE) {
135                if (enclosing.getModifiers().contains(Modifier.PRIVATE)) {
136                    String msg = String.format("Option field cannot be declared in a private %s %s", enclosing.getKind().name().toLowerCase(), enclosing);
137                    processingEnv.getMessager().printMessage(Kind.ERROR, msg, element);
138                    return;
139                }
140                originatingElementsList.add(enclosing);
141                declaringClass = enclosing.getSimpleName() + separator + declaringClass;
142                separator = ".";
143            } else {
144                assert enclosing.getKind() == ElementKind.PACKAGE;
145            }
146            enclosing = enclosing.getEnclosingElement();
147        }
148
149        info.options.add(new OptionInfo(optionName, help, optionType, declaringClass, field));
150    }
151
152    private void createFiles(OptionsInfo info) {
153        String pkg = ((PackageElement) info.topDeclaringType.getEnclosingElement()).getQualifiedName().toString();
154        Name topDeclaringClass = info.topDeclaringType.getSimpleName();
155
156        String optionsClassName = topDeclaringClass + "_" + Options.class.getSimpleName();
157        Element[] originatingElements = info.originatingElements.toArray(new Element[info.originatingElements.size()]);
158
159        Filer filer = processingEnv.getFiler();
160        try (PrintWriter out = createSourceFile(pkg, optionsClassName, filer, originatingElements)) {
161
162            out.println("// CheckStyle: stop header check");
163            out.println("// GENERATED CONTENT - DO NOT EDIT");
164            out.println("// Source: " + topDeclaringClass + ".java");
165            out.println("package " + pkg + ";");
166            out.println("");
167            out.println("import java.util.*;");
168            out.println("import " + Options.class.getPackage().getName() + ".*;");
169            out.println("");
170            out.println("public class " + optionsClassName + " implements " + Options.class.getSimpleName() + " {");
171            out.println("    @Override");
172            String desc = OptionDescriptor.class.getSimpleName();
173            out.println("    public Iterator<" + desc + "> iterator() {");
174            out.println("        // CheckStyle: stop line length check");
175            out.println("        List<" + desc + "> options = Arrays.asList(");
176
177            boolean needPrivateFieldAccessor = false;
178            int i = 0;
179            Collections.sort(info.options);
180            for (OptionInfo option : info.options) {
181                String optionValue;
182                if (option.field.getModifiers().contains(Modifier.PRIVATE)) {
183                    needPrivateFieldAccessor = true;
184                    optionValue = "field(" + option.declaringClass + ".class, \"" + option.field.getSimpleName() + "\")";
185                } else {
186                    optionValue = option.declaringClass + "." + option.field.getSimpleName();
187                }
188                String name = option.name;
189                String type = option.type;
190                String help = option.help;
191                String declaringClass = option.declaringClass;
192                Name fieldName = option.field.getSimpleName();
193                String comma = i == info.options.size() - 1 ? "" : ",";
194                out.printf("            new %s(\"%s\", %s.class, \"%s\", %s.class, \"%s\", %s)%s\n", desc, name, type, help, declaringClass, fieldName, optionValue, comma);
195                i++;
196            }
197            out.println("        );");
198            out.println("        // CheckStyle: resume line length check");
199            out.println("        return options.iterator();");
200            out.println("    }");
201            if (needPrivateFieldAccessor) {
202                out.println("    private static " + OptionValue.class.getSimpleName() + "<?> field(Class<?> declaringClass, String fieldName) {");
203                out.println("        try {");
204                out.println("            java.lang.reflect.Field field = declaringClass.getDeclaredField(fieldName);");
205                out.println("            field.setAccessible(true);");
206                out.println("            return (" + OptionValue.class.getSimpleName() + "<?>) field.get(null);");
207                out.println("        } catch (Exception e) {");
208                out.println("            throw (InternalError) new InternalError().initCause(e);");
209                out.println("        }");
210                out.println("    }");
211            }
212            out.println("}");
213        }
214
215        try {
216            createOptionsFile(info, pkg, topDeclaringClass.toString(), originatingElements);
217        } catch (IOException e) {
218            processingEnv.getMessager().printMessage(Kind.ERROR, e.getMessage(), info.topDeclaringType);
219        }
220    }
221
222    private void createOptionsFile(OptionsInfo info, String pkg, String relativeName, Element... originatingElements) throws IOException {
223        String filename = "META-INF/jvmci.options/" + pkg + "." + relativeName;
224        FileObject file = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", filename, originatingElements);
225        PrintWriter writer = new PrintWriter(new OutputStreamWriter(file.openOutputStream(), "UTF-8"));
226        Types types = processingEnv.getTypeUtils();
227        for (OptionInfo option : info.options) {
228            String help = option.help;
229            if (help.indexOf('\t') >= 0 || help.indexOf('\r') >= 0 || help.indexOf('\n') >= 0) {
230                processingEnv.getMessager().printMessage(Kind.WARNING, "Option help should not contain '\\t', '\\r' or '\\n'", option.field);
231                help = help.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ');
232            }
233            try {
234                char optionTypeToChar = optionTypeToChar(option);
235                String fqDeclaringClass = className(types.erasure(option.field.getEnclosingElement().asType()));
236                String fqFieldType = className(types.erasure(option.field.asType()));
237                writer.printf("%s\t%s\t%s\t%s\t%s%n", option.name, optionTypeToChar, help, fqDeclaringClass, fqFieldType);
238            } catch (IllegalArgumentException iae) {
239            }
240        }
241        writer.close();
242    }
243
244    private String className(TypeMirror t) {
245        DeclaredType dt = (DeclaredType) t;
246        return processingEnv.getElementUtils().getBinaryName((TypeElement) dt.asElement()).toString();
247    }
248
249    private char optionTypeToChar(OptionInfo option) {
250        switch (option.type) {
251            case "Boolean":
252                return 'z';
253            case "Integer":
254                return 'i';
255            case "Long":
256                return 'j';
257            case "Float":
258                return 'f';
259            case "Double":
260                return 'd';
261            case "String":
262                return 's';
263            default:
264                processingEnv.getMessager().printMessage(Kind.ERROR, "Unsupported option type: " + option.type, option.field);
265                throw new IllegalArgumentException();
266        }
267    }
268
269    protected PrintWriter createSourceFile(String pkg, String relativeName, Filer filer, Element... originatingElements) {
270        try {
271            // Ensure Unix line endings to comply with code style guide checked by Checkstyle
272            JavaFileObject sourceFile = filer.createSourceFile(pkg + "." + relativeName, originatingElements);
273            return new PrintWriter(sourceFile.openWriter()) {
274
275                @Override
276                public void println() {
277                    print("\n");
278                }
279            };
280        } catch (IOException e) {
281            throw new RuntimeException(e);
282        }
283    }
284
285    static class OptionInfo implements Comparable<OptionInfo> {
286
287        final String name;
288        final String help;
289        final String type;
290        final String declaringClass;
291        final VariableElement field;
292
293        public OptionInfo(String name, String help, String type, String declaringClass, VariableElement field) {
294            this.name = name;
295            this.help = help;
296            this.type = type;
297            this.declaringClass = declaringClass;
298            this.field = field;
299        }
300
301        @Override
302        public int compareTo(OptionInfo other) {
303            return name.compareTo(other.name);
304        }
305
306        @Override
307        public String toString() {
308            return declaringClass + "." + field;
309        }
310    }
311
312    static class OptionsInfo {
313
314        final Element topDeclaringType;
315        final List<OptionInfo> options = new ArrayList<>();
316        final Set<Element> originatingElements = new HashSet<>();
317
318        public OptionsInfo(Element topDeclaringType) {
319            this.topDeclaringType = topDeclaringType;
320        }
321    }
322
323    private static Element topDeclaringType(Element element) {
324        Element enclosing = element.getEnclosingElement();
325        if (enclosing == null || enclosing.getKind() == ElementKind.PACKAGE) {
326            assert element.getKind() == ElementKind.CLASS || element.getKind() == ElementKind.INTERFACE;
327            return element;
328        }
329        return topDeclaringType(enclosing);
330    }
331
332    @Override
333    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
334        if (roundEnv.processingOver()) {
335            return true;
336        }
337
338        Map<Element, OptionsInfo> map = new HashMap<>();
339        for (Element element : roundEnv.getElementsAnnotatedWith(Option.class)) {
340            if (!processed.contains(element)) {
341                processed.add(element);
342                Element topDeclaringType = topDeclaringType(element);
343                OptionsInfo options = map.get(topDeclaringType);
344                if (options == null) {
345                    options = new OptionsInfo(topDeclaringType);
346                    map.put(topDeclaringType, options);
347                }
348                processElement(element, options);
349            }
350        }
351
352        boolean ok = true;
353        Map<String, OptionInfo> uniqueness = new HashMap<>();
354        for (OptionsInfo info : map.values()) {
355            for (OptionInfo option : info.options) {
356                OptionInfo conflict = uniqueness.put(option.name, option);
357                if (conflict != null) {
358                    processingEnv.getMessager().printMessage(Kind.ERROR, "Duplicate option names for " + option + " and " + conflict, option.field);
359                    ok = false;
360                }
361            }
362        }
363
364        if (ok) {
365            for (OptionsInfo info : map.values()) {
366                createFiles(info);
367            }
368        }
369
370        return true;
371    }
372}