From 774bd17ecec757ff8aeaa0e72ef2ffe4c5e35a45 Mon Sep 17 00:00:00 2001 From: Ioannis Tsakpinis Date: Sun, 14 Sep 2014 17:07:56 +0300 Subject: [PATCH] Ported annotation processing from apt to javac. This is a manual merge of request #86 by @b23prodtm. The original patch is fantastic, but as expected has a few issues that will be fixed in subsequent commits. --- platform_build/build-generator.xml | 475 +++--- .../lwjgl/util/generator/FieldsGenerator.java | 155 +- .../util/generator/GeneratorProcessor.java | 145 ++ .../generator/GeneratorProcessorFactory.java | 176 -- .../util/generator/GeneratorVisitor.java | 609 +++---- .../util/generator/JNITypeTranslator.java | 63 +- .../util/generator/JavaMethodsGenerator.java | 1413 +++++++++-------- .../util/generator/JavaTypeTranslator.java | 219 +-- .../generator/NativeMethodStubsGenerator.java | 90 +- .../util/generator/NativeTypeTranslator.java | 356 ++--- .../util/generator/PostfixTranslator.java | 82 +- .../generator/RegisterStubsGenerator.java | 168 +- .../util/generator/SignatureTranslator.java | 70 +- .../org/lwjgl/util/generator/TypeInfo.java | 375 ++--- .../org/lwjgl/util/generator/TypeMap.java | 11 +- .../util/generator/TypedefsGenerator.java | 21 +- src/java/org/lwjgl/util/generator/Utils.java | 759 ++++----- .../util/generator/openal/ALTypeMap.java | 65 +- .../opencl/CLCapabilitiesGenerator.java | 205 +-- .../opencl/CLGeneratorProcessor.java | 155 ++ .../opencl/CLGeneratorProcessorFactory.java | 181 --- .../opencl/CLPDCapabilitiesGenerator.java | 31 +- .../util/generator/opencl/CLTypeMap.java | 76 +- .../lwjgl/util/generator/opencl/cl_void.java | 5 +- .../opengl/GLCapabilitiesGenerator.java | 72 +- .../opengl/GLESCapabilitiesGenerator.java | 71 +- .../opengl/GLESGeneratorProcessor.java | 164 ++ .../opengl/GLESGeneratorProcessorFactory.java | 184 --- .../util/generator/opengl/GLESTypeMap.java | 89 +- .../opengl/GLGeneratorProcessor.java | 164 ++ .../opengl/GLGeneratorProcessorFactory.java | 189 --- .../GLReferencesGeneratorProcessor.java | 191 +++ ...GLReferencesGeneratorProcessorFactory.java | 218 --- .../util/generator/opengl/GLTypeMap.java | 542 ++++--- .../lwjgl/util/generator/opengl/GLvoid.java | 5 +- .../macosx/org_lwjgl_opengl_MacOSXAWTMouse.m | 3 +- .../lwjgl/opengl/AMD_multi_draw_indirect.java | 6 +- .../org/lwjgl/opengl/ARB_draw_indirect.java | 6 +- .../lwjgl/opengl/ARB_indirect_parameters.java | 6 +- .../lwjgl/opengl/ARB_multi_draw_indirect.java | 6 +- src/templates/org/lwjgl/opengl/GL40.java | 6 +- src/templates/org/lwjgl/opengl/GL43.java | 6 +- 42 files changed, 4014 insertions(+), 3819 deletions(-) create mode 100644 src/java/org/lwjgl/util/generator/GeneratorProcessor.java delete mode 100644 src/java/org/lwjgl/util/generator/GeneratorProcessorFactory.java create mode 100644 src/java/org/lwjgl/util/generator/opencl/CLGeneratorProcessor.java delete mode 100644 src/java/org/lwjgl/util/generator/opencl/CLGeneratorProcessorFactory.java create mode 100644 src/java/org/lwjgl/util/generator/opengl/GLESGeneratorProcessor.java delete mode 100644 src/java/org/lwjgl/util/generator/opengl/GLESGeneratorProcessorFactory.java create mode 100644 src/java/org/lwjgl/util/generator/opengl/GLGeneratorProcessor.java delete mode 100644 src/java/org/lwjgl/util/generator/opengl/GLGeneratorProcessorFactory.java create mode 100644 src/java/org/lwjgl/util/generator/opengl/GLReferencesGeneratorProcessor.java delete mode 100644 src/java/org/lwjgl/util/generator/opengl/GLReferencesGeneratorProcessorFactory.java diff --git a/platform_build/build-generator.xml b/platform_build/build-generator.xml index e288ad31..70f2e6c9 100644 --- a/platform_build/build-generator.xml +++ b/platform_build/build-generator.xml @@ -16,8 +16,13 @@ - - + + + + + + + @@ -25,7 +30,7 @@ - + @@ -60,40 +65,48 @@ **************************************************************************** --> - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - + + + + + + + + + + + + + + - - - - - - - - - - - + + + + + + + + + + + + + + + - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - + + + + + + + + + + + + + + + - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - + + + + + + + + + + + + + + + - - - - - - - - - - - - + + + + + + + + + + + + + + + + diff --git a/src/java/org/lwjgl/util/generator/FieldsGenerator.java b/src/java/org/lwjgl/util/generator/FieldsGenerator.java index a9d8f394..b767979a 100644 --- a/src/java/org/lwjgl/util/generator/FieldsGenerator.java +++ b/src/java/org/lwjgl/util/generator/FieldsGenerator.java @@ -29,96 +29,99 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - package org.lwjgl.util.generator; import java.io.PrintWriter; import java.util.Collection; - -import com.sun.mirror.declaration.FieldDeclaration; -import com.sun.mirror.declaration.Modifier; -import com.sun.mirror.type.PrimitiveType; -import com.sun.mirror.type.TypeMirror; +import java.util.Set; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.Modifier; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.PrimitiveType; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; public class FieldsGenerator { - private static void validateField(FieldDeclaration field) { - // Check if field is "public static final" - Collection modifiers = field.getModifiers(); - if ( modifiers.size() != 3 - || !modifiers.contains(Modifier.PUBLIC) - || !modifiers.contains(Modifier.STATIC) - || !modifiers.contains(Modifier.FINAL) ) { - throw new RuntimeException("Field " + field.getSimpleName() + " is not declared public static final"); - } + private static void validateField(VariableElement field) { + // Check if field is "public static final" + Set modifiers = field.getModifiers(); + if (modifiers.size() != 3 + || !modifiers.contains(Modifier.PUBLIC) + || !modifiers.contains(Modifier.STATIC) + || !modifiers.contains(Modifier.FINAL)) { + throw new RuntimeException("Field " + field.getSimpleName() + " is not declared public static final"); + } - // Check suported types (int, long, float, String) - TypeMirror field_type = field.getType(); - if ( field_type instanceof PrimitiveType ) { - PrimitiveType field_type_prim = (PrimitiveType)field_type; - PrimitiveType.Kind field_kind = field_type_prim.getKind(); - if ( field_kind != PrimitiveType.Kind.INT - && field_kind != PrimitiveType.Kind.LONG - && field_kind != PrimitiveType.Kind.FLOAT - && field_kind != PrimitiveType.Kind.BYTE ) { - throw new RuntimeException("Field " + field.getSimpleName() + " is not of type 'int', 'long' or 'float'"); - } - } else if ( "java.lang.String".equals(field_type.toString()) ) { - } else { - throw new RuntimeException("Field " + field.getSimpleName() + " is not a primitive type or String"); - } + // Check suported types (int, long, float, String) + TypeMirror field_type = field.asType(); + if ("java.lang.String".equals(field_type.toString())) { + } else if (field_type instanceof PrimitiveType) { + PrimitiveType field_type_prim = (PrimitiveType) field_type; + TypeKind field_kind = field_type_prim.getKind(); + if (field_kind != TypeKind.INT + && field_kind != TypeKind.LONG + && field_kind != TypeKind.FLOAT + && field_kind != TypeKind.BYTE) { + throw new RuntimeException("Field " + field.getSimpleName() + " is not of type 'int', 'long', 'float' or 'byte' " + field_kind.toString()); + } + } else { + throw new RuntimeException("Field " + field.getSimpleName() + " is not a primitive type or String"); + } - Object field_value = field.getConstantValue(); - if ( field_value == null ) { - throw new RuntimeException("Field " + field.getSimpleName() + " has no initial value"); - } - } + Object field_value = field.getConstantValue(); + if (field_value == null) { + throw new RuntimeException("Field " + field.getSimpleName() + " has no initial value"); + } + } - private static void generateField(PrintWriter writer, FieldDeclaration field, FieldDeclaration prev_field) { - validateField(field); + private static void generateField(PrintWriter writer, VariableElement field, VariableElement prev_field, ProcessingEnvironment env) { + validateField(field); - Object value = field.getConstantValue(); - String field_value_string; - Class field_value_class = value.getClass(); - if ( field_value_class.equals(Integer.class) ) { - field_value_string = "0x" + Integer.toHexString((Integer)field.getConstantValue()).toUpperCase(); - } else if ( field_value_class.equals(Long.class) ) { - field_value_string = "0x" + Long.toHexString((Long)field.getConstantValue()).toUpperCase() + 'L'; - } else if ( field_value_class.equals(Float.class) ) { - field_value_string = field.getConstantValue() + "f"; - } else if ( value.getClass().equals(Byte.class) ) { - field_value_string = "0x" + Integer.toHexString((Byte)field.getConstantValue()).toUpperCase(); - } else if ( field_value_class.equals(String.class) ) { - field_value_string = "\"" + field.getConstantValue() + "\""; - } else { - throw new RuntimeException("Field is of unexpected type. This means there is a bug in validateField()."); - } + Object value = field.getConstantValue(); + String field_value_string; + Class field_value_class = value.getClass(); + if (field_value_class.equals(Integer.class)) { + field_value_string = "0x" + Integer.toHexString((Integer) field.getConstantValue()).toUpperCase(); + } else if (field_value_class.equals(Long.class)) { + field_value_string = "0x" + Long.toHexString((Long) field.getConstantValue()).toUpperCase() + 'L'; + } else if (field_value_class.equals(Float.class)) { + field_value_string = field.getConstantValue() + "f"; + } else if (value.getClass().equals(Byte.class)) { + field_value_string = "0x" + Integer.toHexString((Byte) field.getConstantValue()).toUpperCase(); + } else if (field_value_class.equals(String.class)) { + field_value_string = "\"" + field.getConstantValue() + "\""; + } else { + throw new RuntimeException("Field is of unexpected type. This means there is a bug in validateField()."); + } - boolean hadDoc = prev_field != null && prev_field.getDocComment() != null; - boolean hasDoc = field.getDocComment() != null; - boolean newBatch = prev_field == null || !prev_field.getType().equals(field.getType()) || (!hadDoc && field.getDocComment() != null) || (hadDoc && hasDoc && !prev_field.getDocComment().equals(field.getDocComment())); + boolean hadDoc = prev_field != null && env.getElementUtils().getDocComment(prev_field) != null; + boolean hasDoc = env.getElementUtils().getDocComment(field) != null; + boolean newBatch = prev_field == null || !prev_field.asType().equals(field.asType()) || (!hadDoc && env.getElementUtils().getDocComment(field) != null) || (hadDoc && hasDoc && !env.getElementUtils().getDocComment(prev_field).equals(env.getElementUtils().getDocComment(field))); - // Print field declaration - if ( newBatch ) { - if ( prev_field != null ) - writer.println(";\n"); + // Print field declaration + if (newBatch) { + if (prev_field != null) { + writer.println(";\n"); + } - Utils.printDocComment(writer, field); - writer.print("\tpublic static final " + field.getType().toString() + " " + field.getSimpleName() + " = " + field_value_string); - } else - writer.print(",\n\t\t" + field.getSimpleName() + " = " + field_value_string); - } + Utils.printDocComment(writer, field, env); + writer.print("\tpublic static final " + field.asType().toString() + " " + field.getSimpleName() + " = " + field_value_string); + } else { + writer.print(",\n\t\t" + field.getSimpleName() + " = " + field_value_string); + } + } - public static void generateFields(PrintWriter writer, Collection fields) { - if ( 0 < fields.size() ) { - writer.println(); - FieldDeclaration prev_field = null; - for ( FieldDeclaration field : fields ) { - generateField(writer, field, prev_field); - prev_field = field; - } - writer.println(";"); - } - } + public static void generateFields(ProcessingEnvironment env, PrintWriter writer, Collection fields) { + if (0 < fields.size()) { + writer.println(); + VariableElement prev_field = null; + for (VariableElement field : fields) { + generateField(writer, field, prev_field, env); + prev_field = field; + } + writer.println(";"); + } + } } diff --git a/src/java/org/lwjgl/util/generator/GeneratorProcessor.java b/src/java/org/lwjgl/util/generator/GeneratorProcessor.java new file mode 100644 index 00000000..ed27834f --- /dev/null +++ b/src/java/org/lwjgl/util/generator/GeneratorProcessor.java @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjgl.util.generator; + +import java.io.File; +import java.io.FileFilter; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.annotation.processing.SupportedOptions; +import javax.annotation.processing.SupportedSourceVersion; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.TypeElement; +import javax.lang.model.util.ElementFilter; +import javax.tools.Diagnostic; + +/** + * Generator tool for creating the java classes and native code from an + * annotated template java interface. + * + * @author elias_naur + * @version $Revision$ $Id$ + */ +@SupportedAnnotationTypes({"*"}) +@SupportedSourceVersion(SourceVersion.RELEASE_7) +@SupportedOptions({"binpath", "typemap", "generatechecks", "contextspecific"}) +public class GeneratorProcessor extends AbstractProcessor { + + private static boolean first_round = true; + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + if (roundEnv.processingOver() || !first_round) { + System.exit(0); + return true; + } + Map options = processingEnv.getOptions(); + String typemap_classname = options.get("typemap"); + String bin_path = options.get("binpath"); + boolean generate_error_checks = options.containsKey("generatechecks"); + boolean context_specific = options.containsKey("contextspecific"); + if (bin_path == null) { + throw new RuntimeException("No path specified for the bin directory with -Abinpath="); + } + + if (typemap_classname == null) { + throw new RuntimeException("No TypeMap class name specified with -Atypemap="); + } + + Element lastFile = null; + processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "annotations " + annotations.toString()); + try { + long generatorLM = getGeneratorLastModified(bin_path); + TypeMap type_map = (TypeMap) (Class.forName(typemap_classname).newInstance()); + for (Iterator it = ElementFilter.typesIn(roundEnv.getRootElements()).iterator(); it.hasNext();) { + lastFile = it.next(); + lastFile.accept(new GeneratorVisitor(processingEnv, type_map, generate_error_checks, context_specific, generatorLM), null); + } + first_round = false; + return true; + } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) { + if (lastFile == null) { + throw new RuntimeException(e); + } else { + throw new RuntimeException("\n-- Failed to process template: " + lastFile.asType().toString() + " --", e); + } + } + } + + /** + * Gets the time of the latest change on the Generator classes. + * + * @return time of the latest change + */ + private static long getGeneratorLastModified(final String bin_path) { + long lastModified = getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator"); + lastModified = Math.max(lastModified, getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator/openal")); + lastModified = Math.max(lastModified, getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator/opengl")); + lastModified = Math.max(lastModified, getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator/opencl")); + + return lastModified; + } + + private static long getDirectoryLastModified(final String bin_path, final String path) { + final File pck = new File(bin_path + path); + if (!pck.exists() || !pck.isDirectory()) { + return Long.MAX_VALUE; + } + + final File[] classes = pck.listFiles(new FileFilter() { + public boolean accept(final File pathname) { + return pathname.isFile() && pathname.getName().endsWith(".class"); + } + }); + + if (classes == null || classes.length == 0) { + return Long.MAX_VALUE; + } + + long lastModified = 0; + + for (File clazz : classes) { + long lm = clazz.lastModified(); + if (lastModified < lm) { + lastModified = lm; + } + } + + return lastModified; + } + +} diff --git a/src/java/org/lwjgl/util/generator/GeneratorProcessorFactory.java b/src/java/org/lwjgl/util/generator/GeneratorProcessorFactory.java deleted file mode 100644 index 9af7da47..00000000 --- a/src/java/org/lwjgl/util/generator/GeneratorProcessorFactory.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) 2002-2008 LWJGL Project - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'LWJGL' nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package org.lwjgl.util.generator; - -import java.io.File; -import java.io.FileFilter; -import java.util.Arrays; -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -import com.sun.mirror.apt.*; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; - -import static com.sun.mirror.util.DeclarationVisitors.*; -import static java.util.Collections.*; - -/** - * Generator tool for creating the java classes and native code - * from an annotated template java interface. - * - * @author elias_naur - * @version $Revision$ - * $Id$ - */ -public class GeneratorProcessorFactory implements AnnotationProcessorFactory, RoundCompleteListener { - - private static boolean first_round = true; - - // Process any set of annotations - private static final Collection supportedAnnotations = - unmodifiableCollection(Arrays.asList("*")); - - private static final Collection supportedOptions = - unmodifiableCollection(Arrays.asList("-Atypemap", "-Ageneratechecks", "-Acontextspecific")); - - public Collection supportedAnnotationTypes() { - return supportedAnnotations; - } - - public Collection supportedOptions() { - return supportedOptions; - } - - public void roundComplete(RoundCompleteEvent event) { - first_round = false; - } - - public AnnotationProcessor getProcessorFor(Set atds, AnnotationProcessorEnvironment env) { - // Only process the initial types, not the generated ones - if ( first_round ) { - env.addListener(this); - return new GeneratorProcessor(env); - } else - return AnnotationProcessors.NO_OP; - } - - private static class GeneratorProcessor implements AnnotationProcessor { - - private final AnnotationProcessorEnvironment env; - - GeneratorProcessor(AnnotationProcessorEnvironment env) { - this.env = env; - } - - public void process() { - Map options = env.getOptions(); - String typemap_classname = null; - String bin_path = null; - boolean generate_error_checks = options.containsKey("-Ageneratechecks"); - boolean context_specific = options.containsKey("-Acontextspecific"); - for ( String k : options.keySet() ) { - if ( !k.startsWith("-A") ) - continue; - - int delimiter = k.indexOf('='); - if ( delimiter != -1 ) { - if ( k.startsWith("-Atypemap") ) { - typemap_classname = k.substring(delimiter + 1); - } else if ( k.startsWith("-Abinpath") ) { - bin_path = k.substring(delimiter + 1); - } - } - } - if ( typemap_classname == null ) - throw new RuntimeException("No TypeMap class name specified with -Atypemap="); - if ( bin_path == null ) - throw new RuntimeException("No path specified for the bin directory with -Abinpath="); - - TypeDeclaration lastFile = null; - try { - long generatorLM = getGeneratorLastModified(bin_path); - TypeMap type_map = (TypeMap)(Class.forName(typemap_classname).newInstance()); - for ( TypeDeclaration typedecl : env.getSpecifiedTypeDeclarations() ) { - lastFile = typedecl; - typedecl.accept(getDeclarationScanner(new GeneratorVisitor(env, type_map, generate_error_checks, context_specific, generatorLM), NO_OP)); - } - } catch (Exception e) { - if ( lastFile == null ) - throw new RuntimeException(e); - else - throw new RuntimeException("\n-- Failed to process template: " + lastFile.getQualifiedName() + " --", e); - } - } - - /** - * Gets the time of the latest change on the Generator classes. - * - * @return time of the latest change - */ - private static long getGeneratorLastModified(final String bin_path) { - long lastModified = getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator"); - lastModified = Math.max(lastModified, getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator/openal")); - lastModified = Math.max(lastModified, getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator/opengl")); - lastModified = Math.max(lastModified, getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator/opencl")); - - return lastModified; - } - - private static long getDirectoryLastModified(final String bin_path, final String path) { - final File pck = new File(bin_path + path); - if ( !pck.exists() || !pck.isDirectory() ) - return Long.MAX_VALUE; - - final File[] classes = pck.listFiles(new FileFilter() { - public boolean accept(final File pathname) { - return pathname.isFile() && pathname.getName().endsWith(".class"); - } - }); - - if ( classes == null || classes.length == 0 ) - return Long.MAX_VALUE; - - long lastModified = 0; - - for ( File clazz : classes ) { - long lm = clazz.lastModified(); - if ( lastModified < lm ) - lastModified = lm; - } - - return lastModified; - } - } -} \ No newline at end of file diff --git a/src/java/org/lwjgl/util/generator/GeneratorVisitor.java b/src/java/org/lwjgl/util/generator/GeneratorVisitor.java index ea1468ef..e840bf55 100644 --- a/src/java/org/lwjgl/util/generator/GeneratorVisitor.java +++ b/src/java/org/lwjgl/util/generator/GeneratorVisitor.java @@ -29,318 +29,367 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - package org.lwjgl.util.generator; -import com.sun.mirror.apt.*; -import com.sun.mirror.declaration.*; -import com.sun.mirror.type.*; -import com.sun.mirror.util.*; - import java.io.*; import java.lang.annotation.Annotation; -import java.nio.channels.FileChannel; -import java.util.*; import java.nio.*; +import java.nio.channels.FileChannel; +import java.util.*; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.ElementKind; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.Modifier; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.ElementKindVisitor7; +import javax.tools.Diagnostic; +import javax.tools.Diagnostic.Kind; +import javax.tools.FileObject; +import javax.tools.StandardLocation; /** * * Generator visitor for the generator tool * * @author elias_naur - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ -public class GeneratorVisitor extends SimpleDeclarationVisitor { - private final AnnotationProcessorEnvironment env; - private final TypeMap type_map; - private final boolean generate_error_checks; - private final boolean context_specific; - private final long generatorLM; +public class GeneratorVisitor extends ElementKindVisitor7 { - public GeneratorVisitor(AnnotationProcessorEnvironment env, TypeMap type_map, boolean generate_error_checks, boolean context_specific, long generatorLM) { - this.env = env; - this.type_map = type_map; - this.generate_error_checks = generate_error_checks; - this.context_specific = context_specific; - this.generatorLM = generatorLM; - } + private final ProcessingEnvironment env; + private final TypeMap type_map; + private final boolean generate_error_checks; + private final boolean context_specific; + private final long generatorLM; - private void validateMethod(MethodDeclaration method) { - if (method.isVarArgs()) - throw new RuntimeException("Method " + method.getSimpleName() + " is variadic"); - Collection modifiers = method.getModifiers(); - if (!modifiers.contains(Modifier.PUBLIC)) - throw new RuntimeException("Method " + method.getSimpleName() + " is not public"); - if (method.getThrownTypes().size() > 0) - throw new RuntimeException("Method " + method.getSimpleName() + " throws checked exceptions"); - validateParameters(method); - StripPostfix strip_annotation = method.getAnnotation(StripPostfix.class); - if (strip_annotation != null && method.getAnnotation(Alternate.class) == null) { - String postfix_param_name = strip_annotation.value(); - ParameterDeclaration postfix_param = Utils.findParameter(method, postfix_param_name); - if (Utils.isParameterMultiTyped(postfix_param)) - throw new RuntimeException("Postfix parameter can't be the same as a multityped parameter in method " + method); - if (Utils.getNIOBufferType(postfix_param.getType()) == null) - throw new RuntimeException("Postfix parameter type must be a nio Buffer"); - } - if (Utils.getResultParameter(method) != null && !method.getReturnType().equals(env.getTypeUtils().getVoidType())) - throw new RuntimeException(method + " return type is not void but a parameter is annotated with Result"); - if (method.getAnnotation(CachedResult.class) != null) { - if (Utils.getNIOBufferType(Utils.getMethodReturnType(method)) == null) - throw new RuntimeException(method + " return type is not a Buffer, but is annotated with CachedResult"); - if (method.getAnnotation(AutoSize.class) == null) - throw new RuntimeException(method + " is annotated with CachedResult but misses an AutoSize annotation"); - } - validateTypes(method, method.getAnnotationMirrors(), method.getReturnType()); - } + public GeneratorVisitor(ProcessingEnvironment env, TypeMap type_map, boolean generate_error_checks, boolean context_specific, long generatorLM) { + this.env = env; + this.type_map = type_map; + this.generate_error_checks = generate_error_checks; + this.context_specific = context_specific; + this.generatorLM = generatorLM; + } - private void validateType(MethodDeclaration method, Class annotation_type, Class type) { - Class[] valid_types = type_map.getValidAnnotationTypes(type); - for ( Class valid_type : valid_types ) - if ( valid_type.equals(annotation_type) ) - return; - throw new RuntimeException(type + " is annotated with invalid native type " + annotation_type + - " in method " + method); - } + private void validateMethod(ExecutableElement method) { + if (method.isVarArgs()) { + throw new RuntimeException("Method " + method.getSimpleName() + " is variadic"); + } + Collection modifiers = method.getModifiers(); + if (!modifiers.contains(Modifier.PUBLIC)) { + throw new RuntimeException("Method " + method.getSimpleName() + " is not public"); + } + if (method.getThrownTypes().size() > 0) { + throw new RuntimeException("Method " + method.getSimpleName() + " throws checked exceptions"); + } + validateParameters(method); + StripPostfix strip_annotation = method.getAnnotation(StripPostfix.class); + if (strip_annotation != null && method.getAnnotation(Alternate.class) == null) { + String postfix_param_name = strip_annotation.value(); + VariableElement postfix_param = Utils.findParameter(method, postfix_param_name); + if (Utils.isParameterMultiTyped(postfix_param)) { + throw new RuntimeException("Postfix parameter can't be the same as a multityped parameter in method " + method); + } + if (Utils.getNIOBufferType(postfix_param.asType()) == null) { + throw new RuntimeException("Postfix parameter type must be a nio Buffer"); + } + } + if (Utils.getResultParameter(method) != null && !method.getReturnType().equals(env.getTypeUtils().getNoType(TypeKind.VOID))) { + throw new RuntimeException(method + " return type is not void but a parameter is annotated with Result"); + } + if (method.getAnnotation(CachedResult.class) != null) { + if (Utils.getNIOBufferType(Utils.getMethodReturnType(method)) == null) { + throw new RuntimeException(method + " return type is not a Buffer, but is annotated with CachedResult"); + } + if (method.getAnnotation(AutoSize.class) == null) { + throw new RuntimeException(method + " is annotated with CachedResult but misses an AutoSize annotation"); + } + } + validateTypes(method, method.getAnnotationMirrors(), method.getReturnType()); + } - private void validateTypes(MethodDeclaration method, Collection annotations, TypeMirror type_mirror) { - for (AnnotationMirror annotation : annotations) { - NativeType native_type_annotation = NativeTypeTranslator.getAnnotation(annotation, NativeType.class); - if (native_type_annotation != null) { - Class annotation_type = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType()); - Class type = Utils.getJavaType(type_mirror); - if (Buffer.class.equals(type)) - continue; - validateType(method, annotation_type, type); - } - } - } + private void validateType(ExecutableElement method, Class annotation_type, Class type) { + Class[] valid_types = type_map.getValidAnnotationTypes(type); + for (Class valid_type : valid_types) { + if (valid_type.equals(annotation_type)) { + return; + } + } + throw new RuntimeException(type + " is annotated with invalid native type " + annotation_type + + " in method " + method); + } - private void validateParameters(MethodDeclaration method) { - for (ParameterDeclaration param : method.getParameters()) { - validateTypes(method, param.getAnnotationMirrors(), param.getType()); - Class param_type = Utils.getJavaType(param.getType()); - if (Utils.getNIOBufferType(param.getType()) != null && param_type != CharSequence.class && param_type != CharSequence[].class) { - Check parameter_check_annotation = param.getAnnotation(Check.class); - NullTerminated null_terminated_annotation = param.getAnnotation(NullTerminated.class); - if (parameter_check_annotation == null && null_terminated_annotation == null) { - boolean found_auto_size_param = false; - for (ParameterDeclaration inner_param : method.getParameters()) { - AutoSize auto_size_annotation = inner_param.getAnnotation(AutoSize.class); - if (auto_size_annotation != null && - auto_size_annotation.value().equals(param.getSimpleName())) { - found_auto_size_param = true; - break; - } - } - if (!found_auto_size_param - && param.getAnnotation(Result.class) == null - && param.getAnnotation(Constant.class) == null - && !Utils.isReturnParameter(method, param) - ) - throw new RuntimeException(param + " has no Check, Result nor Constant annotation, is not the return parameter and no other parameter has" + - " an @AutoSize annotation on it in method " + method); - } - if (param.getAnnotation(CachedReference.class) != null && param.getAnnotation(Result.class) != null) - throw new RuntimeException(param + " can't be annotated with both CachedReference and Result"); - if (param.getAnnotation(BufferObject.class) != null && param.getAnnotation(Result.class) != null) - throw new RuntimeException(param + " can't be annotated with both BufferObject and Result"); - //if (param.getAnnotation(Constant.class) != null) - //throw new RuntimeException("Buffer parameter " + param + " cannot be Constant"); - } else { - if (param.getAnnotation(BufferObject.class) != null) - throw new RuntimeException(param + " type is not a buffer, but annotated as a BufferObject"); - if (param.getAnnotation(CachedReference.class) != null) - throw new RuntimeException(param + " type is not a buffer, but annotated as a CachedReference"); - } - } - } + private void validateTypes(ExecutableElement method, List annotations, TypeMirror type_mirror) { + for (AnnotationMirror annotation : annotations) { + NativeType native_type_annotation = NativeTypeTranslator.getAnnotation(annotation, NativeType.class); + if (native_type_annotation != null) { + Class annotation_type = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType()); + Class type = Utils.getJavaType(type_mirror); + if (Buffer.class.equals(type)) { + continue; + } + validateType(method, annotation_type, type); + } + } + } - private static void generateMethodsNativePointers(PrintWriter writer, Collection methods) { - for (MethodDeclaration method : methods) { - if ( method.getAnnotation(Alternate.class) == null ) - generateMethodNativePointers(writer, method); - } - } + private void validateParameters(ExecutableElement method) { + for (VariableElement param : method.getParameters()) { + validateTypes(method, param.getAnnotationMirrors(), param.asType()); + Class param_type = Utils.getJavaType(param.asType()); + if (Utils.getNIOBufferType(param.asType()) != null && param_type != CharSequence.class && param_type != CharSequence[].class) { + Check parameter_check_annotation = param.getAnnotation(Check.class); + NullTerminated null_terminated_annotation = param.getAnnotation(NullTerminated.class); + if (parameter_check_annotation == null && null_terminated_annotation == null) { + boolean found_auto_size_param = false; + for (VariableElement inner_param : method.getParameters()) { + AutoSize auto_size_annotation = inner_param.getAnnotation(AutoSize.class); + if (auto_size_annotation != null + && auto_size_annotation.value().equals(param.getSimpleName().toString())) { + found_auto_size_param = true; + break; + } + } + if (!found_auto_size_param + && param.getAnnotation(Result.class) == null + && param.getAnnotation(Constant.class) == null + && !Utils.isReturnParameter(method, param)) { + throw new RuntimeException(param + " has no Check, Result nor Constant annotation, is not the return parameter and no other parameter has" + + " an @AutoSize annotation on it in method " + method); + } + } + if (param.getAnnotation(CachedReference.class) != null && param.getAnnotation(Result.class) != null) { + throw new RuntimeException(param + " can't be annotated with both CachedReference and Result"); + } + if (param.getAnnotation(BufferObject.class) != null && param.getAnnotation(Result.class) != null) { + throw new RuntimeException(param + " can't be annotated with both BufferObject and Result"); + } + //if (param.getAnnotation(Constant.class) != null) + //throw new RuntimeException("Buffer parameter " + param + " cannot be Constant"); + } else { + if (param.getAnnotation(BufferObject.class) != null) { + throw new RuntimeException(param + " type is not a buffer, but annotated as a BufferObject"); + } + if (param.getAnnotation(CachedReference.class) != null) { + throw new RuntimeException(param + " type is not a buffer, but annotated as a CachedReference"); + } + } + } + } - private static void generateMethodNativePointers(PrintWriter writer, MethodDeclaration method) { - if ( method.getAnnotation(Extern.class) == null ) - writer.print("static "); - writer.println(Utils.getTypedefName(method) + " " + method.getSimpleName() + ";"); - } + private static void generateMethodsNativePointers(PrintWriter writer, Collection methods) { + for (ExecutableElement method : methods) { + if (method.getAnnotation(Alternate.class) == null) { + generateMethodNativePointers(writer, method); + } + } + } - private void generateJavaSource(InterfaceDeclaration d, PrintWriter java_writer) throws IOException { - java_writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */"); - java_writer.println(); - java_writer.println("package " + d.getPackage().getQualifiedName() + ";"); - java_writer.println(); - java_writer.println("import org.lwjgl.*;"); - java_writer.println("import java.nio.*;"); - Imports imports = d.getAnnotation(Imports.class); - if ( imports != null ) { - for ( String i : imports.value() ) - java_writer.println("import " + i + ";"); - } - java_writer.println(); - Utils.printDocComment(java_writer, d); - if ( d.getAnnotation(Private.class) == null ) - java_writer.print("public "); - boolean is_final = Utils.isFinal(d); - if (is_final) - java_writer.write("final "); - java_writer.print("class " + Utils.getSimpleClassName(d)); - Collection super_interfaces = d.getSuperinterfaces(); - if (super_interfaces.size() > 1) - throw new RuntimeException(d + " extends more than one interface"); - if (super_interfaces.size() == 1) { - InterfaceDeclaration super_interface = super_interfaces.iterator().next().getDeclaration(); - java_writer.print(" extends " + Utils.getSimpleClassName(super_interface)); - } - java_writer.println(" {"); - FieldsGenerator.generateFields(java_writer, d.getFields()); - java_writer.println(); - if (is_final) { - // Write private constructor to avoid instantiation - java_writer.println("\tprivate " + Utils.getSimpleClassName(d) + "() {}"); - } - if (d.getMethods().size() > 0 && !context_specific) { - java_writer.println(); - java_writer.println("\tstatic native void " + Utils.STUB_INITIALIZER_NAME + "() throws LWJGLException;"); - } - JavaMethodsGenerator.generateMethodsJava(env, type_map, java_writer, d, generate_error_checks, context_specific); - java_writer.println("}"); - java_writer.close(); - String qualified_interface_name = Utils.getQualifiedClassName(d); - env.getMessager().printNotice("Generated class " + qualified_interface_name); - } + private static void generateMethodNativePointers(PrintWriter writer, ExecutableElement method) { + if (method.getAnnotation(Extern.class) == null) { + writer.print("static "); + } + writer.println(Utils.getTypedefName(method) + " " + method.getSimpleName() + ";"); + } - private void generateNativeSource(InterfaceDeclaration d) throws IOException { - String qualified_interface_name = Utils.getQualifiedClassName(d); - String qualified_native_name = Utils.getNativeQualifiedName(qualified_interface_name)+ ".c"; - PrintWriter native_writer = env.getFiler().createTextFile(Filer.Location.CLASS_TREE, "", new File(qualified_native_name), "UTF-8"); - native_writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */"); - native_writer.println(); - native_writer.println("#include "); - type_map.printNativeIncludes(native_writer); - native_writer.println(); - TypedefsGenerator.generateNativeTypedefs(type_map, native_writer, d.getMethods()); - native_writer.println(); - if (!context_specific) { - generateMethodsNativePointers(native_writer, d.getMethods()); - native_writer.println(); - } - NativeMethodStubsGenerator.generateNativeMethodStubs(env, type_map, native_writer, d, generate_error_checks, context_specific); - if (!context_specific) { - native_writer.print("JNIEXPORT void JNICALL " + Utils.getQualifiedNativeMethodName(qualified_interface_name, Utils.STUB_INITIALIZER_NAME)); - native_writer.println("(JNIEnv *env, jclass clazz) {"); - native_writer.println("\tJavaMethodAndExtFunction functions[] = {"); - RegisterStubsGenerator.generateMethodsNativeStubBind(native_writer, d, generate_error_checks, context_specific); - native_writer.println("\t};"); - native_writer.println("\tint num_functions = NUMFUNCTIONS(functions);"); - native_writer.print("\t"); - native_writer.print(type_map.getRegisterNativesFunctionName()); - native_writer.println("(env, clazz, num_functions, functions);"); - native_writer.println("}"); - } - native_writer.close(); - env.getMessager().printNotice("Generated C source " + qualified_interface_name); - } + private void generateJavaSource(TypeElement d, PrintWriter java_writer) throws IOException { + java_writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */"); + java_writer.println(); + java_writer.println("package " + env.getElementUtils().getPackageOf(d).getQualifiedName().toString() + ";"); + java_writer.println(); + java_writer.println("import org.lwjgl.*;"); + java_writer.println("import java.nio.*;"); + Imports imports = d.getAnnotation(Imports.class); + if (imports != null) { + for (String i : imports.value()) { + java_writer.println("import " + i + ";"); + } + } + java_writer.println(); + Utils.printDocComment(java_writer, d, env); + if (d.getAnnotation(Private.class) == null) { + java_writer.print("public "); + } + boolean is_final = Utils.isFinal(d); + if (is_final) { + java_writer.write("final "); + } + java_writer.print("class " + Utils.getSimpleClassName(d)); + List super_interfaces = d.getInterfaces(); + if (super_interfaces.size() > 1) { + throw new RuntimeException(d + " extends more than one interface"); + } + if (super_interfaces.size() == 1) { + TypeMirror super_interface = super_interfaces.iterator().next(); + java_writer.print(" extends " + Utils.getSimpleClassName(env.getElementUtils().getTypeElement(super_interface.toString()))); + } + java_writer.println(" {"); + FieldsGenerator.generateFields(env, java_writer, Utils.getFields(d)); + java_writer.println(); + if (is_final) { + // Write private constructor to avoid instantiation + java_writer.println("\tprivate " + Utils.getSimpleClassName(d) + "() {}"); + } + if (Utils.getMethods(d).size() > 0 && !context_specific) { + java_writer.println(); + java_writer.println("\tstatic native void " + Utils.STUB_INITIALIZER_NAME + "() throws LWJGLException;"); + } + JavaMethodsGenerator.generateMethodsJava(env, type_map, java_writer, d, generate_error_checks, context_specific); + java_writer.println("}"); + java_writer.close(); + String qualified_interface_name = Utils.getQualifiedClassName(d); + env.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generated class " + qualified_interface_name); + } - public void visitInterfaceDeclaration(InterfaceDeclaration d) { - final File input = d.getPosition().file(); - final File outputJava = new File(env.getOptions().get("-s") + '/' + d.getPackage().getQualifiedName().replace('.', '/'), Utils.getSimpleClassName(d) + ".java"); + private void generateNativeSource(TypeElement d) throws IOException { + if (d.getKind().equals(ElementKind.ANNOTATION_TYPE)) { + return; + } + String qualified_interface_name = Utils.getQualifiedClassName(d); + String qualified_native_name = Utils.getNativeQualifiedName(qualified_interface_name) + ".c"; + PrintWriter native_writer = new PrintWriter(env.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", qualified_native_name).openWriter()); + native_writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */"); + native_writer.println(); + native_writer.println("#include "); + type_map.printNativeIncludes(native_writer); + native_writer.println(); + TypedefsGenerator.generateNativeTypedefs(type_map, native_writer, Utils.getMethods(d)); + native_writer.println(); + if (!context_specific) { + generateMethodsNativePointers(native_writer, Utils.getMethods(d)); + native_writer.println(); + } + NativeMethodStubsGenerator.generateNativeMethodStubs(env, type_map, native_writer, d, generate_error_checks, context_specific); + if (!context_specific) { + native_writer.print("JNIEXPORT void JNICALL " + Utils.getQualifiedNativeMethodName(qualified_interface_name, Utils.STUB_INITIALIZER_NAME)); + native_writer.println("(JNIEnv *env, jclass clazz) {"); + native_writer.println("\tJavaMethodAndExtFunction functions[] = {"); + RegisterStubsGenerator.generateMethodsNativeStubBind(env, native_writer, d, generate_error_checks, context_specific); + native_writer.println("\t};"); + native_writer.println("\tint num_functions = NUMFUNCTIONS(functions);"); + native_writer.print("\t"); + native_writer.print(type_map.getRegisterNativesFunctionName()); + native_writer.println("(env, clazz, num_functions, functions);"); + native_writer.println("}"); + } + native_writer.close(); + env.getMessager().printMessage(Kind.NOTE, "Generated C source " + qualified_interface_name); + } - PrintWriter java_writer = null; + @Override + public Void visitTypeAsInterface(TypeElement e, Void p) { + PrintWriter java_writer = null; + try { + final Collection methods = Utils.getMethods(e); + if (methods.isEmpty() && Utils.getFields(e).isEmpty()) { + return DEFAULT_VALUE; + } + env.getMessager().printMessage(Kind.NOTE, "methods count : " + Utils.getMethods(e).size() + " fields count : " + Utils.getFields(e).size(), e); + for (final ExecutableElement method : methods) { + validateMethod(method); + } + java_writer = new PrintWriter(env.getFiler().createSourceFile(Utils.getQualifiedClassName(e), env.getElementUtils().getPackageOf(e)).openWriter()); + generateJavaSource(e, java_writer); - try { - final Collection methods = d.getMethods(); - if ( methods.size() == 0 && d.getFields().size() == 0 ) - return; + if (methods.size() > 0) { + boolean noNative = true; + for (final ExecutableElement method : methods) { + Alternate alt_annotation = method.getAnnotation(Alternate.class); + if ((alt_annotation == null || alt_annotation.nativeAlt()) && method.getAnnotation(Reuse.class) == null) { + noNative = false; + break; + } + } + if (noNative) { + return DEFAULT_VALUE; + } - // Skip this class if the output exists and the input has not been modified. - if ( outputJava.exists() && Math.max(input.lastModified(), generatorLM) < outputJava.lastModified() ) - return; + boolean outputNativeExists = true, outputBackupExists = true; + File outputNative = null, outputBackup = null; + try { + final FileObject fo_outputNative = env.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", Utils.getNativeQualifiedName(Utils.getQualifiedClassName(e)).replace(".", "/") + ".c"); + outputNative = new File(fo_outputNative.toUri()); + outputNativeExists = outputNative.exists(); + final FileObject fo_outputBackup = env.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", Utils.getNativeQualifiedName(Utils.getQualifiedClassName(e)).replace(".", "/") + "_backup.c"); + outputBackup = new File(fo_outputBackup.toUri()); + outputBackupExists = outputBackup.exists(); + } catch (IOException ex) { + if (outputNative == null) { + outputNativeExists = false; + } + if (outputBackup == null) { + outputBackupExists = false; + } + } finally { + // If the native file exists, rename. + final ByteBuffer nativeBefore; + if (outputNativeExists) { + nativeBefore = readFile(outputNative); + if (outputBackupExists) { + outputBackup.delete(); + } + outputNative.renameTo(outputBackup); + } else { + nativeBefore = null; + } + try { + generateNativeSource(e); - for ( final MethodDeclaration method : methods ) - validateMethod(method); - java_writer = env.getFiler().createTextFile(Filer.Location.SOURCE_TREE, d.getPackage().getQualifiedName(), new File(Utils.getSimpleClassName(d) + ".java"), null); - generateJavaSource(d, java_writer); + // If the native file did exist, compare with the new file. If they're the same, + // reset the last modified time to avoid ridiculous C compilation times. + if (nativeBefore != null && outputNative.length() == nativeBefore.capacity()) { + final ByteBuffer nativeAfter = readFile(outputNative); + boolean same = true; + for (int i = nativeBefore.position(); i < nativeBefore.limit(); i++) { + if (nativeBefore.get(i) != nativeAfter.get(i)) { + same = false; + break; + } + } - if ( methods.size() > 0 ) { - boolean noNative = true; - for ( final MethodDeclaration method : methods ) { - Alternate alt_annotation = method.getAnnotation(Alternate.class); - if ( (alt_annotation == null || alt_annotation.nativeAlt()) && method.getAnnotation(Reuse.class) == null ) { - noNative = false; - break; - } - } - if ( noNative ) - return; + if (same) { + outputNative.delete(); + outputBackup.renameTo(outputNative); + } + } + } catch (IOException ex) { + throw new RuntimeException(ex); + } finally { + if (outputBackup.exists()) { + outputBackup.delete(); + } + } + } + } + return DEFAULT_VALUE; + } catch (Exception ex) { + // If anything goes wrong mid-gen, delete output to allow regen next time we run. + if (java_writer != null) { + java_writer.close(); + } + throw new RuntimeException(ex); + } + } - final String outputPath = env.getOptions().get("-d") + '/' + Utils.getNativeQualifiedName(Utils.getQualifiedClassName(d)); - final File outputNative = new File(outputPath + ".c"); - final File outputBackup = new File(outputPath + "_backup.c"); + private static ByteBuffer readFile(final File file) throws IOException { + final FileChannel channel = new FileInputStream(file).getChannel(); - // If the native file exists, rename. - final ByteBuffer nativeBefore; - if ( outputNative.exists() ) { - nativeBefore = readFile(outputNative); - outputNative.renameTo(outputBackup); - } else - nativeBefore = null; + final long bytesTotal = channel.size(); + final ByteBuffer buffer = ByteBuffer.allocateDirect((int) bytesTotal); - try { - generateNativeSource(d); + long bytesRead = 0; + do { + bytesRead += channel.read(buffer); + } while (bytesRead < bytesTotal); + buffer.flip(); - // If the native file did exist, compare with the new file. If they're the same, - // reset the last modified time to avoid ridiculous C compilation times. - if ( nativeBefore != null && outputNative.length() == nativeBefore.capacity() ) { - final ByteBuffer nativeAfter = readFile(outputNative); - boolean same = true; - for ( int i = nativeBefore.position(); i < nativeBefore.limit(); i++ ) { - if ( nativeBefore.get(i) != nativeAfter.get(i) ) { - same = false; - break; - } - } + channel.close(); - if ( same ) { - outputNative.delete(); - outputBackup.renameTo(outputNative); - } - } - } finally { - if ( outputBackup.exists() ) - outputBackup.delete(); - } - } - } catch (Exception e) { - // If anything goes wrong mid-gen, delete output to allow regen next time we run. - if ( java_writer != null ) java_writer.close(); - if ( outputJava.exists() ) outputJava.delete(); - - throw new RuntimeException(e); - } - } - - private static ByteBuffer readFile(final File file) throws IOException { - final FileChannel channel = new FileInputStream(file).getChannel(); - - final long bytesTotal = channel.size(); - final ByteBuffer buffer = ByteBuffer.allocateDirect((int)bytesTotal); - - long bytesRead = 0; - do { - bytesRead += channel.read(buffer); - } while ( bytesRead < bytesTotal ); - buffer.flip(); - - channel.close(); - - return buffer; - } + return buffer; + } } diff --git a/src/java/org/lwjgl/util/generator/JNITypeTranslator.java b/src/java/org/lwjgl/util/generator/JNITypeTranslator.java index 44bf8046..fd31a89a 100644 --- a/src/java/org/lwjgl/util/generator/JNITypeTranslator.java +++ b/src/java/org/lwjgl/util/generator/JNITypeTranslator.java @@ -32,12 +32,13 @@ package org.lwjgl.util.generator; -import org.lwjgl.PointerBuffer; - import java.nio.Buffer; - -import com.sun.mirror.type.*; -import com.sun.mirror.util.*; +import javax.lang.model.type.ArrayType; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.NoType; +import javax.lang.model.type.PrimitiveType; +import javax.lang.model.util.SimpleTypeVisitor6; +import org.lwjgl.PointerBuffer; /** * @@ -48,7 +49,7 @@ import com.sun.mirror.util.*; * @version $Revision$ * $Id$ */ -public class JNITypeTranslator implements TypeVisitor { +public class JNITypeTranslator extends SimpleTypeVisitor6 { private final StringBuilder signature = new StringBuilder(); @@ -62,11 +63,8 @@ public class JNITypeTranslator implements TypeVisitor { return objectReturn ? "jobject" : signature.toString(); } - public void visitAnnotationType(AnnotationType t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitArrayType(ArrayType t) { + @Override + public Void visitArray(ArrayType t, Void o) { final String className = t.getComponentType().toString(); if ( "java.lang.CharSequence".equals(className) ) signature.append("jlong"); @@ -76,9 +74,10 @@ public class JNITypeTranslator implements TypeVisitor { signature.append("jobjectArray"); else throw new RuntimeException(t + " is not allowed"); + return DEFAULT_VALUE; } - public void visitClassType(ClassType t) { + private void visitClassType(DeclaredType t) { final Class type = Utils.getJavaType(t); if ( Buffer.class.isAssignableFrom(type) || PointerBuffer.class.isAssignableFrom(type) ) { signature.append("jlong"); @@ -87,19 +86,15 @@ public class JNITypeTranslator implements TypeVisitor { signature.append("jobject"); } - public void visitDeclaredType(DeclaredType t) { - throw new RuntimeException(t + " is not allowed"); + @Override + public Void visitDeclared(DeclaredType t, Void o) { + if(t.asElement().getKind().isClass()) + visitClassType(t); + return DEFAULT_VALUE; } - public void visitEnumType(EnumType t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitInterfaceType(InterfaceType t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitPrimitiveType(PrimitiveType t) { + @Override + public Void visitPrimitive(PrimitiveType t, Void o) { String type; switch (t.getKind()) { case LONG: @@ -127,25 +122,13 @@ public class JNITypeTranslator implements TypeVisitor { throw new RuntimeException(t + " is not allowed"); } signature.append(type); + return DEFAULT_VALUE; } - public void visitReferenceType(ReferenceType t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitTypeMirror(TypeMirror t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitTypeVariable(TypeVariable t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitVoidType(VoidType t) { + @Override + public Void visitNoType(NoType t, Void o) { signature.append(t.toString()); + return DEFAULT_VALUE; } - - public void visitWildcardType(WildcardType t) { - throw new RuntimeException(t + " is not allowed"); - } + } diff --git a/src/java/org/lwjgl/util/generator/JavaMethodsGenerator.java b/src/java/org/lwjgl/util/generator/JavaMethodsGenerator.java index 0271f133..f0f04500 100644 --- a/src/java/org/lwjgl/util/generator/JavaMethodsGenerator.java +++ b/src/java/org/lwjgl/util/generator/JavaMethodsGenerator.java @@ -29,7 +29,6 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - package org.lwjgl.util.generator; /** @@ -37,710 +36,792 @@ package org.lwjgl.util.generator; * This class generates the methods in the generated java source files. * * @author elias_naur - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ - -import org.lwjgl.PointerBuffer; -import org.lwjgl.util.generator.opengl.GLreturn; - -import com.sun.mirror.apt.*; -import com.sun.mirror.declaration.*; -import com.sun.mirror.type.*; - import java.io.*; import java.nio.*; import java.util.*; -import java.util.regex.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.tools.Diagnostic; +import org.lwjgl.PointerBuffer; +import org.lwjgl.util.generator.opengl.GLreturn; public class JavaMethodsGenerator { - private static final String SAVED_PARAMETER_POSTFIX = "_saved"; - public static void generateMethodsJava(AnnotationProcessorEnvironment env, TypeMap type_map, PrintWriter writer, InterfaceDeclaration interface_decl, boolean generate_error_checks, boolean context_specific) { - for (MethodDeclaration method : interface_decl.getMethods()) - generateMethodJava(env, type_map, writer, interface_decl, method, generate_error_checks, context_specific); - } + private static final String SAVED_PARAMETER_POSTFIX = "_saved"; - private static void generateMethodJava(AnnotationProcessorEnvironment env, TypeMap type_map, PrintWriter writer, InterfaceDeclaration interface_decl, MethodDeclaration method, boolean generate_error_checks, boolean context_specific) { - writer.println(); - if (Utils.isMethodIndirect(generate_error_checks, context_specific, method)) { - if (method.getAnnotation(GenerateAutos.class) != null) { - printMethodWithMultiType(env, type_map, writer, interface_decl, method, TypeInfo.getDefaultTypeInfoMap(method), Mode.AUTOS, generate_error_checks, context_specific); - } - Collection> cross_product = TypeInfo.getTypeInfoCrossProduct(type_map, method); - for (Map typeinfos_instance : cross_product) { - printMethodWithMultiType(env, type_map, writer, interface_decl, method, typeinfos_instance, Mode.NORMAL, generate_error_checks, context_specific); - } - } - if ( method.getAnnotation(CachedResult.class) != null && !method.getAnnotation(CachedResult.class).isRange() ) { - printMethodWithMultiType(env, type_map, writer, interface_decl, method, TypeInfo.getDefaultTypeInfoMap(method), Mode.CACHEDRESULT, generate_error_checks, context_specific); - } + public static void generateMethodsJava(ProcessingEnvironment env, TypeMap type_map, PrintWriter writer, TypeElement interface_decl, boolean generate_error_checks, boolean context_specific) { + for (ExecutableElement method : Utils.getMethods(interface_decl)) { + generateMethodJava(env, type_map, writer, interface_decl, method, generate_error_checks, context_specific); + } + } - Reuse reuse_annotation = method.getAnnotation(Reuse.class); - Alternate alt_annotation = method.getAnnotation(Alternate.class); - if ( alt_annotation == null || (alt_annotation.nativeAlt() && !alt_annotation.skipNative()) ) { - if ( alt_annotation != null && method.getSimpleName().equals(alt_annotation.value()) ) - throw new RuntimeException("An alternate function with native code should have a different name than the main function."); + /** + * TODO : fix info multi-type methods print. + * + **/ + private static void generateMethodJava(ProcessingEnvironment env, TypeMap type_map, PrintWriter writer, TypeElement interface_decl, ExecutableElement method, boolean generate_error_checks, boolean context_specific) { + writer.println(); + if (Utils.isMethodIndirect(generate_error_checks, context_specific, method)) { + if (method.getAnnotation(GenerateAutos.class) != null) { + printMethodWithMultiType(env, type_map, writer, interface_decl, method, TypeInfo.getDefaultTypeInfoMap(method), Mode.AUTOS, generate_error_checks, context_specific); + } + Collection> cross_product = TypeInfo.getTypeInfoCrossProduct(env, type_map, method); + for (Map typeinfos_instance : cross_product) { + printMethodWithMultiType(env, type_map, writer, interface_decl, method, typeinfos_instance, Mode.NORMAL, generate_error_checks, context_specific); + } + } + if (method.getAnnotation(CachedResult.class) != null && !method.getAnnotation(CachedResult.class).isRange()) { + printMethodWithMultiType(env, type_map, writer, interface_decl, method, TypeInfo.getDefaultTypeInfoMap(method), Mode.CACHEDRESULT, generate_error_checks, context_specific); + } - if ( reuse_annotation == null ) - printJavaNativeStub(writer, method, Mode.NORMAL, generate_error_checks, context_specific); + Reuse reuse_annotation = method.getAnnotation(Reuse.class); + Alternate alt_annotation = method.getAnnotation(Alternate.class); + if (alt_annotation == null || (alt_annotation.nativeAlt() && !alt_annotation.skipNative())) { + if (alt_annotation != null && method.getSimpleName().toString().equals(alt_annotation.value())) { + throw new RuntimeException("An alternate function with native code should have a different name than the main function."); + } - if (Utils.hasMethodBufferObjectParameter(method)) { - printMethodWithMultiType(env, type_map, writer, interface_decl, method, TypeInfo.getDefaultTypeInfoMap(method), Mode.BUFFEROBJECT, generate_error_checks, context_specific); - if ( reuse_annotation == null ) - printJavaNativeStub(writer, method, Mode.BUFFEROBJECT, generate_error_checks, context_specific); - } - } - } + if (reuse_annotation == null) { + printJavaNativeStub(env, writer, method, Mode.NORMAL, generate_error_checks, context_specific); + } - private static void printJavaNativeStub(PrintWriter writer, MethodDeclaration method, Mode mode, boolean generate_error_checks, boolean context_specific) { - if (Utils.isMethodIndirect(generate_error_checks, context_specific, method)) { - writer.print("\tstatic native "); - } else { - Utils.printDocComment(writer, method); - writer.print("\tpublic static native "); - } - writer.print(getResultType(method, true)); - writer.print(" " + Utils.getSimpleNativeMethodName(method, generate_error_checks, context_specific)); - if (mode == Mode.BUFFEROBJECT) - writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX); - writer.print("("); - boolean first_parameter = generateParametersJava(writer, method, TypeInfo.getDefaultTypeInfoMap(method), true, true, mode); - if (context_specific) { - if (!first_parameter) - writer.print(", "); - writer.print("long " + Utils.FUNCTION_POINTER_VAR_NAME); - } - writer.println(");"); - } + if (Utils.hasMethodBufferObjectParameter(method)) { + printMethodWithMultiType(env, type_map, writer, interface_decl, method, TypeInfo.getDefaultTypeInfoMap(method), Mode.BUFFEROBJECT, generate_error_checks, context_specific); + if (reuse_annotation == null) { + printJavaNativeStub(env, writer, method, Mode.BUFFEROBJECT, generate_error_checks, context_specific); + } + } + } + } - private static boolean generateParametersJava(PrintWriter writer, MethodDeclaration method, Map typeinfos_instance, boolean native_stub, final boolean printTypes, Mode mode) { - boolean first_parameter = true; - for (ParameterDeclaration param : method.getParameters()) { - if ( native_stub && (param.getAnnotation(Helper.class) != null && !param.getAnnotation(Helper.class).passToNative()) ) - continue; - final Constant constant_annotation = param.getAnnotation(Constant.class); - if ( constant_annotation != null && constant_annotation.isNative() ) - continue; - AnnotationMirror auto_annotation_mirror = Utils.getParameterAutoAnnotation(param); - boolean hide_auto_parameter = mode == Mode.NORMAL && !native_stub && auto_annotation_mirror != null; - if (hide_auto_parameter) { - AutoType auto_type_annotation = param.getAnnotation(AutoType.class); - if (auto_type_annotation != null) { - ParameterDeclaration auto_parameter = Utils.findParameter(method, auto_type_annotation.value()); - TypeInfo auto_param_type_info = typeinfos_instance.get(auto_parameter); - if (auto_param_type_info.getSignedness() == Signedness.BOTH) { - if (!first_parameter) - writer.print(", "); - first_parameter = false; - if ( printTypes ) - writer.print("boolean "); - writer.print(TypeInfo.UNSIGNED_PARAMETER_NAME); - } - } - } else if ( - param.getAnnotation(Result.class) == null - && (native_stub || ((param.getAnnotation(Constant.class) == null || param.getAnnotation(Constant.class).keepParam()) && !Utils.isReturnParameter(method, param))) - && (mode != Mode.AUTOS || getAutoTypeParameter(method, param) == null) - ) { - first_parameter = generateParameterJava(writer, param, typeinfos_instance.get(param), native_stub, printTypes, first_parameter, mode); - } - } - CachedResult cached_result_annotation = method.getAnnotation(CachedResult.class); - TypeMirror result_type = Utils.getMethodReturnType(method); - if ((native_stub && Utils.getNIOBufferType(result_type) != null) || Utils.needResultSize(method)) { - AutoSize auto_size_annotation = method.getAnnotation(AutoSize.class); - if ( auto_size_annotation == null || !auto_size_annotation.isNative() ) { - if (cached_result_annotation == null || !cached_result_annotation.isRange()) { - if (!first_parameter) - writer.print(", "); - first_parameter = false; - if ( printTypes ) - writer.print("long "); - writer.print(Utils.RESULT_SIZE_NAME); - } - } - } - if (cached_result_annotation != null) { - if (!first_parameter) - writer.print(", "); + private static void printJavaNativeStub(ProcessingEnvironment env, PrintWriter writer, ExecutableElement method, Mode mode, boolean generate_error_checks, boolean context_specific) { + if (Utils.isMethodIndirect(generate_error_checks, context_specific, method)) { + writer.print("\tstatic native "); + } else { + Utils.printDocComment(writer, method, env); + writer.print("\tpublic static native "); + } + writer.print(getResultType(method, true)); + writer.print(" " + Utils.getSimpleNativeMethodName(method, generate_error_checks, context_specific)); + if (mode == Mode.BUFFEROBJECT) { + writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX); + } + writer.print("("); + boolean first_parameter = generateParametersJava(env, writer, method, TypeInfo.getDefaultTypeInfoMap(method), true, true, mode); + if (context_specific) { + if (!first_parameter) { + writer.print(", "); + } + writer.print("long " + Utils.FUNCTION_POINTER_VAR_NAME); + } + writer.println(");"); + } - if ( mode == Mode.CACHEDRESULT ) { - if ( printTypes ) - writer.print("long "); - writer.print(Utils.CACHED_BUFFER_LENGTH_NAME + ", "); - } + private static boolean generateParametersJava(ProcessingEnvironment env, PrintWriter writer, ExecutableElement method, Map typeinfos_instance, boolean native_stub, final boolean printTypes, Mode mode) { + boolean first_parameter = true; + for (VariableElement param : method.getParameters()) { + if (native_stub && (param.getAnnotation(Helper.class) != null && !param.getAnnotation(Helper.class).passToNative())) { + continue; + } + final Constant constant_annotation = param.getAnnotation(Constant.class); + if (constant_annotation != null && constant_annotation.isNative()) { + continue; + } + /*env.getMessager().printMessage(Diagnostic.Kind.NOTE, param.getAnnotationMirrors() + + " (" + typeinfos_instance.get(param).getType() + ")", param);*/ + AnnotationMirror auto_annotation_mirror = Utils.getParameterAutoAnnotation(param); + boolean hide_auto_parameter = mode == Mode.NORMAL && !native_stub && auto_annotation_mirror != null; + if (hide_auto_parameter) { + AutoType auto_type_annotation = param.getAnnotation(AutoType.class); + if (auto_type_annotation != null) { + VariableElement auto_parameter = Utils.findParameter(method, auto_type_annotation.value()); + TypeInfo auto_param_type_info = typeinfos_instance.get(auto_parameter); + if (auto_param_type_info.getSignedness() == Signedness.BOTH) { + if (!first_parameter) { + writer.print(", "); + } + first_parameter = false; + if (printTypes) { + writer.print("boolean "); + } + writer.print(TypeInfo.UNSIGNED_PARAMETER_NAME); + } + } + } else if (param.getAnnotation(Result.class) == null + && (native_stub || ((param.getAnnotation(Constant.class) == null || param.getAnnotation(Constant.class).keepParam()) && !Utils.isReturnParameter(method, param))) + && (mode != Mode.AUTOS || getAutoTypeParameter(method, param) == null)) { + first_parameter = generateParameterJava(writer, param, typeinfos_instance.get(param), native_stub, printTypes, first_parameter, mode); + } + } + CachedResult cached_result_annotation = method.getAnnotation(CachedResult.class); + TypeMirror result_type = Utils.getMethodReturnType(method); + if ((native_stub && Utils.getNIOBufferType(result_type) != null) || Utils.needResultSize(method)) { + AutoSize auto_size_annotation = method.getAnnotation(AutoSize.class); + if (auto_size_annotation == null || !auto_size_annotation.isNative()) { + if (cached_result_annotation == null || !cached_result_annotation.isRange()) { + if (!first_parameter) { + writer.print(", "); + } + first_parameter = false; + if (printTypes) { + writer.print("long "); + } + writer.print(Utils.RESULT_SIZE_NAME); + } + } + } + if (cached_result_annotation != null) { + if (!first_parameter) { + writer.print(", "); + } - first_parameter = false; - if ( printTypes ) - writer.print(getResultType(method, native_stub)); - writer.print(" " + Utils.CACHED_BUFFER_NAME); - } - return first_parameter; - } + if (mode == Mode.CACHEDRESULT) { + if (printTypes) { + writer.print("long "); + } + writer.print(Utils.CACHED_BUFFER_LENGTH_NAME + ", "); + } - private static boolean generateParameterJava(PrintWriter writer, ParameterDeclaration param, TypeInfo type_info, boolean native_stub, final boolean printTypes, boolean first_parameter, Mode mode) { - Class buffer_type = Utils.getNIOBufferType(param.getType()); - if (!first_parameter) - writer.print(", "); - BufferObject bo_annotation = param.getAnnotation(BufferObject.class); - if (bo_annotation != null && mode == Mode.BUFFEROBJECT) { - if (buffer_type == null) - throw new RuntimeException("type of " + param + " is not a nio Buffer parameter but is annotated as buffer object"); - if ( printTypes ) - writer.print("long "); - writer.print(param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX); - } else { - if ( native_stub && param.getAnnotation(PointerWrapper.class) != null ) - writer.print("long "); - else { - Class type = type_info.getType(); - if ( native_stub && (type == CharSequence.class || type == CharSequence[].class || type == PointerBuffer.class || Buffer.class.isAssignableFrom(type) ) ) - writer.print("long "); - else if ( printTypes ) - writer.print(type_info.getType().getSimpleName() + " "); - } - AutoSize auto_size_annotation = param.getAnnotation(AutoSize.class); - if ( auto_size_annotation != null ) - writer.print(auto_size_annotation.value() + "_"); - writer.print(param.getSimpleName()); - } - return false; - } + first_parameter = false; + if (printTypes) { + writer.print(getResultType(method, native_stub)); + } + writer.print(" " + Utils.CACHED_BUFFER_NAME); + } + return first_parameter; + } - private static void printBufferObjectCheck(PrintWriter writer, BufferKind kind, Mode mode, boolean context_specific) { - String bo_check_method_name = kind.toString(); - writer.print("\t\t" + Utils.CHECKS_CLASS_NAME + ".ensure" + bo_check_method_name); - if (mode == Mode.BUFFEROBJECT) - writer.print("enabled"); - else - writer.print("disabled"); + private static boolean generateParameterJava(PrintWriter writer, VariableElement param, TypeInfo type_info, boolean native_stub, final boolean printTypes, boolean first_parameter, Mode mode) { + Class buffer_type = Utils.getNIOBufferType(param.asType()); + if (!first_parameter) { + writer.print(", "); + } + BufferObject bo_annotation = param.getAnnotation(BufferObject.class); + if (bo_annotation != null && mode == Mode.BUFFEROBJECT) { + if (buffer_type == null) { + throw new RuntimeException("type of " + param + " is not a nio Buffer parameter but is annotated as buffer object"); + } + if (printTypes) { + writer.print("long "); + } + writer.print(param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX); + } else { + if (native_stub && param.getAnnotation(PointerWrapper.class) != null) { + writer.print("long "); + } else { + Class type = type_info.getType(); + if (native_stub && (type == CharSequence.class || type == CharSequence[].class || type == PointerBuffer.class || Buffer.class.isAssignableFrom(type))) { + writer.print("long "); + } else if (printTypes) { + writer.print(type.getSimpleName() + " "); + } + } + AutoSize auto_size_annotation = param.getAnnotation(AutoSize.class); + if (auto_size_annotation != null) { + writer.print(auto_size_annotation.value() + "_"); + } + writer.print(param.getSimpleName()); + } + return false; + } - if ( context_specific ) - writer.println("(caps);"); - else - writer.println("();"); - } + private static void printBufferObjectCheck(PrintWriter writer, BufferKind kind, Mode mode, boolean context_specific) { + String bo_check_method_name = kind.toString(); + writer.print("\t\t" + Utils.CHECKS_CLASS_NAME + ".ensure" + bo_check_method_name); + if (mode == Mode.BUFFEROBJECT) { + writer.print("enabled"); + } else { + writer.print("disabled"); + } - private static void printBufferObjectChecks(PrintWriter writer, MethodDeclaration method, Mode mode, boolean context_specific) { - EnumSet check_set = EnumSet.noneOf(BufferKind.class); - for (ParameterDeclaration param : method.getParameters()) { - BufferObject bo_annotation = param.getAnnotation(BufferObject.class); - if (bo_annotation != null) - check_set.add(bo_annotation.value()); - } - for (BufferKind kind : check_set) - printBufferObjectCheck(writer, kind, mode, context_specific); - } + if (context_specific) { + writer.println("(caps);"); + } else { + writer.println("();"); + } + } - private static void printMethodWithMultiType(AnnotationProcessorEnvironment env, TypeMap type_map, PrintWriter writer, InterfaceDeclaration interface_decl, MethodDeclaration method, Map typeinfos_instance, Mode mode, boolean generate_error_checks, boolean context_specific) { - Utils.printDocComment(writer, method); - if ( method.getAnnotation(Deprecated.class) != null ) - writer.println("\t@Deprecated"); - if ( interface_decl.getAnnotation(Private.class) == null && method.getAnnotation(Private.class) == null ) - writer.print("\tpublic static "); - else - writer.print("\tstatic "); - writer.print(getResultType(method, false)); - StripPostfix strip_annotation = method.getAnnotation(StripPostfix.class); - String method_name; - Alternate alt_annotation = method.getAnnotation(Alternate.class); - method_name = alt_annotation == null || alt_annotation.javaAlt() ? method.getSimpleName() : alt_annotation.value(); - if (strip_annotation != null && mode == Mode.NORMAL) - method_name = getPostfixStrippedName(type_map, interface_decl, method); - writer.print(" " + method_name + "("); - generateParametersJava(writer, method, typeinfos_instance, false, true, mode); - writer.println(") {"); + private static void printBufferObjectChecks(PrintWriter writer, ExecutableElement method, Mode mode, boolean context_specific) { + EnumSet check_set = EnumSet.noneOf(BufferKind.class); + for (VariableElement param : method.getParameters()) { + BufferObject bo_annotation = param.getAnnotation(BufferObject.class); + if (bo_annotation != null) { + check_set.add(bo_annotation.value()); + } + } + for (BufferKind kind : check_set) { + printBufferObjectCheck(writer, kind, mode, context_specific); + } + } - final TypeMirror result_type = Utils.getMethodReturnType(method); - boolean has_result = !result_type.equals(env.getTypeUtils().getVoidType()); + private static void printMethodWithMultiType(ProcessingEnvironment env, TypeMap type_map, PrintWriter writer, TypeElement interface_decl, ExecutableElement method, Map typeinfos_instance, Mode mode, boolean generate_error_checks, boolean context_specific) { + Utils.printDocComment(writer, method, env); + if (method.getAnnotation(Deprecated.class) != null) { + writer.println("\t@Deprecated"); + } + if (interface_decl.getAnnotation(Private.class) == null && method.getAnnotation(Private.class) == null) { + writer.print("\tpublic static "); + } else { + writer.print("\tstatic "); + } + writer.print(getResultType(method, false)); + StripPostfix strip_annotation = method.getAnnotation(StripPostfix.class); + String method_name; + Alternate alt_annotation = method.getAnnotation(Alternate.class); + method_name = alt_annotation == null || alt_annotation.javaAlt() ? method.getSimpleName().toString() : alt_annotation.value(); + if (strip_annotation != null && mode == Mode.NORMAL) { + method_name = getPostfixStrippedName(type_map, interface_decl, method); + } + writer.print(" " + method_name + "("); + generateParametersJava(env, writer, method, typeinfos_instance, false, true, mode); + writer.println(") {"); - final Reuse reuse_annotation = method.getAnnotation(Reuse.class); - if ( reuse_annotation != null ) { - writer.print("\t\t"); - if ( has_result || method.getAnnotation(GLreturn.class) != null ) - writer.print("return "); + final TypeMirror result_type = Utils.getMethodReturnType(method); + boolean has_result = !result_type.equals(env.getTypeUtils().getNoType(TypeKind.VOID)); - writer.print(reuse_annotation.value() + "." + (reuse_annotation.method().length() > 0 ? reuse_annotation.method() : method_name) + "("); - generateParametersJava(writer, method, typeinfos_instance, false, false, mode); - writer.println(");\n\t}"); - return; - } + final Reuse reuse_annotation = method.getAnnotation(Reuse.class); + if (reuse_annotation != null) { + writer.print("\t\t"); + if (has_result || method.getAnnotation(GLreturn.class) != null) { + writer.print("return "); + } - if (context_specific) { - type_map.printCapabilitiesInit(writer); - writer.print("\t\tlong " + Utils.FUNCTION_POINTER_VAR_NAME + " = " + type_map.getCapabilities() + "."); - writer.println(Utils.getFunctionAddressName(interface_decl, method, true) + ";"); - writer.print("\t\tBufferChecks.checkFunctionAddress("); - writer.println(Utils.FUNCTION_POINTER_VAR_NAME + ");"); - } - final Code code_annotation = method.getAnnotation(Code.class); - if (code_annotation != null && code_annotation.value().length() > 0) - writer.println(code_annotation.value()); - printBufferObjectChecks(writer, method, mode, context_specific); - printParameterChecks(writer, method, typeinfos_instance, mode, generate_error_checks); - printParameterCaching(writer, interface_decl, method, mode, context_specific); + writer.print(reuse_annotation.value() + "." + (reuse_annotation.method().length() > 0 ? reuse_annotation.method() : method_name) + "("); + generateParametersJava(env, writer, method, typeinfos_instance, false, false, mode); + writer.println(");\n\t}"); + return; + } - if ( code_annotation != null && code_annotation.javaBeforeNative().length() > 0 ) - writer.println(code_annotation.javaBeforeNative()); - writer.print("\t\t"); + if (context_specific) { + type_map.printCapabilitiesInit(writer); + writer.print("\t\tlong " + Utils.FUNCTION_POINTER_VAR_NAME + " = " + type_map.getCapabilities() + "."); + writer.println(Utils.getFunctionAddressName(interface_decl, method, true) + ";"); + writer.print("\t\tBufferChecks.checkFunctionAddress("); + writer.println(Utils.FUNCTION_POINTER_VAR_NAME + ");"); + } + final Code code_annotation = method.getAnnotation(Code.class); + if (code_annotation != null && code_annotation.value().length() > 0) { + writer.println(code_annotation.value()); + } + printBufferObjectChecks(writer, method, mode, context_specific); + printParameterChecks(writer, method, typeinfos_instance, mode, generate_error_checks); + printParameterCaching(writer, interface_decl, method, mode, context_specific); - final PointerWrapper pointer_wrapper_annotation = method.getAnnotation(PointerWrapper.class); - if (has_result) { - writer.print(getResultType(method, false) + " " + Utils.RESULT_VAR_NAME); + if (code_annotation != null && code_annotation.javaBeforeNative().length() > 0) { + writer.println(code_annotation.javaBeforeNative()); + } + writer.print("\t\t"); - if ( code_annotation != null && code_annotation.tryBlock() ) { - writer.print(" = " + getDefaultResultValue(method)); - writer.println(";\n\t\ttry {"); - writer.print("\t\t\t" + Utils.RESULT_VAR_NAME); - } + final PointerWrapper pointer_wrapper_annotation = method.getAnnotation(PointerWrapper.class); + if (has_result) { + writer.print(getResultType(method, false) + " " + Utils.RESULT_VAR_NAME); - writer.print(" = "); - if ( pointer_wrapper_annotation != null ) { - if ( pointer_wrapper_annotation.factory().length() > 0 ) - writer.print(pointer_wrapper_annotation.factory() + "("); - else - writer.print("new " + getResultType(method, false) + "("); - } - } else if ( method.getAnnotation(GLreturn.class) != null ) { - has_result = true; - Utils.printGLReturnPre(writer, method, method.getAnnotation(GLreturn.class), type_map); - } - writer.print(Utils.getSimpleNativeMethodName(method, generate_error_checks, context_specific)); - if (mode == Mode.BUFFEROBJECT) - writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX); - writer.print("("); - boolean first_parameter = printMethodCallArguments(writer, method, typeinfos_instance, mode, type_map); - if (context_specific) { - if (!first_parameter) - writer.print(", "); - writer.print(Utils.FUNCTION_POINTER_VAR_NAME); - } - if ( has_result && pointer_wrapper_annotation != null ) { - writer.print(")"); - if ( pointer_wrapper_annotation.params().length() > 0 ) - writer.print(", " + pointer_wrapper_annotation.params()); - } - writer.println(");"); + if (code_annotation != null && code_annotation.tryBlock()) { + writer.print(" = " + getDefaultResultValue(method)); + writer.println(";\n\t\ttry {"); + writer.print("\t\t\t" + Utils.RESULT_VAR_NAME); + } - if ( code_annotation != null && code_annotation.javaAfterNative().length() > 0 ) - writer.println(code_annotation.javaAfterNative()); - - final String tabs = code_annotation != null && code_annotation.tryBlock() ? "\t\t\t" : "\t\t"; - if (generate_error_checks && method.getAnnotation(NoErrorCheck.class) == null) - type_map.printErrorCheckMethod(writer, method, tabs); - // DISABLED: indirect buffer support - //printNondirectParameterCopies(writer, method, mode); - if (has_result) { - if ( method.getAnnotation(GLreturn.class) == null ) { - if ( ByteBuffer.class.equals(Utils.getJavaType(result_type)) ) - writer.println(tabs + "return LWJGLUtil.CHECKS && " + Utils.RESULT_VAR_NAME + " == null ? null : " + Utils.RESULT_VAR_NAME + ".order(ByteOrder.nativeOrder());"); // safeNewBuffer returns a direct ByteBuffer with BIG_ENDIAN order. - else - writer.println(tabs + "return " + Utils.RESULT_VAR_NAME + ";"); - } else - Utils.printGLReturnPost(writer, method, method.getAnnotation(GLreturn.class), type_map); - } - - if ( code_annotation != null && code_annotation.tryBlock() ) { - writer.println("\t\t} finally {"); - writer.println(code_annotation.javaFinally()); - writer.println("\t\t}"); - } - writer.println("\t}"); - } - - private static String getExtensionPostfix(InterfaceDeclaration interface_decl) { - String interface_simple_name = interface_decl.getSimpleName(); - Extension extension_annotation = interface_decl.getAnnotation(Extension.class); - if (extension_annotation == null) { - int underscore_index = interface_simple_name.indexOf("_"); - if (underscore_index != -1) - return interface_simple_name.substring(0, underscore_index); - else - return ""; - } else - return extension_annotation.postfix(); - } - - private static ParameterDeclaration getAutoTypeParameter(MethodDeclaration method, ParameterDeclaration target_parameter) { - for (ParameterDeclaration param : method.getParameters()) { - AnnotationMirror auto_annotation = Utils.getParameterAutoAnnotation(param); - if (auto_annotation != null) { - Class annotation_type = NativeTypeTranslator.getClassFromType(auto_annotation.getAnnotationType()); - String parameter_name; - if (annotation_type.equals(AutoType.class)) - parameter_name = param.getAnnotation(AutoType.class).value(); - else if (annotation_type.equals(AutoSize.class)) - parameter_name = param.getAnnotation(AutoSize.class).value(); - else - throw new RuntimeException("Unknown annotation type " + annotation_type); - if (target_parameter.getSimpleName().equals(parameter_name)) - return param; - } - } - return null; - } - - private static boolean hasAnyParameterAutoTypeAnnotation(MethodDeclaration method, ParameterDeclaration target_param) { - for (ParameterDeclaration param : method.getParameters()) { - AutoType auto_type_annotation = param.getAnnotation(AutoType.class); - if (auto_type_annotation != null) { - ParameterDeclaration type_target_param = Utils.findParameter(method, auto_type_annotation.value()); - if (target_param.equals(type_target_param)) - return true; - } - } - return false; - } - - private static final Map postfixPatterns = new HashMap(); - - private static Pattern getPostfixPattern(String regex) { - Pattern pattern = postfixPatterns.get(regex); - if ( pattern == null ) - postfixPatterns.put(regex, pattern = Pattern.compile(regex)); - return pattern; - } - - private static String getPostfixStrippedName(TypeMap type_map, InterfaceDeclaration interface_decl, MethodDeclaration method) { - StripPostfix strip_annotation = method.getAnnotation(StripPostfix.class); - ParameterDeclaration postfix_parameter = Utils.findParameter(method, strip_annotation.value()); - String postfix = strip_annotation.postfix(); - boolean postfixOverride = !("NULL".equals(postfix) && strip_annotation.hasPostfix()); - if ( !postfixOverride ) { - PostfixTranslator translator = new PostfixTranslator(type_map, postfix_parameter); - postfix_parameter.getType().accept(translator); - postfix = translator.getSignature(); - } else if ( !strip_annotation.hasPostfix() ) - postfix = ""; - - String method_name; - Alternate alt_annotation = method.getAnnotation(Alternate.class); - method_name = alt_annotation == null || alt_annotation.javaAlt() ? method.getSimpleName() : alt_annotation.value(); - - String extension_postfix = "NULL".equals(strip_annotation.extension()) ? getExtensionPostfix(interface_decl) : strip_annotation.extension(); - - Matcher matcher = getPostfixPattern( - postfixOverride - ? (postfix + "(?:v)?" + extension_postfix + "$") - : ("(?:" + postfix + "(?:v)?|i(?:64)?_v|v)" + extension_postfix + "$") - ).matcher(method_name); - - if ( !matcher.find() ) - throw new RuntimeException(method_name + " is specified as being postfix stripped on parameter " + postfix_parameter + ", but it's postfix is neither '" + postfix + "' nor 'v'"); - - return method_name.substring(0, matcher.start()) + extension_postfix; - } - - private static int getBufferElementSizeExponent(Class c) { - if (IntBuffer.class.equals(c)) - return 2; - else if (LongBuffer.class.equals(c)) - return 3; - else if (DoubleBuffer.class.equals(c)) - return 3; - else if (ShortBuffer.class.equals(c)) - return 1; - else if (ByteBuffer.class.equals(c)) - return 0; - else if (FloatBuffer.class.equals(c)) - return 2; - else - throw new RuntimeException(c + " is not allowed"); - } - - private static boolean printMethodCallArgument(PrintWriter writer, MethodDeclaration method, ParameterDeclaration param, Map typeinfos_instance, Mode mode, boolean first_parameter, TypeMap type_map) { - if (!first_parameter) - writer.print(", "); - - AnnotationMirror auto_annotation = Utils.getParameterAutoAnnotation(param); - Constant constant_annotation = param.getAnnotation(Constant.class); - if (constant_annotation != null) { - writer.print(constant_annotation.value()); - } else if (auto_annotation != null && mode == Mode.NORMAL) { - Class param_type = NativeTypeTranslator.getClassFromType(auto_annotation.getAnnotationType()); - if (AutoType.class.equals(param_type)) { - final AutoType auto_type_annotation = param.getAnnotation(AutoType.class); - final ParameterDeclaration auto_parameter = Utils.findParameter(method, auto_type_annotation.value()); - final String auto_type = typeinfos_instance.get(auto_parameter).getAutoType(); - if ( auto_type == null ) - throw new RuntimeException("No auto type for parameter " + param.getSimpleName() + " in method " + method); - writer.print(auto_type); - } else if (AutoSize.class.equals(param_type)) { - final AutoSize auto_size_annotation = param.getAnnotation(AutoSize.class); - if ( !auto_size_annotation.useExpression() ) { - final String auto_parameter_name = auto_size_annotation.value(); - final ParameterDeclaration auto_target_param = Utils.findParameter(method, auto_parameter_name); - final TypeInfo auto_target_type_info = typeinfos_instance.get(auto_target_param); - final boolean shift_remaining = !hasAnyParameterAutoTypeAnnotation(method, auto_target_param) && Utils.isParameterMultiTyped(auto_target_param); - int shifting = 0; - if ( shift_remaining ) { - shifting = getBufferElementSizeExponent(auto_target_type_info.getType()); - if ( shifting > 0 ) - writer.print("("); - } - if ( auto_size_annotation.canBeNull() ) - writer.print("(" + auto_parameter_name + " == null ? 0 : " + auto_parameter_name + ".remaining())"); - else - writer.print(auto_parameter_name + ".remaining()"); - // Shift the remaining if the target parameter is multityped and there's no AutoType to track type - if (shift_remaining && shifting > 0) { - writer.print(" << " + shifting); - writer.print(")"); - } - } - writer.print(auto_size_annotation.expression()); - } else - throw new RuntimeException("Unknown auto annotation " + param_type); - } else { - if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) { - writer.print(param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX); - } else { - Class type = typeinfos_instance.get(param).getType(); - Check check_annotation = param.getAnnotation(Check.class); - boolean hide_buffer = mode == Mode.AUTOS && getAutoTypeParameter(method, param) != null; - if (hide_buffer) { - writer.print("0L"); - } else { - if ( type == CharSequence.class || type == CharSequence[].class ) { - final String offset = Utils.getStringOffset(method, param); - - writer.print("APIUtil.getBuffer"); - if ( param.getAnnotation(NullTerminated.class) != null ) - writer.print("NT"); - writer.print('('); - writer.print(type_map.getAPIUtilParam(true)); - writer.print(param.getSimpleName()); - if ( offset != null ) - writer.print(", " + offset); - writer.print(")"); - } else { - final AutoSize auto_size_annotation = param.getAnnotation(AutoSize.class); - if ( auto_size_annotation != null ) - writer.print(auto_size_annotation.value() + "_"); - - final Class buffer_type = Utils.getNIOBufferType(param.getType()); - if ( buffer_type == null ) - writer.print(param.getSimpleName()); - else { - writer.print("MemoryUtil.getAddress"); - if ( check_annotation != null && check_annotation.canBeNull() ) - writer.print("Safe"); - writer.print("("); - writer.print(param.getSimpleName()); - writer.print(")"); - } - } - } - if ( type != long.class ) { - PointerWrapper pointer_annotation = param.getAnnotation(PointerWrapper.class); - if ( pointer_annotation != null ) { - if ( pointer_annotation.canBeNull() ) - writer.print(" == null ? 0 : " + param.getSimpleName()); - writer.print(".getPointer()"); - } - } - } - } - return false; - } - - private static boolean printMethodCallArguments(PrintWriter writer, MethodDeclaration method, Map typeinfos_instance, Mode mode, TypeMap type_map) { - boolean first_parameter = true; - for ( ParameterDeclaration param : method.getParameters() ) { - if ( param.getAnnotation(Result.class) != null || (param.getAnnotation(Helper.class) != null && !param.getAnnotation(Helper.class).passToNative()) ) - continue; - - final Constant constant_annotation = param.getAnnotation(Constant.class); - if ( constant_annotation== null || !constant_annotation.isNative() ) - first_parameter = printMethodCallArgument(writer, method, param, typeinfos_instance, mode, first_parameter, type_map); - } - if (Utils.getNIOBufferType(Utils.getMethodReturnType(method)) != null) { - if (method.getAnnotation(CachedResult.class) != null && method.getAnnotation(CachedResult.class).isRange()) { - first_parameter = false; - Utils.printExtraCallArguments(writer, method, ""); - } else { - AutoSize auto_size_annotation = method.getAnnotation(AutoSize.class); - if ( auto_size_annotation == null || !auto_size_annotation.isNative() ) { - if (!first_parameter) - writer.print(", "); - first_parameter = false; - - String result_size_expression; - if ( mode == Mode.CACHEDRESULT ) - result_size_expression = Utils.CACHED_BUFFER_LENGTH_NAME; - else if ( auto_size_annotation == null ) - result_size_expression = Utils.RESULT_SIZE_NAME; - else - result_size_expression = auto_size_annotation.value(); - - Utils.printExtraCallArguments(writer, method, result_size_expression); - } - } - } - return first_parameter; - } - - private static void printParameterCaching(PrintWriter writer, InterfaceDeclaration interface_decl, MethodDeclaration method, Mode mode, boolean context_specific) { - for (ParameterDeclaration param : method.getParameters()) { - Class java_type = Utils.getJavaType(param.getType()); - CachedReference cachedReference = param.getAnnotation(CachedReference.class); - if (Buffer.class.isAssignableFrom(java_type) && - cachedReference != null && - (mode != Mode.BUFFEROBJECT || param.getAnnotation(BufferObject.class) == null) && - param.getAnnotation(Result.class) == null) { - writer.print("\t\tif ( LWJGLUtil.CHECKS ) StateTracker."); - if ( context_specific ) - writer.print("getReferences(caps)."); - else - writer.print("getTracker()."); - if(cachedReference.name().length() > 0) { - writer.print(cachedReference.name()); + writer.print(" = "); + if (pointer_wrapper_annotation != null) { + if (pointer_wrapper_annotation.factory().length() > 0) { + writer.print(pointer_wrapper_annotation.factory() + "("); } else { - writer.print(Utils.getReferenceName(interface_decl, method, param)); + writer.print("new " + getResultType(method, false) + "("); } - if(cachedReference.index().length() > 0) { - writer.print("[" + cachedReference.index() + "]"); + } + } else if (method.getAnnotation(GLreturn.class) != null) { + has_result = true; + Utils.printGLReturnPre(writer, method, method.getAnnotation(GLreturn.class), type_map); + } + writer.print(Utils.getSimpleNativeMethodName(method, generate_error_checks, context_specific)); + if (mode == Mode.BUFFEROBJECT) { + writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX); + } + writer.print("("); + boolean first_parameter = printMethodCallArguments(writer, method, typeinfos_instance, mode, type_map); + if (context_specific) { + if (!first_parameter) { + writer.print(", "); + } + writer.print(Utils.FUNCTION_POINTER_VAR_NAME); + } + if (has_result && pointer_wrapper_annotation != null) { + writer.print(")"); + if (pointer_wrapper_annotation.params().length() > 0) { + writer.print(", " + pointer_wrapper_annotation.params()); + } + } + writer.println(");"); + + if (code_annotation != null && code_annotation.javaAfterNative().length() > 0) { + writer.println(code_annotation.javaAfterNative()); + } + + final String tabs = code_annotation != null && code_annotation.tryBlock() ? "\t\t\t" : "\t\t"; + if (generate_error_checks && method.getAnnotation(NoErrorCheck.class) == null) { + type_map.printErrorCheckMethod(writer, method, tabs); + } + // DISABLED: indirect buffer support + //printNondirectParameterCopies(writer, method, mode); + if (has_result) { + if (method.getAnnotation(GLreturn.class) == null) { + if (ByteBuffer.class.equals(Utils.getJavaType(result_type))) { + writer.println(tabs + "return LWJGLUtil.CHECKS && " + Utils.RESULT_VAR_NAME + " == null ? null : " + Utils.RESULT_VAR_NAME + ".order(ByteOrder.nativeOrder());"); // safeNewBuffer returns a direct ByteBuffer with BIG_ENDIAN order. + } else { + writer.println(tabs + "return " + Utils.RESULT_VAR_NAME + ";"); } - writer.println(" = " + param.getSimpleName() + ";"); - } - } - } + } else { + Utils.printGLReturnPost(writer, method, method.getAnnotation(GLreturn.class), type_map); + } + } - private static void printParameterChecks(PrintWriter writer, MethodDeclaration method, Map typeinfos, Mode mode, final boolean generate_error_checks) { - if ( mode == Mode.NORMAL ) { - final GenerateAutos gen_autos_annotation = method.getAnnotation(GenerateAutos.class); - if ( gen_autos_annotation != null && gen_autos_annotation.sizeVariables().length > 0 ) { - // For the auto-generated parameters, declare and init a size variable (that can be reused by @Code) - for ( final ParameterDeclaration param : method.getParameters() ) { - if ( Arrays.binarySearch(gen_autos_annotation.sizeVariables(), param.getSimpleName()) >= 0 ) { - final int shifting = getBufferElementSizeExponent(typeinfos.get(param).getType()); - final Check check_annotation = param.getAnnotation(Check.class); + if (code_annotation != null && code_annotation.tryBlock()) { + writer.println("\t\t} finally {"); + writer.println(code_annotation.javaFinally()); + writer.println("\t\t}"); + } + writer.println("\t}"); + } - writer.print("\t\tlong " + param.getSimpleName() + "_size = "); - if ( check_annotation == null || !check_annotation.canBeNull() ) - writer.println(param.getSimpleName() + ".remaining() << " + shifting + ";"); - else - writer.println(param.getSimpleName() + " == null ? 0 : " + param.getSimpleName() + ".remaining() << " + shifting + ";"); - } - } - } - } + private static String getExtensionPostfix(TypeElement interface_decl) { + String interface_simple_name = interface_decl.getSimpleName().toString(); + Extension extension_annotation = interface_decl.getAnnotation(Extension.class); + if (extension_annotation == null) { + int underscore_index = interface_simple_name.indexOf("_"); + if (underscore_index != -1) { + return interface_simple_name.substring(0, underscore_index); + } else { + return ""; + } + } else { + return extension_annotation.postfix(); + } + } - for (ParameterDeclaration param : method.getParameters()) { - Class java_type = Utils.getJavaType(param.getType()); - if ( java_type.isArray() || (Utils.isAddressableType(java_type) && - (mode != Mode.BUFFEROBJECT || param.getAnnotation(BufferObject.class) == null) && - (mode != Mode.AUTOS || getAutoTypeParameter(method, param) == null) && - param.getAnnotation(Result.class) == null && - !Utils.isReturnParameter(method, param)) ) { - String check_value = null; - boolean can_be_null = false; - Check check_annotation = param.getAnnotation(Check.class); - if (check_annotation != null) { - check_value = check_annotation.value(); - can_be_null = check_annotation.canBeNull(); - } - if ((Buffer.class.isAssignableFrom(java_type) || PointerBuffer.class.isAssignableFrom(java_type)) && param.getAnnotation(Constant.class) == null) { - boolean out_parameter = param.getAnnotation(OutParameter.class) != null; - TypeInfo typeinfo = typeinfos.get(param); - printParameterCheck(writer, method, param.getSimpleName(), typeinfo.getType().getSimpleName(), check_value, can_be_null, param.getAnnotation(NullTerminated.class), out_parameter, generate_error_checks); - } else if ( String.class.equals(java_type)) { - if (!can_be_null) - writer.println("\t\tBufferChecks.checkNotNull(" + param.getSimpleName() + ");"); - } else if ( java_type.isArray() ) { - final TypeInfo typeinfo = typeinfos.get(param); - printArrayParameterCheck(writer, param.getSimpleName(), typeinfo.getType().getSimpleName(), check_value, can_be_null); - } - } - } - if (method.getAnnotation(CachedResult.class) != null) - printParameterCheck(writer, method, Utils.CACHED_BUFFER_NAME, null, null, true, null, false, generate_error_checks); - } + private static VariableElement getAutoTypeParameter(ExecutableElement method, VariableElement target_parameter) { + for (VariableElement param : method.getParameters()) { + AnnotationMirror auto_annotation = Utils.getParameterAutoAnnotation(param); + if (auto_annotation != null) { + Class annotation_type = NativeTypeTranslator.getClassFromType(auto_annotation.getAnnotationType()); + String parameter_name; + if (annotation_type.equals(AutoType.class)) { + parameter_name = param.getAnnotation(AutoType.class).value(); + } else if (annotation_type.equals(AutoSize.class)) { + parameter_name = param.getAnnotation(AutoSize.class).value(); + } else { + throw new RuntimeException("Unknown annotation type " + annotation_type); + } + if (target_parameter.getSimpleName().toString().equals(parameter_name)) { + return param; + } + } + } + return null; + } - private static void printParameterCheck(PrintWriter writer, MethodDeclaration method, String name, String type, String check_value, boolean can_be_null, NullTerminated null_terminated, boolean out_parameter, boolean generate_error_checks) { - String tabs; - if (can_be_null) { - writer.print("\t\tif (" + name + " != null)"); - if ( null_terminated != null ) - writer.println(" {"); - else - writer.println(); - tabs = "\t\t\t"; - } else - tabs = "\t\t"; - writer.print(tabs + "BufferChecks.check"); - if (check_value != null && check_value.length() > 0) { - writer.print("Buffer"); - if ( "Buffer".equals(type) ) - writer.print("Size"); // Check size only, Buffer.isDirect() was added in 1.6, cannot use yet. TODO: Remove? - writer.print("(" + name + ", " + check_value); - } else { - writer.print("Direct(" + name); - } - writer.println(");"); - if ( can_be_null && generate_error_checks ) { - final Check check_annotation = method.getAnnotation(Check.class); - if ( check_annotation != null && check_annotation.value().equals(name) ) { - writer.println("\t\telse"); - writer.println("\t\t\t" + name + " = APIUtil.getBufferIntDebug();"); // Use an exclusive buffer here - } - } - if (null_terminated != null) { - writer.print(tabs + "BufferChecks.checkNullTerminated("); - writer.print(name); - if ( null_terminated.value().length() > 0 ) { - writer.print(", "); - writer.print(null_terminated.value()); - } - writer.println(");"); - if ( can_be_null ) - writer.println("\t\t}"); - } - } + private static boolean hasAnyParameterAutoTypeAnnotation(ExecutableElement method, VariableElement target_param) { + for (VariableElement param : method.getParameters()) { + AutoType auto_type_annotation = param.getAnnotation(AutoType.class); + if (auto_type_annotation != null) { + VariableElement type_target_param = Utils.findParameter(method, auto_type_annotation.value()); + if (target_param.equals(type_target_param)) { + return true; + } + } + } + return false; + } - private static void printArrayParameterCheck(PrintWriter writer, String name, String type, String check_value, boolean can_be_null) { - String tabs; - if ( can_be_null ) { - writer.println("\t\tif (" + name + " != null)"); - tabs = "\t\t\t"; - } else - tabs = "\t\t"; + private static final Map postfixPatterns = new HashMap<>(); - writer.print(tabs + "BufferChecks.checkArray(" + name); - if ( check_value != null && check_value.length() > 0) - writer.print(", " + check_value); - writer.println(");"); - } + private static Pattern getPostfixPattern(String regex) { + Pattern pattern = postfixPatterns.get(regex); + if (pattern == null) { + postfixPatterns.put(regex, pattern = Pattern.compile(regex)); + } + return pattern; + } - private static String getResultType(MethodDeclaration method, boolean native_stub) { - if ( native_stub && method.getAnnotation(PointerWrapper.class) != null ) - return "long"; - else if ( !native_stub && method.getAnnotation(GLreturn.class) != null ) - return Utils.getMethodReturnType(method, method.getAnnotation(GLreturn.class), false); - else - return Utils.getJavaType(Utils.getMethodReturnType(method)).getSimpleName(); - } + private static String getPostfixStrippedName(TypeMap type_map, TypeElement interface_decl, ExecutableElement method) { + StripPostfix strip_annotation = method.getAnnotation(StripPostfix.class); + VariableElement postfix_parameter = Utils.findParameter(method, strip_annotation.value()); + String postfix = strip_annotation.postfix(); + boolean postfixOverride = !("NULL".equals(postfix) && strip_annotation.hasPostfix()); + if (!postfixOverride) { + PostfixTranslator translator = new PostfixTranslator(type_map, postfix_parameter); + postfix_parameter.asType().accept(translator, null); + postfix = translator.getSignature(); + } else if (!strip_annotation.hasPostfix()) { + postfix = ""; + } - private static String getDefaultResultValue(MethodDeclaration method) { - if ( method.getAnnotation(GLreturn.class) != null ) { - final String type = Utils.getMethodReturnType(method, method.getAnnotation(GLreturn.class), false); - if ( "boolean".equals(type) ) - return "false"; - else if ( Character.isLowerCase(type.charAt(0)) ) - return "0"; - else - return "null"; - } else { - final Class type = Utils.getJavaType(Utils.getMethodReturnType(method)); - if ( type.isPrimitive() ) { - if ( type == boolean.class ) - return "false"; - else - return "0"; - } else - return "null"; - } - } + String method_name; + Alternate alt_annotation = method.getAnnotation(Alternate.class); + method_name = alt_annotation == null || alt_annotation.javaAlt() ? method.getSimpleName().toString() : alt_annotation.value(); + + String extension_postfix = "NULL".equals(strip_annotation.extension()) ? getExtensionPostfix(interface_decl) : strip_annotation.extension(); + + Matcher matcher = getPostfixPattern( + postfixOverride + ? (postfix + "(?:v)?" + extension_postfix + "$") + : ("(?:" + postfix + "(?:v)?|i(?:64)?_v|v)" + extension_postfix + "$") + ).matcher(method_name); + + if (!matcher.find()) { + throw new RuntimeException(method_name + " is specified as being postfix stripped on parameter " + postfix_parameter + ", but it's postfix is neither '" + postfix + "' nor 'v'"); + } + + return method_name.substring(0, matcher.start()) + extension_postfix; + } + + private static int getBufferElementSizeExponent(Class c) { + if (IntBuffer.class.equals(c)) { + return 2; + } else if (LongBuffer.class.equals(c)) { + return 3; + } else if (DoubleBuffer.class.equals(c)) { + return 3; + } else if (ShortBuffer.class.equals(c)) { + return 1; + } else if (ByteBuffer.class.equals(c)) { + return 0; + } else if (FloatBuffer.class.equals(c)) { + return 2; + } else { + throw new RuntimeException(c + " is not allowed"); + } + } + + private static boolean printMethodCallArgument(PrintWriter writer, ExecutableElement method, VariableElement param, Map typeinfos_instance, Mode mode, boolean first_parameter, TypeMap type_map) { + if (!first_parameter) { + writer.print(", "); + } + + AnnotationMirror auto_annotation = Utils.getParameterAutoAnnotation(param); + Constant constant_annotation = param.getAnnotation(Constant.class); + if (constant_annotation != null) { + writer.print(constant_annotation.value()); + } else if (auto_annotation != null && mode == Mode.NORMAL) { + Class param_type = NativeTypeTranslator.getClassFromType(auto_annotation.getAnnotationType()); + if (AutoType.class.equals(param_type)) { + final AutoType auto_type_annotation = param.getAnnotation(AutoType.class); + final VariableElement auto_parameter = Utils.findParameter(method, auto_type_annotation.value()); + final String auto_type = typeinfos_instance.get(auto_parameter).getAutoType(); + if (auto_type == null) { + throw new RuntimeException("No auto type for parameter " + param.getSimpleName() + " in method " + method); + } + writer.print(auto_type); + } else if (AutoSize.class.equals(param_type)) { + final AutoSize auto_size_annotation = param.getAnnotation(AutoSize.class); + if (!auto_size_annotation.useExpression()) { + final String auto_parameter_name = auto_size_annotation.value(); + final VariableElement auto_target_param = Utils.findParameter(method, auto_parameter_name); + final TypeInfo auto_target_type_info = typeinfos_instance.get(auto_target_param); + final boolean shift_remaining = !hasAnyParameterAutoTypeAnnotation(method, auto_target_param) && Utils.isParameterMultiTyped(auto_target_param); + int shifting = 0; + if (shift_remaining) { + shifting = getBufferElementSizeExponent(auto_target_type_info.getType()); + if (shifting > 0) { + writer.print("("); + } + } + if (auto_size_annotation.canBeNull()) { + writer.print("(" + auto_parameter_name + " == null ? 0 : " + auto_parameter_name + ".remaining())"); + } else { + writer.print(auto_parameter_name + ".remaining()"); + } + // Shift the remaining if the target parameter is multityped and there's no AutoType to track type + if (shift_remaining && shifting > 0) { + writer.print(" << " + shifting); + writer.print(")"); + } + } + writer.print(auto_size_annotation.expression()); + } else { + throw new RuntimeException("Unknown auto annotation " + param_type); + } + } else { + if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) { + writer.print(param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX); + } else { + Class type = typeinfos_instance.get(param).getType(); + Check check_annotation = param.getAnnotation(Check.class); + boolean hide_buffer = mode == Mode.AUTOS && getAutoTypeParameter(method, param) != null; + if (hide_buffer) { + writer.print("0L"); + } else { + if (type == CharSequence.class || type == CharSequence[].class) { + final String offset = Utils.getStringOffset(method, param); + + writer.print("APIUtil.getBuffer"); + if (param.getAnnotation(NullTerminated.class) != null) { + writer.print("NT"); + } + writer.print('('); + writer.print(type_map.getAPIUtilParam(true)); + writer.print(param.getSimpleName()); + if (offset != null) { + writer.print(", " + offset); + } + writer.print(")"); + } else { + final AutoSize auto_size_annotation = param.getAnnotation(AutoSize.class); + if (auto_size_annotation != null) { + writer.print(auto_size_annotation.value() + "_"); + } + + final Class buffer_type = Utils.getNIOBufferType(param.asType()); + if (buffer_type == null) { + writer.print(param.getSimpleName()); + } else { + writer.print("MemoryUtil.getAddress"); + if (check_annotation != null && check_annotation.canBeNull()) { + writer.print("Safe"); + } + writer.print("("); + writer.print(param.getSimpleName()); + writer.print(")"); + } + } + } + if (type != long.class) { + PointerWrapper pointer_annotation = param.getAnnotation(PointerWrapper.class); + if (pointer_annotation != null) { + if (pointer_annotation.canBeNull()) { + writer.print(" == null ? 0 : " + param.getSimpleName()); + } + writer.print(".getPointer()"); + } + } + } + } + return false; + } + + private static boolean printMethodCallArguments(PrintWriter writer, ExecutableElement method, Map typeinfos_instance, Mode mode, TypeMap type_map) { + boolean first_parameter = true; + for (VariableElement param : method.getParameters()) { + if (param.getAnnotation(Result.class) != null || (param.getAnnotation(Helper.class) != null && !param.getAnnotation(Helper.class).passToNative())) { + continue; + } + + final Constant constant_annotation = param.getAnnotation(Constant.class); + if (constant_annotation == null || !constant_annotation.isNative()) { + first_parameter = printMethodCallArgument(writer, method, param, typeinfos_instance, mode, first_parameter, type_map); + } + } + if (Utils.getNIOBufferType(Utils.getMethodReturnType(method)) != null) { + if (method.getAnnotation(CachedResult.class) != null && method.getAnnotation(CachedResult.class).isRange()) { + first_parameter = false; + Utils.printExtraCallArguments(writer, method, ""); + } else { + AutoSize auto_size_annotation = method.getAnnotation(AutoSize.class); + if (auto_size_annotation == null || !auto_size_annotation.isNative()) { + if (!first_parameter) { + writer.print(", "); + } + first_parameter = false; + + String result_size_expression; + if (mode == Mode.CACHEDRESULT) { + result_size_expression = Utils.CACHED_BUFFER_LENGTH_NAME; + } else if (auto_size_annotation == null) { + result_size_expression = Utils.RESULT_SIZE_NAME; + } else { + result_size_expression = auto_size_annotation.value(); + } + + Utils.printExtraCallArguments(writer, method, result_size_expression); + } + } + } + return first_parameter; + } + + private static void printParameterCaching(PrintWriter writer, TypeElement interface_decl, ExecutableElement method, Mode mode, boolean context_specific) { + for (VariableElement param : method.getParameters()) { + Class java_type = Utils.getJavaType(param.asType()); + CachedReference cachedReference = param.getAnnotation(CachedReference.class); + if (Buffer.class.isAssignableFrom(java_type) + && cachedReference != null + && (mode != Mode.BUFFEROBJECT || param.getAnnotation(BufferObject.class) == null) + && param.getAnnotation(Result.class) == null) { + writer.print("\t\tif ( LWJGLUtil.CHECKS ) StateTracker."); + if (context_specific) { + writer.print("getReferences(caps)."); + } else { + writer.print("getTracker()."); + } + if (cachedReference.name().length() > 0) { + writer.print(cachedReference.name()); + } else { + writer.print(Utils.getReferenceName(interface_decl, method, param)); + } + if (cachedReference.index().length() > 0) { + writer.print("[" + cachedReference.index() + "]"); + } + writer.println(" = " + param.getSimpleName() + ";"); + } + } + } + + private static void printParameterChecks(PrintWriter writer, ExecutableElement method, Map typeinfos, Mode mode, final boolean generate_error_checks) { + if (mode == Mode.NORMAL) { + final GenerateAutos gen_autos_annotation = method.getAnnotation(GenerateAutos.class); + if (gen_autos_annotation != null && gen_autos_annotation.sizeVariables().length > 0) { + // For the auto-generated parameters, declare and init a size variable (that can be reused by @Code) + for (final VariableElement param : method.getParameters()) { + if (Arrays.binarySearch(gen_autos_annotation.sizeVariables(), param.getSimpleName().toString()) >= 0) { + final int shifting = getBufferElementSizeExponent(typeinfos.get(param).getType()); + final Check check_annotation = param.getAnnotation(Check.class); + + writer.print("\t\tlong " + param.getSimpleName() + "_size = "); + if (check_annotation == null || !check_annotation.canBeNull()) { + writer.println(param.getSimpleName() + ".remaining() << " + shifting + ";"); + } else { + writer.println(param.getSimpleName() + " == null ? 0 : " + param.getSimpleName() + ".remaining() << " + shifting + ";"); + } + } + } + } + } + + for (VariableElement param : method.getParameters()) { + Class java_type = Utils.getJavaType(param.asType()); + if (java_type.isArray() || (Utils.isAddressableType((Class) java_type) + && (mode != Mode.BUFFEROBJECT || param.getAnnotation(BufferObject.class) == null) + && (mode != Mode.AUTOS || getAutoTypeParameter(method, param) == null) + && param.getAnnotation(Result.class) == null + && !Utils.isReturnParameter(method, param))) { + String check_value = null; + boolean can_be_null = false; + Check check_annotation = param.getAnnotation(Check.class); + if (check_annotation != null) { + check_value = check_annotation.value(); + can_be_null = check_annotation.canBeNull(); + } + if ((Buffer.class.isAssignableFrom(java_type) || PointerBuffer.class.isAssignableFrom(java_type)) && param.getAnnotation(Constant.class) == null) { + boolean out_parameter = param.getAnnotation(OutParameter.class) != null; + TypeInfo typeinfo = typeinfos.get(param); + printParameterCheck(writer, method, param.getSimpleName().toString(), typeinfo.getType().getSimpleName(), check_value, can_be_null, param.getAnnotation(NullTerminated.class), out_parameter, generate_error_checks); + } else if (String.class.equals(java_type)) { + if (!can_be_null) { + writer.println("\t\tBufferChecks.checkNotNull(" + param.getSimpleName() + ");"); + } + } else if (java_type.isArray()) { + final TypeInfo typeinfo = typeinfos.get(param); + printArrayParameterCheck(writer, param.getSimpleName().toString(), typeinfo.getType().getSimpleName(), check_value, can_be_null); + } + } + } + if (method.getAnnotation(CachedResult.class) != null) { + printParameterCheck(writer, method, Utils.CACHED_BUFFER_NAME, null, null, true, null, false, generate_error_checks); + } + } + + private static void printParameterCheck(PrintWriter writer, ExecutableElement method, String name, String type, String check_value, boolean can_be_null, NullTerminated null_terminated, boolean out_parameter, boolean generate_error_checks) { + String tabs; + if (can_be_null) { + writer.print("\t\tif (" + name + " != null)"); + if (null_terminated != null) { + writer.println(" {"); + } else { + writer.println(); + } + tabs = "\t\t\t"; + } else { + tabs = "\t\t"; + } + writer.print(tabs + "BufferChecks.check"); + if (check_value != null && check_value.length() > 0) { + writer.print("Buffer"); + if ("Buffer".equals(type)) { + writer.print("Size"); // Check size only, Buffer.isDirect() was added in 1.6, cannot use yet. TODO: Remove? + } + writer.print("(" + name + ", " + check_value); + } else { + writer.print("Direct(" + name); + } + writer.println(");"); + if (can_be_null && generate_error_checks) { + final Check check_annotation = method.getAnnotation(Check.class); + if (check_annotation != null && check_annotation.value().equals(name)) { + writer.println("\t\telse"); + writer.println("\t\t\t" + name + " = APIUtil.getBufferIntDebug();"); // Use an exclusive buffer here + } + } + if (null_terminated != null) { + writer.print(tabs + "BufferChecks.checkNullTerminated("); + writer.print(name); + if (null_terminated.value().length() > 0) { + writer.print(", "); + writer.print(null_terminated.value()); + } + writer.println(");"); + if (can_be_null) { + writer.println("\t\t}"); + } + } + } + + private static void printArrayParameterCheck(PrintWriter writer, String name, String type, String check_value, boolean can_be_null) { + String tabs; + if (can_be_null) { + writer.println("\t\tif (" + name + " != null)"); + tabs = "\t\t\t"; + } else { + tabs = "\t\t"; + } + + writer.print(tabs + "BufferChecks.checkArray(" + name); + if (check_value != null && check_value.length() > 0) { + writer.print(", " + check_value); + } + writer.println(");"); + } + + private static String getResultType(ExecutableElement method, boolean native_stub) { + if (native_stub && method.getAnnotation(PointerWrapper.class) != null) { + return "long"; + } else if (!native_stub && method.getAnnotation(GLreturn.class) != null) { + return Utils.getMethodReturnType(method, method.getAnnotation(GLreturn.class), false); + } else { + return Utils.getJavaType(Utils.getMethodReturnType(method)).getSimpleName(); + } + } + + private static String getDefaultResultValue(ExecutableElement method) { + if (method.getAnnotation(GLreturn.class) != null) { + final String type = Utils.getMethodReturnType(method, method.getAnnotation(GLreturn.class), false); + if ("boolean".equals(type)) { + return "false"; + } else if (Character.isLowerCase(type.charAt(0))) { + return "0"; + } else { + return "null"; + } + } else { + final Class type = Utils.getJavaType(Utils.getMethodReturnType(method)); + if (type.isPrimitive()) { + if (type == boolean.class) { + return "false"; + } else { + return "0"; + } + } else { + return "null"; + } + } + } } diff --git a/src/java/org/lwjgl/util/generator/JavaTypeTranslator.java b/src/java/org/lwjgl/util/generator/JavaTypeTranslator.java index 69b0bbba..b67e1440 100644 --- a/src/java/org/lwjgl/util/generator/JavaTypeTranslator.java +++ b/src/java/org/lwjgl/util/generator/JavaTypeTranslator.java @@ -29,132 +29,133 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - package org.lwjgl.util.generator; -import org.lwjgl.opencl.CLMem; - import java.nio.ByteBuffer; - -import com.sun.mirror.type.*; -import com.sun.mirror.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.lang.model.type.ArrayType; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.NoType; +import javax.lang.model.type.PrimitiveType; +import javax.lang.model.type.TypeKind; +import static javax.lang.model.type.TypeKind.BOOLEAN; +import static javax.lang.model.type.TypeKind.BYTE; +import static javax.lang.model.type.TypeKind.DOUBLE; +import static javax.lang.model.type.TypeKind.FLOAT; +import static javax.lang.model.type.TypeKind.INT; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.SimpleTypeVisitor6; /** - * A TypeVisitor that translates (annotated) TypeMirrors to - * java types (represented by a Class) + * A TypeVisitor that translates (annotated) TypeMirrors to java types + * (represented by a Class) * * @author elias_naur - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ -public class JavaTypeTranslator implements TypeVisitor { - private Class type; +public class JavaTypeTranslator extends SimpleTypeVisitor6 { - public Class getType() { - return type; - } + private Class type; - public void visitAnnotationType(AnnotationType t) { - throw new RuntimeException(t + " is not allowed"); - } + public Class getType() { + return type; + } - public void visitArrayType(ArrayType t) { - final TypeMirror componentType = t.getComponentType(); - if ( componentType instanceof PrimitiveType ) { - type = getPrimitiveArrayClassFromKind(((PrimitiveType)componentType).getKind()); - } else { - try { - final Class c = Class.forName(t.getComponentType().toString()); - if ( CharSequence.class.isAssignableFrom(c) || ByteBuffer.class.isAssignableFrom(c) || org.lwjgl.PointerWrapper.class.isAssignableFrom(c) ) - type = Class.forName("[L" + t.getComponentType() + ";"); - else { - throw new RuntimeException(t + " is not allowed"); - } - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - } + @Override + public Void visitArray(ArrayType t, Void o) { + final TypeMirror componentType = t.getComponentType(); + try { + final Class c = Class.forName(t.getComponentType().toString()); + if (CharSequence.class.isAssignableFrom(c) || ByteBuffer.class.isAssignableFrom(c) || org.lwjgl.PointerWrapper.class.isAssignableFrom(c)) { + type = Class.forName("[L" + t.getComponentType() + ";"); + } + } catch (ClassNotFoundException ex) { + type = null; + } finally { + if (type == null) { + if (componentType instanceof PrimitiveType) { + type = getPrimitiveArrayClassFromKind(((PrimitiveType) componentType).getKind()); + } else { + throw new RuntimeException(t + " is not allowed"); + } + } + return DEFAULT_VALUE; + } + } - public static Class getPrimitiveClassFromKind(PrimitiveType.Kind kind) { - switch ( kind ) { - case LONG: - return long.class; - case INT: - return int.class; - case DOUBLE: - return double.class; - case FLOAT: - return float.class; - case SHORT: - return short.class; - case BYTE: - return byte.class; - case BOOLEAN: - return boolean.class; - default: - throw new RuntimeException(kind + " is not allowed"); - } - } + public static Class getPrimitiveClassFromKind(TypeKind kind) { + switch (kind) { + case LONG: + return long.class; + case INT: + return int.class; + case DOUBLE: + return double.class; + case FLOAT: + return float.class; + case SHORT: + return short.class; + case BYTE: + return byte.class; + case BOOLEAN: + return boolean.class; + default: + throw new RuntimeException(kind + " is not allowed"); + } + } - private static Class getPrimitiveArrayClassFromKind(PrimitiveType.Kind kind) { - switch ( kind ) { - case LONG: - return long[].class; - case INT: - return int[].class; - case DOUBLE: - return double[].class; - case FLOAT: - return float[].class; - case SHORT: - return short[].class; - case BYTE: - return byte[].class; - case BOOLEAN: - return boolean[].class; - default: - throw new RuntimeException(kind + " is not allowed"); - } - } + private static Class getPrimitiveArrayClassFromKind(TypeKind kind) { + switch (kind) { + case LONG: + return long[].class; + case INT: + return int[].class; + case DOUBLE: + return double[].class; + case FLOAT: + return float[].class; + case SHORT: + return short[].class; + case BYTE: + return byte[].class; + case BOOLEAN: + return boolean[].class; + default: + throw new RuntimeException(kind + " is not allowed"); + } + } - public void visitPrimitiveType(PrimitiveType t) { - type = getPrimitiveClassFromKind(t.getKind()); - } + @Override + public Void visitPrimitive(PrimitiveType t, Void p) { + type = getPrimitiveClassFromKind(t.getKind()); + return DEFAULT_VALUE; + } - public void visitDeclaredType(DeclaredType t) { - throw new RuntimeException(t + " is not allowed"); - } + @Override + public Void visitDeclared(DeclaredType t, Void o) { + if (t.asElement().getKind().isClass()) { + visitClassType(t); + } else if (t.asElement().getKind().isInterface()) { + visitInterfaceType(t); + } else { + throw new RuntimeException(t.asElement().getKind() + " is not allowed"); + } + return DEFAULT_VALUE; + } - public void visitEnumType(EnumType t) { - throw new RuntimeException(t + " is not allowed"); - } + private void visitClassType(DeclaredType t) { + type = NativeTypeTranslator.getClassFromType(t); + } - public void visitClassType(ClassType t) { - type = NativeTypeTranslator.getClassFromType(t); - } + private void visitInterfaceType(DeclaredType t) { + type = NativeTypeTranslator.getClassFromType(t); + } - public void visitInterfaceType(InterfaceType t) { - type = NativeTypeTranslator.getClassFromType(t); - } + @Override + public Void visitNoType(NoType t, Void p) { + type = void.class; + return DEFAULT_VALUE; + } - public void visitReferenceType(ReferenceType t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitTypeMirror(TypeMirror t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitTypeVariable(TypeVariable t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitVoidType(VoidType t) { - type = void.class; - } - - public void visitWildcardType(WildcardType t) { - throw new RuntimeException(t + " is not allowed"); - } } diff --git a/src/java/org/lwjgl/util/generator/NativeMethodStubsGenerator.java b/src/java/org/lwjgl/util/generator/NativeMethodStubsGenerator.java index 04f8ee76..bd010b11 100644 --- a/src/java/org/lwjgl/util/generator/NativeMethodStubsGenerator.java +++ b/src/java/org/lwjgl/util/generator/NativeMethodStubsGenerator.java @@ -41,15 +41,17 @@ package org.lwjgl.util.generator; * $Id$ */ -import org.lwjgl.PointerBuffer; - -import com.sun.mirror.apt.*; -import com.sun.mirror.declaration.*; -import com.sun.mirror.type.*; - import java.io.*; -import java.util.*; import java.nio.*; +import java.util.*; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.Element; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import org.lwjgl.PointerBuffer; public class NativeMethodStubsGenerator { private static final String BUFFER_ADDRESS_POSTFIX = "_address"; @@ -57,8 +59,8 @@ public class NativeMethodStubsGenerator { private static final String STRING_LIST_NAME = "_str"; private static final String POINTER_LIST_NAME = "_ptr"; - public static void generateNativeMethodStubs(AnnotationProcessorEnvironment env, TypeMap type_map, PrintWriter writer, InterfaceDeclaration d, boolean generate_error_checks, boolean context_specific) { - for (MethodDeclaration method : d.getMethods()) { + public static void generateNativeMethodStubs(ProcessingEnvironment env, TypeMap type_map, PrintWriter writer, TypeElement d, boolean generate_error_checks, boolean context_specific) { + for (ExecutableElement method : Utils.getMethods( d)) { Alternate alt_annotation = method.getAnnotation(Alternate.class); if ( (alt_annotation != null && (!alt_annotation.nativeAlt() || alt_annotation.skipNative())) || method.getAnnotation(Reuse.class) != null ) continue; @@ -68,8 +70,8 @@ public class NativeMethodStubsGenerator { } } - private static void generateParameters(PrintWriter writer, Collection params, Mode mode) { - for (ParameterDeclaration param : params) { + private static void generateParameters(PrintWriter writer, List params, Mode mode) { + for (VariableElement param : params) { if ( param.getAnnotation(Result.class) != null || (param.getAnnotation(Helper.class) != null && !param.getAnnotation(Helper.class).passToNative()) ) continue; final Constant constant_annotation = param.getAnnotation(Constant.class); @@ -78,7 +80,7 @@ public class NativeMethodStubsGenerator { } } - private static void generateParameter(PrintWriter writer, ParameterDeclaration param, Mode mode) { + private static void generateParameter(PrintWriter writer, VariableElement param, Mode mode) { writer.print(", "); if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) { writer.print("jlong " + param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX); @@ -86,12 +88,12 @@ public class NativeMethodStubsGenerator { writer.print("jlong " + param.getSimpleName()); } else { JNITypeTranslator translator = new JNITypeTranslator(); - param.getType().accept(translator); + param.asType().accept(translator, null); writer.print(translator.getSignature() + " " + param.getSimpleName()); } } - private static void generateMethodStub(AnnotationProcessorEnvironment env, TypeMap type_map, PrintWriter writer, String interface_name, MethodDeclaration method, Mode mode, boolean generate_error_checks, boolean context_specific) { + private static void generateMethodStub(ProcessingEnvironment env, TypeMap type_map, PrintWriter writer, String interface_name, ExecutableElement method, Mode mode, boolean generate_error_checks, boolean context_specific) { if ( !context_specific && method.getAnnotation(Alternate.class) == null ) writer.print("static "); else @@ -105,7 +107,7 @@ public class NativeMethodStubsGenerator { writer.print("jlong"); } else { JNITypeTranslator translator = new JNITypeTranslator(); - result_type.accept(translator); + result_type.accept(translator, null); writer.print(translator.getReturnSignature()); } writer.print(" JNICALL "); @@ -137,7 +139,7 @@ public class NativeMethodStubsGenerator { final Code code_annotation = method.getAnnotation(Code.class); - final boolean hasResult = !result_type.equals(env.getTypeUtils().getVoidType()); + final boolean hasResult = !result_type.equals(env.getTypeUtils().getNoType(TypeKind.VOID)); final boolean resultPreDeclare = hasResult && (hasPointerArrayInits(method.getParameters()) || (code_annotation != null && (code_annotation.nativeAfterVars().length() > 0 || code_annotation.nativeBeforeCall().length() > 0))); if ( resultPreDeclare ) printResultParam(type_map, writer, method, result_type, true); @@ -164,7 +166,7 @@ public class NativeMethodStubsGenerator { writer.println(code_annotation.nativeAfterCall()); generateStringDeallocations(writer, method.getParameters()); - if (!result_type.equals(env.getTypeUtils().getVoidType())) { + if (!result_type.equals(env.getTypeUtils().getNoType(TypeKind.VOID))) { writer.print("\treturn "); Class java_result_type = Utils.getJavaType(result_type); if (Buffer.class.isAssignableFrom(java_result_type)) { @@ -197,11 +199,11 @@ public class NativeMethodStubsGenerator { writer.println(); } - private static void printResultParam(final TypeMap type_map, final PrintWriter writer, final MethodDeclaration method, final TypeMirror result_type, final boolean preDeclare) { - final ParameterDeclaration result_param = Utils.getResultParameter(method); - final Declaration return_declaration = result_param == null ? method : result_param; + private static void printResultParam(final TypeMap type_map, final PrintWriter writer, final ExecutableElement method, final TypeMirror result_type, final boolean preDeclare) { + final VariableElement result_param = Utils.getResultParameter(method); + final Element return_declaration = result_param == null ? method : result_param; final NativeTypeTranslator result_translator = new NativeTypeTranslator(type_map, return_declaration); - result_type.accept(result_translator); + result_type.accept(result_translator, null); if ( preDeclare ) writer.print("\t"); writer.print(result_translator.getSignature() + " " + Utils.RESULT_VAR_NAME); @@ -211,10 +213,10 @@ public class NativeMethodStubsGenerator { writer.print(result_param == null ? " = " : ";\n\t"); } - private static void generateCallParameters(PrintWriter writer, TypeMap type_map, Collection params) { + private static void generateCallParameters(PrintWriter writer, TypeMap type_map, List params) { if (params.size() > 0) { boolean first = true; - for ( ParameterDeclaration param : params ) { + for ( VariableElement param : params ) { if ( param.getAnnotation(Helper.class) != null ) continue; @@ -228,7 +230,7 @@ public class NativeMethodStubsGenerator { } } - private static void generateCallParameter(PrintWriter writer, TypeMap type_map, ParameterDeclaration param) { + private static void generateCallParameter(PrintWriter writer, TypeMap type_map, VariableElement param) { if ( param.getAnnotation(Helper.class) != null ) return; @@ -242,7 +244,7 @@ public class NativeMethodStubsGenerator { if (is_indirect || param.getAnnotation(PointerArray.class) != null) { writer.print("("); final NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param); - param.getType().accept(translator); + param.asType().accept(translator, null); writer.print(translator.getSignature()); writer.print("*)"); } @@ -256,15 +258,15 @@ public class NativeMethodStubsGenerator { } else { writer.print(param.getSimpleName()); if ( param.getAnnotation(PointerArray.class) != null ) - writer.print(getPointerArrayName(Utils.getJavaType(param.getType()))); - else if ( Utils.isAddressableType(param.getType()) ) + writer.print(getPointerArrayName(Utils.getJavaType(param.asType()))); + else if ( Utils.isAddressableType(param.asType()) ) writer.print(BUFFER_ADDRESS_POSTFIX); } } - private static void generateStringDeallocations(PrintWriter writer, Collection params) { - for (ParameterDeclaration param : params) { - final Class java_type = Utils.getJavaType(param.getType()); + private static void generateStringDeallocations(PrintWriter writer, List params) { + for (VariableElement param : params) { + final Class java_type = Utils.getJavaType(param.asType()); if ( java_type.equals(String.class) && param.getAnnotation(Result.class) == null ) writer.println("\tfree(" + param.getSimpleName() + BUFFER_ADDRESS_POSTFIX + ");"); else if (param.getAnnotation(PointerArray.class) != null ) // Free the string array mem @@ -272,12 +274,12 @@ public class NativeMethodStubsGenerator { } } - private static void generateBufferParameterAddresses(TypeMap type_map, PrintWriter writer, MethodDeclaration method, Mode mode) { + private static void generateBufferParameterAddresses(TypeMap type_map, PrintWriter writer, ExecutableElement method, Mode mode) { strLoopDeclared = false; ptrLoopDeclared = false; - for ( ParameterDeclaration param : method.getParameters() ) { + for ( VariableElement param : method.getParameters() ) { final Constant constant_annotation = param.getAnnotation(Constant.class); - if ( param.getAnnotation(Result.class) == null && (constant_annotation == null || !constant_annotation.isNative()) && Utils.isAddressableType(param.getType())) + if ( param.getAnnotation(Result.class) == null && (constant_annotation == null || !constant_annotation.isNative()) && Utils.isAddressableType(param.asType())) generateBufferParameterAddress(type_map, writer, method, param, mode); } } @@ -285,13 +287,13 @@ public class NativeMethodStubsGenerator { private static boolean strLoopDeclared; private static boolean ptrLoopDeclared; - private static void generateBufferParameterAddress(TypeMap type_map, PrintWriter writer, MethodDeclaration method, ParameterDeclaration param, Mode mode) { + private static void generateBufferParameterAddress(TypeMap type_map, PrintWriter writer, ExecutableElement method, VariableElement param, Mode mode) { final Check check_annotation = param.getAnnotation(Check.class); final PointerArray array_annotation = param.getAnnotation(PointerArray.class); - final Class java_type = Utils.getJavaType(param.getType()); + final Class java_type = Utils.getJavaType(param.asType()); final NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param); - param.getType().accept(translator); + param.asType().accept(translator, null); final String native_type = translator.getSignature(); if ( !java_type.isArray() || CharSequence.class.isAssignableFrom(java_type.getComponentType()) ) { @@ -317,7 +319,7 @@ public class NativeMethodStubsGenerator { final String n = getPointerArrayName(java_type); final String arrayType; if ( POINTER_LIST_NAME.equals(n) ) { - if ( n.equals(param.getSimpleName()) ) + if ( n.equals(param.getSimpleName().toString()) ) throw new RuntimeException("The name '" + n + "' is not valid for object array arguments annotated with PointerArray"); arrayType = translator.getSignature(true) + (org.lwjgl.PointerWrapper.class.isAssignableFrom(java_type.getComponentType()) ? " " : ""); @@ -329,7 +331,7 @@ public class NativeMethodStubsGenerator { ptrLoopDeclared = true; } } else { - if ( n.equals(param.getSimpleName()) ) + if ( n.equals(param.getSimpleName().toString()) ) throw new RuntimeException("The name '" + n + "' is not valid for arguments annotated with PointerArray"); arrayType = translator.getSignature(true); @@ -357,8 +359,8 @@ public class NativeMethodStubsGenerator { return STRING_LIST_NAME; } - private static boolean hasPointerArrayInits(Collection params) { - for ( ParameterDeclaration param : params ) { + private static boolean hasPointerArrayInits(List params) { + for ( VariableElement param : params ) { PointerArray pointerArray_annotation = param.getAnnotation(PointerArray.class); if ( pointerArray_annotation != null ) return true; @@ -366,14 +368,14 @@ public class NativeMethodStubsGenerator { return false; } - private static void generatePointerArrayInits(TypeMap type_map, PrintWriter writer, Collection params) { - for ( ParameterDeclaration param : params ) { + private static void generatePointerArrayInits(TypeMap type_map, PrintWriter writer, List params) { + for ( VariableElement param : params ) { PointerArray pointerArray_annotation = param.getAnnotation(PointerArray.class); if ( pointerArray_annotation != null ) { - final Class java_type = Utils.getJavaType(param.getType()); + final Class java_type = Utils.getJavaType(param.asType()); final Class component_type = java_type.isArray() ? java_type.getComponentType() : null; final NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param); - param.getType().accept(translator); + param.asType().accept(translator, null); final String n = getPointerArrayName(java_type); if ( POINTER_LIST_NAME.equals(n) ) { diff --git a/src/java/org/lwjgl/util/generator/NativeTypeTranslator.java b/src/java/org/lwjgl/util/generator/NativeTypeTranslator.java index 0570ff4f..c64b8c0c 100644 --- a/src/java/org/lwjgl/util/generator/NativeTypeTranslator.java +++ b/src/java/org/lwjgl/util/generator/NativeTypeTranslator.java @@ -29,225 +29,225 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - package org.lwjgl.util.generator; /** * - * A TypeVisitor that translates types (and optional native type - * annotations) to the native type string. + * A TypeVisitor that translates types (and optional native type annotations) to + * the native type string. * * @author elias_naur - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ - -import org.lwjgl.PointerBuffer; - import java.lang.annotation.Annotation; import java.nio.*; import java.util.ArrayList; import java.util.Collection; - -import com.sun.mirror.declaration.AnnotationMirror; -import com.sun.mirror.declaration.Declaration; -import com.sun.mirror.type.*; -import com.sun.mirror.util.TypeVisitor; +import java.util.List; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.Element; +import javax.lang.model.type.ArrayType; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.NoType; +import javax.lang.model.type.PrimitiveType; +import javax.lang.model.type.TypeKind; +import javax.lang.model.util.SimpleTypeVisitor6; +import org.lwjgl.PointerBuffer; /** * $Id$ *

- * A TypeVisitor that translates (annotated) TypeMirrors to - * native types + * A TypeVisitor that translates (annotated) TypeMirrors to native types * * @author elias_naur * @version $Revision$ */ -public class NativeTypeTranslator implements TypeVisitor { +public class NativeTypeTranslator extends SimpleTypeVisitor6 { - private Collection native_types; - private boolean is_indirect; - private final Declaration declaration; - private final TypeMap type_map; + private Collection native_types; + private boolean is_indirect; + private final Element declaration; + private final TypeMap type_map; - public NativeTypeTranslator(TypeMap type_map, Declaration declaration) { - this.declaration = declaration; - this.type_map = type_map; - } + public NativeTypeTranslator(TypeMap type_map, Element declaration) { + this.declaration = declaration; + this.type_map = type_map; + } - public String getSignature() { - return getSignature(false); - } + public String getSignature() { + return getSignature(false); + } - public String getSignature(final boolean skipConst) { - StringBuilder signature = new StringBuilder(); - if ( !skipConst && declaration.getAnnotation(Const.class) != null ) - signature.append("const "); + public String getSignature(final boolean skipConst) { + StringBuilder signature = new StringBuilder(); + if (!skipConst && declaration.getAnnotation(Const.class) != null) { + signature.append("const "); + } - if ( declaration.getAnnotation(PointerWrapper.class) != null ) { - signature.append(declaration.getAnnotation(PointerWrapper.class).value()); - } else if ( declaration.getAnnotation(NativeType.class) != null ) { - signature.append(declaration.getAnnotation(NativeType.class).value()); - } else { - // Use the name of the native type annotation as the C type name - signature.append(getAnnotationType().getSimpleName()); - } + if (declaration.getAnnotation(PointerWrapper.class) != null) { + signature.append(declaration.getAnnotation(PointerWrapper.class).value()); + } else if (declaration.getAnnotation(NativeType.class) != null) { + signature.append(declaration.getAnnotation(NativeType.class).value()); + } else { + // Use the name of the native type annotation as the C type name + signature.append(getAnnotationType().getSimpleName()); + } - if ( is_indirect ) - signature.append(" *"); - return signature.toString(); - } + if (is_indirect) { + signature.append(" *"); + } + return signature.toString(); + } - public Class getAnnotationType() { - if ( native_types.size() != 1 ) - throw new RuntimeException("Expected only one native type for declaration " + declaration + - ", but got " + native_types.size()); - return native_types.iterator().next(); - } + public Class getAnnotationType() { + if (native_types.size() != 1) { + throw new RuntimeException("Expected only one native type for declaration " + declaration + + ", but got " + native_types.size()); + } + return native_types.iterator().next(); + } - public void visitAnnotationType(AnnotationType t) { - throw new RuntimeException(t + " is not allowed"); - } + @Override + public Void visitArray(ArrayType t, Void o) { + final Class type = Utils.getJavaType(t).getComponentType(); - public void visitArrayType(ArrayType t) { - final Class type = Utils.getJavaType(t).getComponentType(); + if (CharSequence.class.isAssignableFrom(type)) { + is_indirect = true; + native_types = new ArrayList<>(); + native_types.add(type_map.getStringArrayType()); + } else if (Buffer.class.isAssignableFrom(type)) { + is_indirect = true; + native_types = new ArrayList<>(); + native_types.add(type_map.getByteBufferArrayType()); + } else if (org.lwjgl.PointerWrapper.class.isAssignableFrom(type)) { + is_indirect = false; + } else { + throw new RuntimeException(t + " is not allowed"); + } + return DEFAULT_VALUE; + } - if ( CharSequence.class.isAssignableFrom(type) ) { - is_indirect = true; - native_types = new ArrayList(); - native_types.add(type_map.getStringArrayType()); - } else if ( Buffer.class.isAssignableFrom(type) ) { - is_indirect = true; - native_types = new ArrayList(); - native_types.add(type_map.getByteBufferArrayType()); - } else if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(type) ) { - is_indirect = false; - } else - throw new RuntimeException(t + " is not allowed"); - } + public static TypeKind getPrimitiveKindFromBufferClass(Class c) { + if (IntBuffer.class.equals(c)) { + return TypeKind.INT; + } else if (DoubleBuffer.class.equals(c)) { + return TypeKind.DOUBLE; + } else if (ShortBuffer.class.equals(c)) { + return TypeKind.SHORT; + } else if (ByteBuffer.class.equals(c) || PointerBuffer.class.equals(c)) { + return TypeKind.BYTE; + } else if (FloatBuffer.class.equals(c)) { + return TypeKind.FLOAT; + } else if (LongBuffer.class.equals(c)) { + return TypeKind.LONG; + } else { + throw new RuntimeException(c + " is not allowed"); + } + } - public static PrimitiveType.Kind getPrimitiveKindFromBufferClass(Class c) { - if ( IntBuffer.class.equals(c) ) - return PrimitiveType.Kind.INT; - else if ( DoubleBuffer.class.equals(c) ) - return PrimitiveType.Kind.DOUBLE; - else if ( ShortBuffer.class.equals(c) ) - return PrimitiveType.Kind.SHORT; - else if ( ByteBuffer.class.equals(c) || PointerBuffer.class.equals(c) ) - return PrimitiveType.Kind.BYTE; - else if ( FloatBuffer.class.equals(c) ) - return PrimitiveType.Kind.FLOAT; - else if ( LongBuffer.class.equals(c) ) - return PrimitiveType.Kind.LONG; - else - throw new RuntimeException(c + " is not allowed"); - } + @SuppressWarnings("unchecked") + public static Class getClassFromType(DeclaredType t) { + try { + return (Class) Class.forName(t.toString()); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } - @SuppressWarnings("unchecked") - public static Class getClassFromType(DeclaredType t) { - try { - return (Class)Class.forName(t.getDeclaration().getQualifiedName()); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - } + private void getNativeTypeFromAnnotatedPrimitiveType(TypeKind kind) { + native_types = translateAnnotations(); + if (native_types.isEmpty()) { + native_types.add(type_map.getNativeTypeFromPrimitiveType(kind)); + } + } - private void getNativeTypeFromAnnotatedPrimitiveType(PrimitiveType.Kind kind) { - native_types = translateAnnotations(); - if ( native_types.size() == 0 ) - native_types.add(type_map.getNativeTypeFromPrimitiveType(kind)); - } + private void visitClassType(DeclaredType t) { + is_indirect = true; - public void visitClassType(ClassType t) { - is_indirect = true; + Class c = getClassFromType(t); + if (String.class.equals(c)) { + native_types = new ArrayList<>(); + native_types.add(type_map.getStringElementType()); + } else if (Buffer.class.equals(c)) { + native_types = new ArrayList<>(); + native_types.add(type_map.getVoidType()); + } else if (Buffer.class.isAssignableFrom(c) || PointerBuffer.class.isAssignableFrom(c)) { + TypeKind kind = getPrimitiveKindFromBufferClass(c); + getNativeTypeFromAnnotatedPrimitiveType(kind); + } else if (org.lwjgl.PointerWrapper.class.isAssignableFrom(c)) { + native_types = new ArrayList<>(); + native_types.add(PointerWrapper.class); - Class c = getClassFromType(t); - if ( String.class.equals(c) ) { - native_types = new ArrayList(); - native_types.add(type_map.getStringElementType()); - } else if ( Buffer.class.equals(c) ) { - native_types = new ArrayList(); - native_types.add(type_map.getVoidType()); - } else if ( Buffer.class.isAssignableFrom(c) || PointerBuffer.class.isAssignableFrom(c) ) { - PrimitiveType.Kind kind = getPrimitiveKindFromBufferClass(c); - getNativeTypeFromAnnotatedPrimitiveType(kind); - } else if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(c) ) { - native_types = new ArrayList(); - native_types.add(PointerWrapper.class); + is_indirect = false; + } else { + throw new RuntimeException(t + " is not allowed"); + } + } - is_indirect = false; - } else - throw new RuntimeException(t + " is not allowed"); - } + @Override + public Void visitPrimitive(PrimitiveType t, Void p) { + getNativeTypeFromAnnotatedPrimitiveType(t.getKind()); + return DEFAULT_VALUE; + } - public void visitPrimitiveType(PrimitiveType t) { - getNativeTypeFromAnnotatedPrimitiveType(t.getKind()); - } + private void visitInterfaceType(DeclaredType t) { + // See ARB_debug_label.glObjectPtrLabel + Class c = getClassFromType(t); + if (org.lwjgl.PointerWrapper.class.isAssignableFrom(c)) { + native_types = new ArrayList<>(); + native_types.add(PointerWrapper.class); - public void visitDeclaredType(DeclaredType t) { - throw new RuntimeException(t + " is not allowed"); - } + is_indirect = false; + } else { + throw new RuntimeException(t + " is not allowed"); + } + } - public void visitEnumType(EnumType t) { - throw new RuntimeException(t + " is not allowed"); - } + @Override + public Void visitDeclared(DeclaredType t, Void p) { + if (t.asElement().getKind().isInterface()) { + visitInterfaceType(t); + } else if (t.asElement().getKind().isClass()) { + visitClassType(t); + } + return DEFAULT_VALUE; + } - public void visitInterfaceType(InterfaceType t) { - // See ARB_debug_label.glObjectPtrLabel - Class c = getClassFromType(t); - if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(c) ) { - native_types = new ArrayList(); - native_types.add(PointerWrapper.class); + /* Check if the annotation is itself annotated with a certain annotation type + * @discuss compare (DeclaredType).getAnnotation(Class) and (Element).getAnnotation(Class), they mean different Annotation's. + */ + public static T getAnnotation(AnnotationMirror annotation, Class type) { + return annotation.getAnnotationType().asElement().getAnnotation(type); + } - is_indirect = false; - } else - throw new RuntimeException(t + " is not allowed"); - } + private static Class translateAnnotation(AnnotationMirror annotation) { + NativeType native_type = getAnnotation(annotation, NativeType.class); + if (native_type != null) { + return getClassFromType(annotation.getAnnotationType()); + } else { + return null; + } + } - // Check if the annotation is itself annotated with a certain annotation type + private List translateAnnotations() { + List result = new ArrayList<>(); + for (AnnotationMirror annotation : Utils.getSortedAnnotations(declaration.getAnnotationMirrors())) { + Class translated_result = translateAnnotation(annotation); + if (translated_result != null) { + result.add(translated_result); + } + } + return result; + } - public static T getAnnotation(AnnotationMirror annotation, Class type) { - return annotation.getAnnotationType().getDeclaration().getAnnotation(type); - } + @Override + public Void visitNoType(NoType t, Void p) { + native_types = translateAnnotations(); + if (native_types.isEmpty()) { + native_types.add(void.class); + } + return DEFAULT_VALUE; + } - private static Class translateAnnotation(AnnotationMirror annotation) { - NativeType native_type = getAnnotation(annotation, NativeType.class); - if ( native_type != null ) { - return getClassFromType(annotation.getAnnotationType()); - } else - return null; - } - - private Collection translateAnnotations() { - Collection result = new ArrayList(); - for ( AnnotationMirror annotation : Utils.getSortedAnnotations(declaration.getAnnotationMirrors()) ) { - Class translated_result = translateAnnotation(annotation); - if ( translated_result != null ) { - result.add(translated_result); - } - } - return result; - } - - public void visitReferenceType(ReferenceType t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitTypeMirror(TypeMirror t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitTypeVariable(TypeVariable t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitVoidType(VoidType t) { - native_types = translateAnnotations(); - if ( native_types.size() == 0 ) - native_types.add(void.class); - } - - public void visitWildcardType(WildcardType t) { - throw new RuntimeException(t + " is not allowed"); - } } diff --git a/src/java/org/lwjgl/util/generator/PostfixTranslator.java b/src/java/org/lwjgl/util/generator/PostfixTranslator.java index 8e76e70d..21ce8480 100644 --- a/src/java/org/lwjgl/util/generator/PostfixTranslator.java +++ b/src/java/org/lwjgl/util/generator/PostfixTranslator.java @@ -42,19 +42,21 @@ package org.lwjgl.util.generator; * $Id$ */ -import com.sun.mirror.declaration.*; -import com.sun.mirror.type.*; -import com.sun.mirror.util.*; - import java.lang.annotation.Annotation; import java.nio.*; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.Element; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.PrimitiveType; +import javax.lang.model.type.TypeKind; +import javax.lang.model.util.SimpleTypeVisitor6; -public class PostfixTranslator implements TypeVisitor { +public class PostfixTranslator extends SimpleTypeVisitor6 { private final StringBuilder signature = new StringBuilder(); - private final Declaration declaration; + private final Element declaration; private final TypeMap type_map; - public PostfixTranslator(TypeMap type_map, Declaration declaration) { + public PostfixTranslator(TypeMap type_map, Element declaration) { this.declaration = declaration; this.type_map = type_map; } @@ -63,47 +65,34 @@ public class PostfixTranslator implements TypeVisitor { return signature.toString(); } - public void visitAnnotationType(AnnotationType t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitArrayType(ArrayType t) { - throw new RuntimeException(t + " is not allowed"); - } - - private static PrimitiveType.Kind getPrimitiveKindFromBufferClass(Class c) { + private static TypeKind getPrimitiveKindFromBufferClass(Class c) { if (IntBuffer.class.equals(c) || int.class.equals(c) ) - return PrimitiveType.Kind.INT; + return TypeKind.INT; else if (DoubleBuffer.class.equals(c) || double.class.equals(c) ) - return PrimitiveType.Kind.DOUBLE; + return TypeKind.DOUBLE; else if (ShortBuffer.class.equals(c) || short.class.equals(c) ) - return PrimitiveType.Kind.SHORT; + return TypeKind.SHORT; else if (ByteBuffer.class.equals(c) || byte.class.equals(c) ) - return PrimitiveType.Kind.BYTE; + return TypeKind.BYTE; else if (FloatBuffer.class.equals(c) || float.class.equals(c)) - return PrimitiveType.Kind.FLOAT; + return TypeKind.FLOAT; else if (LongBuffer.class.equals(c) || long.class.equals(c) ) - return PrimitiveType.Kind.LONG; + return TypeKind.LONG; else throw new RuntimeException(c + " is not allowed"); } - public void visitClassType(ClassType t) { + private void visitClassType(DeclaredType t) { Class c = NativeTypeTranslator.getClassFromType(t); - PrimitiveType.Kind kind = getPrimitiveKindFromBufferClass(c); + TypeKind kind = getPrimitiveKindFromBufferClass(c); visitPrimitiveTypeKind(kind); } - public void visitDeclaredType(DeclaredType t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitEnumType(EnumType t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitInterfaceType(InterfaceType t) { - throw new RuntimeException(t + " is not allowed"); + @Override + public Void visitDeclared(DeclaredType t, Void o) { + if(t.asElement().getKind().isClass()) + visitClassType(t); + return DEFAULT_VALUE; } private boolean translateAnnotation(AnnotationMirror annotation) { @@ -127,11 +116,13 @@ public class PostfixTranslator implements TypeVisitor { return result; } - public void visitPrimitiveType(PrimitiveType t) { + @Override + public Void visitPrimitive(PrimitiveType t, Void o) { visitPrimitiveTypeKind(t.getKind()); + return DEFAULT_VALUE; } - private void visitPrimitiveTypeKind(PrimitiveType.Kind kind) { + private void visitPrimitiveTypeKind(TypeKind kind) { boolean annotated_translation = translateAnnotations(); if (annotated_translation) return; @@ -161,23 +152,4 @@ public class PostfixTranslator implements TypeVisitor { } signature.append(type); } - - public void visitReferenceType(ReferenceType t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitTypeMirror(TypeMirror t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitTypeVariable(TypeVariable t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitVoidType(VoidType t) { - } - - public void visitWildcardType(WildcardType t) { - throw new RuntimeException(t + " is not allowed"); - } } \ No newline at end of file diff --git a/src/java/org/lwjgl/util/generator/RegisterStubsGenerator.java b/src/java/org/lwjgl/util/generator/RegisterStubsGenerator.java index 7bfc1014..11ec7609 100644 --- a/src/java/org/lwjgl/util/generator/RegisterStubsGenerator.java +++ b/src/java/org/lwjgl/util/generator/RegisterStubsGenerator.java @@ -29,7 +29,6 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - package org.lwjgl.util.generator; /** @@ -37,98 +36,109 @@ package org.lwjgl.util.generator; * This class generates the initNatives native function. * * @author elias_naur - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ - -import com.sun.mirror.declaration.*; -import com.sun.mirror.type.*; - import java.io.*; import java.util.*; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeMirror; public class RegisterStubsGenerator { - public static void generateMethodsNativeStubBind(PrintWriter writer, InterfaceDeclaration d, boolean generate_error_checks, boolean context_specific) { - Iterator it = d.getMethods().iterator(); - while (it.hasNext()) { - MethodDeclaration method = it.next(); - Alternate alt_annotation = method.getAnnotation(Alternate.class); - if ( (alt_annotation != null && (!alt_annotation.nativeAlt() || alt_annotation.skipNative())) || method.getAnnotation(Reuse.class) != null ) - continue; - EnumSet platforms; - PlatformDependent platform_annotation = method.getAnnotation(PlatformDependent.class); - if (platform_annotation != null) - platforms = EnumSet.copyOf(Arrays.asList(platform_annotation.value())); - else - platforms = EnumSet.of(Platform.ALL); - for (Platform platform : platforms) { - platform.printPrologue(writer); - boolean has_buffer_parameter = Utils.hasMethodBufferObjectParameter(method); - printMethodNativeStubBind(writer, d, method, platform, Mode.NORMAL, it.hasNext() || has_buffer_parameter, generate_error_checks, context_specific); - if (has_buffer_parameter) { - printMethodNativeStubBind(writer, d, method, platform, Mode.BUFFEROBJECT, it.hasNext(), generate_error_checks, context_specific); - } - platform.printEpilogue(writer); - } - } - writer.println(); - } - private static String getTypeSignature(TypeMirror type, boolean add_position_signature) { - SignatureTranslator v = new SignatureTranslator(add_position_signature); - type.accept(v); - return v.getSignature(); - } + public static void generateMethodsNativeStubBind(ProcessingEnvironment env, PrintWriter writer, TypeElement d, boolean generate_error_checks, boolean context_specific) { + Iterator it = Utils.getMethods( d).iterator(); + while (it.hasNext()) { + ExecutableElement method = it.next(); + Alternate alt_annotation = method.getAnnotation(Alternate.class); + if ((alt_annotation != null && (!alt_annotation.nativeAlt() || alt_annotation.skipNative())) || method.getAnnotation(Reuse.class) != null) { + continue; + } + EnumSet platforms; + PlatformDependent platform_annotation = method.getAnnotation(PlatformDependent.class); + if (platform_annotation != null) { + platforms = EnumSet.copyOf(Arrays.asList(platform_annotation.value())); + } else { + platforms = EnumSet.of(Platform.ALL); + } + for (Platform platform : platforms) { + platform.printPrologue(writer); + boolean has_buffer_parameter = Utils.hasMethodBufferObjectParameter(method); + printMethodNativeStubBind(writer, d, method, platform, Mode.NORMAL, it.hasNext() || has_buffer_parameter, generate_error_checks, context_specific); + if (has_buffer_parameter) { + printMethodNativeStubBind(writer, d, method, platform, Mode.BUFFEROBJECT, it.hasNext(), generate_error_checks, context_specific); + } + platform.printEpilogue(writer); + } + } + writer.println(); + } - private static String getMethodSignature(MethodDeclaration method, Mode mode) { - Collection params = method.getParameters(); - String signature = "("; - for (ParameterDeclaration param : params) { - if ( param.getAnnotation(Result.class) != null || (param.getAnnotation(Helper.class) != null && !param.getAnnotation(Helper.class).passToNative()) ) - continue; + private static String getTypeSignature(TypeMirror type, boolean add_position_signature) { + SignatureTranslator v = new SignatureTranslator(add_position_signature); + type.accept(v, null); + return v.getSignature(); + } - final Constant constant_annotation = param.getAnnotation(Constant.class); - if ( constant_annotation != null && constant_annotation.isNative() ) - continue; + private static String getMethodSignature(ExecutableElement method, Mode mode) { + List params = method.getParameters(); + String signature = "("; + for (VariableElement param : params) { + if (param.getAnnotation(Result.class) != null || (param.getAnnotation(Helper.class) != null && !param.getAnnotation(Helper.class).passToNative())) { + continue; + } - if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) - signature += "J"; - else - signature += getTypeSignature(param.getType(), true); - } + final Constant constant_annotation = param.getAnnotation(Constant.class); + if (constant_annotation != null && constant_annotation.isNative()) { + continue; + } - final TypeMirror result_type = Utils.getMethodReturnType(method); - final CachedResult cached_result_annotation = method.getAnnotation(CachedResult.class); - final AutoSize auto_size_annotation = method.getAnnotation(AutoSize.class); + if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) { + signature += "J"; + } else { + signature += getTypeSignature(param.asType(), true); + } + } - final boolean isNIOBuffer = Utils.getNIOBufferType(result_type) != null; - if ( isNIOBuffer && (auto_size_annotation == null || !auto_size_annotation.isNative()) ) - signature += "J"; + final TypeMirror result_type = Utils.getMethodReturnType(method); + final CachedResult cached_result_annotation = method.getAnnotation(CachedResult.class); + final AutoSize auto_size_annotation = method.getAnnotation(AutoSize.class); - final String result_type_signature = isNIOBuffer ? "Ljava/nio/ByteBuffer;" : getTypeSignature(result_type, false); - if ( cached_result_annotation != null ) - signature += result_type_signature; + final boolean isNIOBuffer = Utils.getNIOBufferType(result_type) != null; + if (isNIOBuffer && (auto_size_annotation == null || !auto_size_annotation.isNative())) { + signature += "J"; + } - signature += ")"; - signature += result_type_signature; - return signature; - } + final String result_type_signature = isNIOBuffer ? "Ljava/nio/ByteBuffer;" : getTypeSignature(result_type, false); + if (cached_result_annotation != null) { + signature += result_type_signature; + } - private static void printMethodNativeStubBind(PrintWriter writer, InterfaceDeclaration d, MethodDeclaration method, Platform platform, Mode mode, boolean has_more, boolean generate_error_checks, boolean context_specific) { - writer.print("\t\t{\"" + Utils.getSimpleNativeMethodName(method, generate_error_checks, context_specific)); - if (mode == Mode.BUFFEROBJECT) - writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX); - writer.print("\", \"" + getMethodSignature(method, mode) + "\", (void *)&"); - writer.print(Utils.getQualifiedNativeMethodName(Utils.getQualifiedClassName(d), method, generate_error_checks, context_specific)); - if (mode == Mode.BUFFEROBJECT) - writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX); + signature += ")"; + signature += result_type_signature; + return signature; + } - final Alternate alt_annotation = method.getAnnotation(Alternate.class); - final String methodName = alt_annotation == null ? method.getSimpleName() : alt_annotation.value(); - String opengl_handle_name = methodName.replaceFirst("gl", platform.getPrefix()); - writer.print(", \"" + opengl_handle_name + "\", (void *)&" + methodName + ", " + (method.getAnnotation(Optional.class) == null ? "false" : "true") + "}"); - if (has_more) - writer.println(","); - } + private static void printMethodNativeStubBind(PrintWriter writer, TypeElement d, ExecutableElement method, Platform platform, Mode mode, boolean has_more, boolean generate_error_checks, boolean context_specific) { + writer.print("\t\t{\"" + Utils.getSimpleNativeMethodName(method, generate_error_checks, context_specific)); + if (mode == Mode.BUFFEROBJECT) { + writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX); + } + writer.print("\", \"" + getMethodSignature(method, mode) + "\", (void *)&"); + writer.print(Utils.getQualifiedNativeMethodName(Utils.getQualifiedClassName(d), method, generate_error_checks, context_specific)); + if (mode == Mode.BUFFEROBJECT) { + writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX); + } + + final Alternate alt_annotation = method.getAnnotation(Alternate.class); + final String methodName = alt_annotation == null ? method.getSimpleName().toString() : alt_annotation.value(); + String opengl_handle_name = methodName.replaceFirst("gl", platform.getPrefix()); + writer.print(", \"" + opengl_handle_name + "\", (void *)&" + methodName + ", " + (method.getAnnotation(Optional.class) == null ? "false" : "true") + "}"); + if (has_more) { + writer.println(","); + } + } } diff --git a/src/java/org/lwjgl/util/generator/SignatureTranslator.java b/src/java/org/lwjgl/util/generator/SignatureTranslator.java index a9e97432..b4434816 100644 --- a/src/java/org/lwjgl/util/generator/SignatureTranslator.java +++ b/src/java/org/lwjgl/util/generator/SignatureTranslator.java @@ -41,14 +41,24 @@ package org.lwjgl.util.generator; * $Id$ */ -import org.lwjgl.PointerBuffer; - -import com.sun.mirror.type.*; -import com.sun.mirror.util.*; import java.nio.*; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.type.ArrayType; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.NoType; +import javax.lang.model.type.PrimitiveType; +import static javax.lang.model.type.TypeKind.BOOLEAN; +import static javax.lang.model.type.TypeKind.BYTE; +import static javax.lang.model.type.TypeKind.DOUBLE; +import static javax.lang.model.type.TypeKind.FLOAT; +import static javax.lang.model.type.TypeKind.INT; +import static javax.lang.model.type.TypeKind.LONG; +import static javax.lang.model.type.TypeKind.SHORT; +import javax.lang.model.util.SimpleTypeVisitor6; +import org.lwjgl.PointerBuffer; -class SignatureTranslator implements TypeVisitor { +class SignatureTranslator extends SimpleTypeVisitor6 { private final boolean add_position_signature; private final StringBuilder signature = new StringBuilder(); @@ -64,11 +74,8 @@ class SignatureTranslator implements TypeVisitor { return signature.toString(); } - public void visitAnnotationType(AnnotationType t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitArrayType(ArrayType t) { + @Override + public Void visitArray(ArrayType t, Void o) { final Class type = Utils.getJavaType(t.getComponentType()); if ( CharSequence.class.isAssignableFrom(type) ) signature.append("J"); @@ -78,9 +85,10 @@ class SignatureTranslator implements TypeVisitor { signature.append("[L" + getNativeNameFromClassName(type.getName()) + ";"); else throw new RuntimeException(t + " is not allowed"); + return DEFAULT_VALUE; } - public void visitClassType(ClassType t) { + private void visitClassType(DeclaredType t) { Class type = NativeTypeTranslator.getClassFromType(t); if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(type) || (Utils.isAddressableType(type) && !String.class.equals(type)) ) @@ -90,7 +98,7 @@ class SignatureTranslator implements TypeVisitor { if ( (CharSequence.class.isAssignableFrom(type) && !String.class.equals(type)) || CharSequence[].class.isAssignableFrom(type) || PointerBuffer.class.isAssignableFrom(type) ) type_name = ByteBuffer.class.getName(); else - type_name = t.getDeclaration().getQualifiedName(); + type_name = t.toString(); signature.append("L"); signature.append(getNativeNameFromClassName(type_name)); @@ -98,15 +106,16 @@ class SignatureTranslator implements TypeVisitor { } } - public void visitDeclaredType(DeclaredType t) { - throw new RuntimeException(t + " is not allowed"); + @Override + public Void visitDeclared(DeclaredType t, Void o) { + if(t.asElement().getKind().isClass()) + visitClassType(t); + else if(t.asElement().getKind().isInterface()) + visitInterfaceType(t); + return DEFAULT_VALUE; } - public void visitEnumType(EnumType t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitInterfaceType(InterfaceType t) { + private void visitInterfaceType(DeclaredType t) { Class type = NativeTypeTranslator.getClassFromType(t); if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(type) ) signature.append("J"); @@ -114,7 +123,8 @@ class SignatureTranslator implements TypeVisitor { throw new RuntimeException(t + " is not allowed"); } - public void visitPrimitiveType(PrimitiveType t) { + @Override + public Void visitPrimitive(PrimitiveType t, Void o) { switch (t.getKind()) { case BOOLEAN: signature.append("Z"); @@ -140,25 +150,13 @@ class SignatureTranslator implements TypeVisitor { default: throw new RuntimeException("Unsupported type " + t); } + return DEFAULT_VALUE; } - public void visitReferenceType(ReferenceType t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitTypeMirror(TypeMirror t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitTypeVariable(TypeVariable t) { - throw new RuntimeException(t + " is not allowed"); - } - - public void visitVoidType(VoidType t) { + @Override + public Void visitNoType(NoType t, Void o) { signature.append("V"); + return DEFAULT_VALUE; } - public void visitWildcardType(WildcardType t) { - throw new RuntimeException(t + " is not allowed"); - } } diff --git a/src/java/org/lwjgl/util/generator/TypeInfo.java b/src/java/org/lwjgl/util/generator/TypeInfo.java index d2967e48..dc41d612 100644 --- a/src/java/org/lwjgl/util/generator/TypeInfo.java +++ b/src/java/org/lwjgl/util/generator/TypeInfo.java @@ -33,207 +33,216 @@ package org.lwjgl.util.generator; /** * - * This class represent a parameter configuration. There are multiple - * TypeInfos in case of multityped parameters. + * This class represent a parameter configuration. There are multiple TypeInfos + * in case of multityped parameters. * * @author elias_naur - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ - +import java.lang.annotation.Annotation; +import java.nio.*; +import java.util.*; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.Element; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.tools.Diagnostic; import org.lwjgl.PointerBuffer; import org.lwjgl.util.generator.opengl.GLvoid; -import com.sun.mirror.declaration.*; -import com.sun.mirror.type.*; - -import java.lang.annotation.Annotation; -import java.util.*; -import java.nio.*; - public class TypeInfo { - public static final String UNSIGNED_PARAMETER_NAME = "unsigned"; - private final Signedness signedness; - private final Class type; - private final String auto_type; + public static final String UNSIGNED_PARAMETER_NAME = "unsigned"; - private TypeInfo(Class type, Signedness signedness, String auto_type) { - this.type = type; - this.signedness = signedness; - this.auto_type = auto_type; - } + private final Signedness signedness; + private final Class type; + private final String auto_type; - public Class getType() { - return type; - } + private TypeInfo(Class type, Signedness signedness, String auto_type) { + this.type = type; + this.signedness = signedness; + this.auto_type = auto_type; + } - public Signedness getSignedness() { - return signedness; - } + public Class getType() { + return type; + } - public String getAutoType() { - if (auto_type == null) - throw new RuntimeException("No auto type assigned"); - return auto_type; - } + public Signedness getSignedness() { + return signedness; + } - private static Class getTypeFromPrimitiveKind(PrimitiveType.Kind kind) { - Class type; - switch (kind) { - case LONG: - type = long.class; - break; - case INT: - type = int.class; - break; - case FLOAT: - type = float.class; - break; - case DOUBLE: - type = double.class; - break; - case SHORT: - type = short.class; - break; - case BYTE: - type = byte.class; - break; - case BOOLEAN: - type = boolean.class; - break; - default: - throw new RuntimeException(kind + " is not allowed"); - } - return type; - } + public String getAutoType() { + if (auto_type == null) { + throw new RuntimeException("No auto type assigned"); + } + return auto_type; + } - private static Class getBufferTypeFromPrimitiveKind(PrimitiveType.Kind kind, AnnotationMirror annotation) { - Class type; - switch (kind) { - case INT: - type = IntBuffer.class; - break; - case FLOAT: - type = FloatBuffer.class; - break; - case DOUBLE: - type = DoubleBuffer.class; - break; - case SHORT: - type = ShortBuffer.class; - break; - case LONG: - if ( annotation.getAnnotationType().getDeclaration().getAnnotation(PointerType.class) != null ) - type = PointerBuffer.class; - else - type = LongBuffer.class; - break; - case BYTE: /* fall through */ - case BOOLEAN: - type = ByteBuffer.class; - break; - default: - throw new RuntimeException(kind + " is not allowed"); - } - return type; - } + private static Class getTypeFromPrimitiveKind(TypeKind kind) { + Class type; + switch (kind) { + case LONG: + type = long.class; + break; + case INT: + type = int.class; + break; + case FLOAT: + type = float.class; + break; + case DOUBLE: + type = double.class; + break; + case SHORT: + type = short.class; + break; + case BYTE: + type = byte.class; + break; + case BOOLEAN: + type = boolean.class; + break; + default: + throw new RuntimeException(kind + " is not allowed"); + } + return type; + } - private static TypeInfo getDefaultTypeInfo(TypeMirror t) { - Class java_type = Utils.getJavaType(t); - return new TypeInfo(java_type, Signedness.NONE, null); - } + private static Class getBufferTypeFromPrimitiveKind(TypeKind kind, AnnotationMirror annotation) { + Class type; + switch (kind) { + case INT: + type = IntBuffer.class; + break; + case FLOAT: + type = FloatBuffer.class; + break; + case DOUBLE: + type = DoubleBuffer.class; + break; + case SHORT: + type = ShortBuffer.class; + break; + case LONG: + if (annotation.getAnnotationType().asElement().getAnnotation(PointerType.class) != null) { + type = PointerBuffer.class; + } else { + type = LongBuffer.class; + } + break; + case BYTE: /* fall through */ - public static Map getDefaultTypeInfoMap(MethodDeclaration method) { - Map map = new HashMap(); - for (ParameterDeclaration param : method.getParameters()) { - TypeInfo type_info = getDefaultTypeInfo(param.getType()); - map.put(param, type_info); - } - return map; - } + case BOOLEAN: + type = ByteBuffer.class; + break; + default: + throw new RuntimeException(kind + " is not allowed"); + } + return type; + } - private static Collection getTypeInfos(TypeMap type_map, Declaration param, TypeMirror decl_type) { - Collection annotations = Utils.getSortedAnnotations(param.getAnnotationMirrors()); - Map types = new HashMap(); - Collection multityped_result = new ArrayList(); - boolean add_default_type = true; - for (AnnotationMirror annotation : annotations) { - NativeType native_type_annotation = NativeTypeTranslator.getAnnotation(annotation, NativeType.class); - if (native_type_annotation != null) { - Class annotation_type = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType()); - Signedness signedness = type_map.getSignednessFromType(annotation_type); - Class inverse_type = type_map.getInverseType(annotation_type); - String auto_type = type_map.getAutoTypeFromAnnotation(annotation); - if (inverse_type != null) { - if (types.containsKey(inverse_type)) { - TypeInfo inverse_type_info = types.get(inverse_type); - String inverse_auto_type = inverse_type_info.getAutoType(); - auto_type = signedness == Signedness.UNSIGNED ? auto_type + " : " + inverse_auto_type : - inverse_auto_type + " : " + auto_type; - auto_type = UNSIGNED_PARAMETER_NAME + " ? " + auto_type; - signedness = Signedness.BOTH; - types.remove(inverse_type); - multityped_result.remove(inverse_type_info); - } - } - Class type; - PrimitiveType.Kind kind; - GLvoid void_annotation = param.getAnnotation(GLvoid.class); - kind = void_annotation == null ? type_map.getPrimitiveTypeFromNativeType(annotation_type) : void_annotation.value(); - if (Utils.getNIOBufferType(decl_type) != null) - type = getBufferTypeFromPrimitiveKind(kind, annotation); - else - type = getTypeFromPrimitiveKind(kind); - TypeInfo type_info = new TypeInfo(type, signedness, auto_type); - types.put(annotation_type, type_info); - multityped_result.add(type_info); - add_default_type = false; - } - } - if (add_default_type) { - TypeInfo default_type_info = getDefaultTypeInfo(decl_type); - Collection result = new ArrayList(); - result.add(default_type_info); - return result; - } else - return multityped_result; - } + private static TypeInfo getDefaultTypeInfo(TypeMirror t) { + Class java_type = Utils.getJavaType(t); + return new TypeInfo(java_type, Signedness.NONE, null); + } - private static Map> getTypeInfoMap(TypeMap type_map, MethodDeclaration method) { - Map> map = new HashMap>(); - for (ParameterDeclaration param : method.getParameters()) { - Collection types = getTypeInfos(type_map, param, param.getType()); - map.put(param, types); - } - return map; - } + public static Map getDefaultTypeInfoMap(ExecutableElement method) { + Map map = new HashMap<>(); + for (VariableElement param : method.getParameters()) { + TypeInfo type_info = getDefaultTypeInfo(param.asType()); + map.put(param, type_info); + } + return map; + } - public static Collection> getTypeInfoCrossProduct(TypeMap type_map, MethodDeclaration method) { - Collection parameter_collection = method.getParameters(); - ParameterDeclaration[] parameters = new ParameterDeclaration[parameter_collection.size()]; - parameter_collection.toArray(parameters); - Collection> cross_product = new ArrayList>(); - getCrossProductRecursive(0, parameters, getTypeInfoMap(type_map, method), - new HashMap(), cross_product); - return cross_product; - } + private static Collection getTypeInfos(ProcessingEnvironment env, TypeMap type_map, VariableElement param) { + List annotations = param.getAnnotationMirrors(); + GLvoid void_annotation = param.getAnnotation(GLvoid.class); - private static void getCrossProductRecursive(int index, ParameterDeclaration[] parameters, Map> typeinfos_map, Map current_instance, - Collection> cross_product) { - if (index == parameters.length) { - cross_product.add(current_instance); - return; - } - ParameterDeclaration param = parameters[index]; - Collection typeinfos = typeinfos_map.get(param); - if (typeinfos != null) { - for (TypeInfo typeinfo : typeinfos) { - Map instance = new HashMap(current_instance); - instance.put(param, typeinfo); - getCrossProductRecursive(index + 1, parameters, typeinfos_map, instance, cross_product); - } - } - } + Map types = new HashMap<>(); + Collection multityped_result = new ArrayList<>(); + boolean add_default_type = true; + for (AnnotationMirror annotation : annotations) { + NativeType native_type_annotation = NativeTypeTranslator.getAnnotation(annotation, NativeType.class); + if (native_type_annotation != null) { + Class annotation_type = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType()); + /*env.getMessager().printMessage(Diagnostic.Kind.NOTE, "annotation_type " + annotation_type, param, annotation);*/ + Signedness signedness = type_map.getSignednessFromType(annotation_type); + Class inverse_type = type_map.getInverseType(annotation_type); + String auto_type = type_map.getAutoTypeFromAnnotation(annotation); + if (inverse_type != null) { + if (types.containsKey(inverse_type)) { + TypeInfo inverse_type_info = types.get(inverse_type); + String inverse_auto_type = inverse_type_info.getAutoType(); + auto_type = signedness == Signedness.UNSIGNED ? auto_type + " : " + inverse_auto_type + : inverse_auto_type + " : " + auto_type; + auto_type = UNSIGNED_PARAMETER_NAME + " ? " + auto_type; + signedness = Signedness.BOTH; + types.remove(inverse_type); + multityped_result.remove(inverse_type_info); + } + } + Class type; + TypeKind kind; + kind = void_annotation == null ? type_map.getPrimitiveTypeFromNativeType(annotation_type) : void_annotation.value(); + if (Utils.getNIOBufferType(param.asType()) != null) { + type = getBufferTypeFromPrimitiveKind(kind, annotation); + } else { + type = getTypeFromPrimitiveKind(kind); + } + TypeInfo type_info = new TypeInfo(type, signedness, auto_type); + types.put(annotation_type, type_info); + multityped_result.add(type_info); + add_default_type = false; + } + } + if (add_default_type) { + TypeInfo default_type_info = getDefaultTypeInfo(param.asType()); + Collection result = new ArrayList<>(); + result.add(default_type_info); + return result; + } else { + return multityped_result; + } + } + + private static Map> getTypeInfoMap(ProcessingEnvironment env, TypeMap type_map, ExecutableElement method) { + Map> map = new HashMap<>(); + for (VariableElement param : method.getParameters()) { + Collection types = getTypeInfos(env, type_map, param); + map.put(param, types); + } + return map; + } + + public static Collection> getTypeInfoCrossProduct(ProcessingEnvironment env, TypeMap type_map, ExecutableElement method) { + List parameter_collection = method.getParameters(); + Collection> cross_product = new ArrayList<>(); + getCrossProductRecursive(0, parameter_collection, getTypeInfoMap(env, type_map, method), + new HashMap(), cross_product); + return cross_product; + } + + private static void getCrossProductRecursive(int index, List parameters, Map> typeinfos_map, Map current_instance, Collection> cross_product) { + if (index == parameters.size()) { + /** + * the last parameter is treated as multi-type only + */ + cross_product.add(current_instance); + return; + } + VariableElement param = parameters.get(index); + Collection typeinfos = typeinfos_map.get(param); + if (typeinfos != null) { + for (TypeInfo typeinfo : typeinfos) { + Map instance = new HashMap<>(current_instance); + instance.put(param, typeinfo); + getCrossProductRecursive(index + 1, parameters, typeinfos_map, instance, cross_product); + } + } + } } diff --git a/src/java/org/lwjgl/util/generator/TypeMap.java b/src/java/org/lwjgl/util/generator/TypeMap.java index aa863767..fd829e64 100644 --- a/src/java/org/lwjgl/util/generator/TypeMap.java +++ b/src/java/org/lwjgl/util/generator/TypeMap.java @@ -41,19 +41,20 @@ package org.lwjgl.util.generator; * $Id$ */ -import com.sun.mirror.declaration.*; -import com.sun.mirror.type.*; import java.io.*; import java.lang.annotation.Annotation; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.type.TypeKind; public interface TypeMap { void printCapabilitiesInit(PrintWriter writer); String getCapabilities(); String getAPIUtilParam(boolean comma); - void printErrorCheckMethod(PrintWriter writer, MethodDeclaration method, String tabs); + void printErrorCheckMethod(PrintWriter writer, ExecutableElement method, String tabs); String getRegisterNativesFunctionName(); - PrimitiveType.Kind getPrimitiveTypeFromNativeType(Class native_type); + TypeKind getPrimitiveTypeFromNativeType(Class native_type); String getTypedefPostfix(); String getFunctionPrefix(); void printNativeIncludes(PrintWriter writer); @@ -63,7 +64,7 @@ public interface TypeMap { Class[] getValidAnnotationTypes(Class type); Class getVoidType(); String translateAnnotation(Class annotation_type); - Class getNativeTypeFromPrimitiveType(PrimitiveType.Kind kind); + Class getNativeTypeFromPrimitiveType(TypeKind kind); String getAutoTypeFromAnnotation(AnnotationMirror annotation); Class getInverseType(Class type); Signedness getSignednessFromType(Class type); diff --git a/src/java/org/lwjgl/util/generator/TypedefsGenerator.java b/src/java/org/lwjgl/util/generator/TypedefsGenerator.java index af1c7db5..d4f8d032 100644 --- a/src/java/org/lwjgl/util/generator/TypedefsGenerator.java +++ b/src/java/org/lwjgl/util/generator/TypedefsGenerator.java @@ -41,19 +41,20 @@ package org.lwjgl.util.generator; * $Id$ */ -import com.sun.mirror.declaration.*; -import com.sun.mirror.type.*; import java.io.*; import java.util.*; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeMirror; public class TypedefsGenerator { - private static void generateNativeTypedefs(TypeMap type_map, PrintWriter writer, MethodDeclaration method) { + private static void generateNativeTypedefs(TypeMap type_map, PrintWriter writer, ExecutableElement method) { TypeMirror return_type = method.getReturnType(); writer.print("typedef "); writer.print(type_map.getTypedefPostfix()); NativeTypeTranslator translator = new NativeTypeTranslator(type_map, method); - return_type.accept(translator); + return_type.accept(translator, null); writer.print(translator.getSignature()); writer.print(" ("); writer.print(type_map.getFunctionPrefix()); @@ -62,10 +63,10 @@ public class TypedefsGenerator { writer.println(");"); } - private static void generateNativeTypedefsParameters(TypeMap type_map, PrintWriter writer, Collection params) { + private static void generateNativeTypedefsParameters(TypeMap type_map, PrintWriter writer, Collection params) { if (params.size() > 0) { boolean first = true; - for ( ParameterDeclaration param : params ) { + for ( VariableElement param : params ) { if ( param.getAnnotation(Helper.class) != null ) continue; @@ -79,17 +80,17 @@ public class TypedefsGenerator { } } - private static void generateNativeTypedefsParameter(TypeMap type_map, PrintWriter writer, ParameterDeclaration param) { + private static void generateNativeTypedefsParameter(TypeMap type_map, PrintWriter writer, VariableElement param) { NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param); - param.getType().accept(translator); + param.asType().accept(translator, null); writer.print(translator.getSignature()); if (param.getAnnotation(Result.class) != null || param.getAnnotation(Indirect.class) != null || param.getAnnotation(PointerArray.class) != null) writer.print("*"); writer.print(" " + param.getSimpleName()); } - public static void generateNativeTypedefs(TypeMap type_map, PrintWriter writer, Collection methods) { - for (MethodDeclaration method : methods) { + public static void generateNativeTypedefs(TypeMap type_map, PrintWriter writer, Collection methods) { + for (ExecutableElement method : methods) { if ( method.getAnnotation(Alternate.class) == null && method.getAnnotation(Reuse.class) == null ) generateNativeTypedefs(type_map, writer, method); } diff --git a/src/java/org/lwjgl/util/generator/Utils.java b/src/java/org/lwjgl/util/generator/Utils.java index 156bd315..fc74e8e7 100644 --- a/src/java/org/lwjgl/util/generator/Utils.java +++ b/src/java/org/lwjgl/util/generator/Utils.java @@ -36,423 +36,474 @@ package org.lwjgl.util.generator; * Various utility methods to the generator. * * @author elias_naur - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ - +import java.io.PrintWriter; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.util.*; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.Element; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.type.TypeVisitor; +import javax.lang.model.util.ElementFilter; +import javax.tools.Diagnostic; import org.lwjgl.PointerBuffer; import org.lwjgl.util.generator.opengl.GLboolean; import org.lwjgl.util.generator.opengl.GLchar; import org.lwjgl.util.generator.opengl.GLcharARB; import org.lwjgl.util.generator.opengl.GLreturn; -import java.io.PrintWriter; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.util.*; - -import com.sun.mirror.declaration.*; -import com.sun.mirror.type.PrimitiveType; -import com.sun.mirror.type.TypeMirror; - public class Utils { - public static final String TYPEDEF_POSTFIX = "PROC"; - public static final String FUNCTION_POINTER_VAR_NAME = "function_pointer"; - public static final String FUNCTION_POINTER_POSTFIX = "_pointer"; - public static final String CHECKS_CLASS_NAME = "GLChecks"; - public static final String CONTEXT_CAPS_CLASS_NAME = "ContextCapabilities"; - public static final String STUB_INITIALIZER_NAME = "initNativeStubs"; - public static final String BUFFER_OBJECT_METHOD_POSTFIX = "BO"; - public static final String BUFFER_OBJECT_PARAMETER_POSTFIX = "_buffer_offset"; - public static final String RESULT_SIZE_NAME = "result_size"; - public static final String RESULT_VAR_NAME = "__result"; - public static final String CACHED_BUFFER_LENGTH_NAME = "length"; - public static final String CACHED_BUFFER_NAME = "old_buffer"; - private static final String OVERLOADED_METHOD_PREFIX = "n"; + public static final String TYPEDEF_POSTFIX = "PROC"; + public static final String FUNCTION_POINTER_VAR_NAME = "function_pointer"; + public static final String FUNCTION_POINTER_POSTFIX = "_pointer"; + public static final String CHECKS_CLASS_NAME = "GLChecks"; + public static final String CONTEXT_CAPS_CLASS_NAME = "ContextCapabilities"; + public static final String STUB_INITIALIZER_NAME = "initNativeStubs"; + public static final String BUFFER_OBJECT_METHOD_POSTFIX = "BO"; + public static final String BUFFER_OBJECT_PARAMETER_POSTFIX = "_buffer_offset"; + public static final String RESULT_SIZE_NAME = "result_size"; + public static final String RESULT_VAR_NAME = "__result"; + public static final String CACHED_BUFFER_LENGTH_NAME = "length"; + public static final String CACHED_BUFFER_NAME = "old_buffer"; + private static final String OVERLOADED_METHOD_PREFIX = "n"; - public static String getTypedefName(MethodDeclaration method) { - Alternate alt_annotation = method.getAnnotation(Alternate.class); - return (alt_annotation == null ? method.getSimpleName() : alt_annotation.value()) + TYPEDEF_POSTFIX; - } + public static String getTypedefName(ExecutableElement method) { + Alternate alt_annotation = method.getAnnotation(Alternate.class); + return (alt_annotation == null ? method.getSimpleName() : alt_annotation.value()) + TYPEDEF_POSTFIX; + } - public static String getFunctionAddressName(InterfaceDeclaration interface_decl, MethodDeclaration method) { - return getFunctionAddressName(interface_decl, method, false); - } + public static String getFunctionAddressName(TypeElement interface_decl, ExecutableElement method) { + return getFunctionAddressName(interface_decl, method, false); + } - public static String getFunctionAddressName(InterfaceDeclaration interface_decl, MethodDeclaration method, boolean forceAlt) { - final Alternate alt_annotation = method.getAnnotation(Alternate.class); + public static String getFunctionAddressName(TypeElement interface_decl, ExecutableElement method, boolean forceAlt) { + final Alternate alt_annotation = method.getAnnotation(Alternate.class); - /* Removed prefix so that we can identify reusable entry points, removed postfix because it's not needed and looks nicer. - String interfaceName = interface_decl.getSimpleName(); // If we add this back, we need to fix @Reuse (add a param for the template name) - if ( alt_annotation == null || (alt_annotation.nativeAlt() && !forceAlt) ) - return interfaceName + "_" + method.getSimpleName() + FUNCTION_POINTER_POSTFIX; - else - return interfaceName + "_" + alt_annotation.value() + FUNCTION_POINTER_POSTFIX; - */ - if ( alt_annotation == null || (alt_annotation.nativeAlt() && !forceAlt) ) - return method.getSimpleName(); - else - return alt_annotation.value(); - } + /* Removed prefix so that we can identify reusable entry points, removed postfix because it's not needed and looks nicer. + String interfaceName = interface_decl.getSimpleName(); // If we add this back, we need to fix @Reuse (add a param for the template name) + if ( alt_annotation == null || (alt_annotation.nativeAlt() && !forceAlt) ) + return interfaceName + "_" + method.getSimpleName() + FUNCTION_POINTER_POSTFIX; + else + return interfaceName + "_" + alt_annotation.value() + FUNCTION_POINTER_POSTFIX; + */ + if (alt_annotation == null || (alt_annotation.nativeAlt() && !forceAlt)) { + return method.getSimpleName().toString(); + } else { + return alt_annotation.value(); + } + } - public static boolean isFinal(InterfaceDeclaration d) { - Extension extension_annotation = d.getAnnotation(Extension.class); - return extension_annotation == null || extension_annotation.isFinal(); - } + public static boolean isFinal(Element d) { + Extension extension_annotation = d.getAnnotation(Extension.class); + return extension_annotation == null || extension_annotation.isFinal(); + } - private static class AnnotationMirrorComparator implements Comparator { + private static class AnnotationMirrorComparator implements Comparator { - public int compare(AnnotationMirror a1, AnnotationMirror a2) { - String n1 = a1.getAnnotationType().getDeclaration().getQualifiedName(); - String n2 = a2.getAnnotationType().getDeclaration().getQualifiedName(); - int result = n1.compareTo(n2); - return result; - } + /** + * Sort annotations. + */ + @Override + public int compare(AnnotationMirror a1, AnnotationMirror a2) { + String n1 = a1.getAnnotationType().toString(); + String n2 = a2.getAnnotationType().toString(); + int result = n1.compareTo(n2); + return result; + } - public boolean equals(AnnotationMirror a1, AnnotationMirror a2) { - return compare(a1, a2) == 0; - } - } + public boolean equals(AnnotationMirror a1, AnnotationMirror a2) { + return compare(a1, a2) == 0; + } + } - public static Collection getSortedAnnotations(Collection annotations) { - List annotation_list = new ArrayList(annotations); - Collections.sort(annotation_list, new AnnotationMirrorComparator()); - return annotation_list; - } + public static List getSortedAnnotations(List annotations) { + List annotation_list = new ArrayList<>(annotations); + Collections.sort(annotation_list, new AnnotationMirrorComparator()); + return annotation_list; + } - public static String getReferenceName(InterfaceDeclaration interface_decl, MethodDeclaration method, ParameterDeclaration param) { - return interface_decl.getSimpleName() + "_" + method.getSimpleName() + "_" + param.getSimpleName(); - } + public static String getReferenceName(TypeElement interface_decl, ExecutableElement method, VariableElement param) { + return interface_decl.getSimpleName() + "_" + method.getSimpleName() + "_" + param.getSimpleName(); + } - public static boolean isAddressableType(TypeMirror type) { - return isAddressableType(getJavaType(type)); - } + public static boolean isAddressableType(TypeMirror type) { + return isAddressableType(getJavaType(type)); + } - public static boolean isAddressableType(Class type) { - if ( type.isArray() ) { - final Class component_type = type.getComponentType(); - return isAddressableTypeImpl(component_type) || org.lwjgl.PointerWrapper.class.isAssignableFrom(component_type); - } - return isAddressableTypeImpl(type); - } + public static boolean isAddressableType(Class type) { + if (type.isArray()) { + final Class component_type = type.getComponentType(); + return isAddressableTypeImpl(component_type) || org.lwjgl.PointerWrapper.class.isAssignableFrom(component_type); + } + return isAddressableTypeImpl(type); + } - private static boolean isAddressableTypeImpl(Class type) { - return Buffer.class.isAssignableFrom(type) || PointerBuffer.class.isAssignableFrom(type) || CharSequence.class.isAssignableFrom(type); - } + private static boolean isAddressableTypeImpl(Class type) { + return Buffer.class.isAssignableFrom(type) || PointerBuffer.class.isAssignableFrom(type) || CharSequence.class.isAssignableFrom(type); + } - public static Class getJavaType(TypeMirror type_mirror) { - JavaTypeTranslator translator = new JavaTypeTranslator(); - type_mirror.accept(translator); - return translator.getType(); - } + public static Class getJavaType(TypeMirror type_mirror) { + JavaTypeTranslator translator = new JavaTypeTranslator(); + type_mirror.accept((TypeVisitor) translator, null); + return translator.getType(); + } - private static boolean hasParameterMultipleTypes(ParameterDeclaration param) { - int num_native_annotations = 0; - for ( AnnotationMirror annotation : param.getAnnotationMirrors() ) - if ( NativeTypeTranslator.getAnnotation(annotation, NativeType.class) != null ) - num_native_annotations++; - return num_native_annotations > 1; - } + private static boolean hasParameterMultipleTypes(VariableElement param) { + int num_native_annotations = 0; + for (AnnotationMirror annotation : param.getAnnotationMirrors()) { + if (NativeTypeTranslator.getAnnotation(annotation, NativeType.class) != null) { + num_native_annotations++; + } + } + return num_native_annotations > 1; + } - public static boolean isParameterMultiTyped(ParameterDeclaration param) { - boolean result = Buffer.class.equals(Utils.getJavaType(param.getType())); - if ( !result && hasParameterMultipleTypes(param) ) - throw new RuntimeException(param + " not defined as java.nio.Buffer but has multiple types"); - return result; - } + public static boolean isParameterMultiTyped(VariableElement param) { + boolean result = Buffer.class.equals(Utils.getJavaType(param.asType())); + if (!result && hasParameterMultipleTypes(param)) { + throw new RuntimeException(param + " not defined as java.nio.Buffer but has multiple types"); + } + return result; + } - public static ParameterDeclaration findParameter(MethodDeclaration method, String name) { - for ( ParameterDeclaration param : method.getParameters() ) - if ( param.getSimpleName().equals(name) ) - return param; - throw new RuntimeException("Parameter " + name + " not found"); - } + public static VariableElement findParameter(ExecutableElement method, String name) { + for (VariableElement param : method.getParameters()) { + if (param.getSimpleName().toString().equals(name)) { + return param; + } + } + throw new RuntimeException("Parameter " + name + " not found"); + } - public static void printDocComment(PrintWriter writer, Declaration decl) { - final String overloadsComment; - if ( (decl instanceof MethodDeclaration) && decl.getAnnotation(Alternate.class) != null ) - overloadsComment = "Overloads " + decl.getAnnotation(Alternate.class).value() + "."; - else - overloadsComment = null; + public static void printDocComment(PrintWriter writer, Element decl, ProcessingEnvironment pe) { + final String overloadsComment; + if ((decl instanceof ExecutableElement) && decl.getAnnotation(Alternate.class) != null) { + overloadsComment = "Overloads " + decl.getAnnotation(Alternate.class).value() + "."; + } else { + overloadsComment = null; + } - String doc_comment = decl.getDocComment(); - if ( doc_comment != null ) { - final String tab = decl instanceof InterfaceDeclaration ? "" : "\t"; - writer.println(tab + "/**"); + String doc_comment = pe.getElementUtils().getDocComment(decl); + if (doc_comment != null) { + final String tab = (decl instanceof TypeElement) ? "" : "\t"; + writer.println(tab + "/**"); - if ( overloadsComment != null ) { - writer.println("\t * " + overloadsComment); - writer.println("\t *

"); - } + if (overloadsComment != null) { + writer.println("\t * " + overloadsComment); + writer.println("\t *

"); + } - final StringTokenizer doc_lines = new StringTokenizer(doc_comment, "\n", true); - boolean lastWasNL = false; - while ( doc_lines.hasMoreTokens() ) { - final String t = doc_lines.nextToken(); - if ( "\n".equals(t) ) { - if ( lastWasNL ) - writer.println(tab + " *

"); - lastWasNL = true; - } else { - writer.println(tab + " * " + t); - lastWasNL = false; - } - } + final StringTokenizer doc_lines = new StringTokenizer(doc_comment, "\n", true); + boolean lastWasNL = false; + while (doc_lines.hasMoreTokens()) { + final String t = doc_lines.nextToken(); + if ("\n".equals(t)) { + if (lastWasNL) { + writer.println(tab + " *

"); + } + lastWasNL = true; + } else { + writer.println(tab + " * " + t); + lastWasNL = false; + } + } - writer.println(tab + " */"); - } else if ( overloadsComment != null ) - writer.println("\t/** " + overloadsComment + " */"); - } + writer.println(tab + " */"); + } else if (overloadsComment != null) { + writer.println("\t/** " + overloadsComment + " */"); + } + } - public static AnnotationMirror getParameterAutoAnnotation(ParameterDeclaration param) { - for ( AnnotationMirror annotation : param.getAnnotationMirrors() ) - if ( NativeTypeTranslator.getAnnotation(annotation, Auto.class) != null ) - return annotation; - return null; - } + public static AnnotationMirror getParameterAutoAnnotation(VariableElement param) { + for (AnnotationMirror annotation : param.getAnnotationMirrors()) { + if (NativeTypeTranslator.getAnnotation(annotation, Auto.class) != null) { + return annotation; + } + } + return null; + } - // DISABLED: We always generate indirect methods. (affects OpenAL only at the time of this change) - public static boolean isMethodIndirect(boolean generate_error_checks, boolean context_specific, MethodDeclaration method) { - /* - for (ParameterDeclaration param : method.getParameters()) { - if (isAddressableType(param.getType()) || getParameterAutoAnnotation(param) != null || - param.getAnnotation(Constant.class) != null) - return true; - } - return hasMethodBufferObjectParameter(method) || method.getAnnotation(Code.class) != null || - method.getAnnotation(CachedResult.class) != null || - (generate_error_checks && method.getAnnotation(NoErrorCheck.class) == null) || - context_specific; - */ - return true; - } + // DISABLED: We always generate indirect methods. (affects OpenAL only at the time of this change) + public static boolean isMethodIndirect(boolean generate_error_checks, boolean context_specific, ExecutableElement method) { + /* + for (VariableElement param : method.getParameters()) { + if (isAddressableType(param.getType()) || getParameterAutoAnnotation(param) != null || + param.getAnnotation(Constant.class) != null) + return true; + } + return hasMethodBufferObjectParameter(method) || method.getAnnotation(Code.class) != null || + method.getAnnotation(CachedResult.class) != null || + (generate_error_checks && method.getAnnotation(NoErrorCheck.class) == null) || + context_specific; + */ + return true; + } - public static String getNativeQualifiedName(String qualified_name) { - return qualified_name.replaceAll("\\.", "_"); - } + public static String getNativeQualifiedName(String qualified_name) { + return qualified_name.replaceAll("\\.", "_"); + } - public static String getQualifiedNativeMethodName(String qualified_class_name, String method_name) { - // Escape '_' in method name - if ( method_name.indexOf('_') != -1 ) - method_name = method_name.replace("_", "_1"); + public static String getQualifiedNativeMethodName(String qualified_class_name, String method_name) { + // Escape '_' in method name + if (method_name.indexOf('_') != -1) { + method_name = method_name.replace("_", "_1"); + } - return "Java_" + getNativeQualifiedName(qualified_class_name) + "_" + method_name; - } + return "Java_" + getNativeQualifiedName(qualified_class_name) + "_" + method_name; + } - public static String getQualifiedNativeMethodName(String qualified_class_name, MethodDeclaration method, boolean generate_error_checks, boolean context_specific) { - String method_name = getSimpleNativeMethodName(method, generate_error_checks, context_specific); - return getQualifiedNativeMethodName(qualified_class_name, method_name); - } + public static String getQualifiedNativeMethodName(String qualified_class_name, ExecutableElement method, boolean generate_error_checks, boolean context_specific) { + String method_name = getSimpleNativeMethodName(method, generate_error_checks, context_specific); + return getQualifiedNativeMethodName(qualified_class_name, method_name); + } - public static ParameterDeclaration getResultParameter(MethodDeclaration method) { - ParameterDeclaration result_param = null; - for ( ParameterDeclaration param : method.getParameters() ) { - if ( param.getAnnotation(Result.class) != null ) { - if ( result_param != null ) - throw new RuntimeException("Multiple parameters annotated with Result in method " + method); - result_param = param; - } - } - return result_param; - } + public static VariableElement getResultParameter(ExecutableElement method) { + VariableElement result_param = null; + for (VariableElement param : method.getParameters()) { + if (param.getAnnotation(Result.class) != null) { + if (result_param != null) { + throw new RuntimeException("Multiple parameters annotated with Result in method " + method); + } + result_param = param; + } + } + return result_param; + } - public static TypeMirror getMethodReturnType(MethodDeclaration method) { - TypeMirror result_type; - ParameterDeclaration result_param = getResultParameter(method); - if ( result_param != null ) { - result_type = result_param.getType(); - } else - result_type = method.getReturnType(); - return result_type; - } + public static TypeMirror getMethodReturnType(ExecutableElement method) { + TypeMirror result_type; + VariableElement result_param = getResultParameter(method); + if (result_param != null) { + result_type = result_param.asType(); + } else { + result_type = method.getReturnType(); + } + return result_type; + } - public static String getMethodReturnType(MethodDeclaration method, GLreturn return_annotation, boolean buffer) { - ParameterDeclaration return_param = null; - for ( ParameterDeclaration param : method.getParameters() ) { - if ( param.getSimpleName().equals(return_annotation.value()) ) { - return_param = param; - break; - } - } - if ( return_param == null ) - throw new RuntimeException("The @GLreturn parameter \"" + return_annotation.value() + "\" could not be found in method: " + method); + public static String getMethodReturnType(ExecutableElement method, GLreturn return_annotation, boolean buffer) { + VariableElement return_param = null; + for (VariableElement param : method.getParameters()) { + if (param.getSimpleName().toString().equals(return_annotation.value())) { + return_param = param; + break; + } + } + if (return_param == null) { + throw new RuntimeException("The @GLreturn parameter \"" + return_annotation.value() + "\" could not be found in method: " + method); + } - PrimitiveType.Kind kind = NativeTypeTranslator.getPrimitiveKindFromBufferClass(Utils.getJavaType(return_param.getType())); - if ( return_param.getAnnotation(GLboolean.class) != null ) - kind = PrimitiveType.Kind.BOOLEAN; + TypeKind kind = NativeTypeTranslator.getPrimitiveKindFromBufferClass(Utils.getJavaType(return_param.asType())); + if (return_param.getAnnotation(GLboolean.class) != null) { + kind = TypeKind.BOOLEAN; + } - if ( kind == PrimitiveType.Kind.BYTE && (return_param.getAnnotation(GLchar.class) != null || return_param.getAnnotation(GLcharARB.class) != null) ) - return "String"; - else { - final String type = JavaTypeTranslator.getPrimitiveClassFromKind(kind).getName(); - return buffer ? Character.toUpperCase(type.charAt(0)) + type.substring(1) : type; - } - } + if (kind == TypeKind.BYTE && (return_param.getAnnotation(GLchar.class) != null || return_param.getAnnotation(GLcharARB.class) != null)) { + return "String"; + } else { + final String type = JavaTypeTranslator.getPrimitiveClassFromKind(kind).getName(); + return buffer ? Character.toUpperCase(type.charAt(0)) + type.substring(1) : type; + } + } - public static boolean needResultSize(MethodDeclaration method) { - return getNIOBufferType(getMethodReturnType(method)) != null && method.getAnnotation(AutoSize.class) == null; - } + public static boolean needResultSize(ExecutableElement method) { + return getNIOBufferType(getMethodReturnType(method)) != null && method.getAnnotation(AutoSize.class) == null; + } - public static void printExtraCallArguments(PrintWriter writer, MethodDeclaration method, String size_parameter_name) { - writer.print(size_parameter_name); - if ( method.getAnnotation(CachedResult.class) != null ) { - writer.print(", " + CACHED_BUFFER_NAME); - } - } + public static void printExtraCallArguments(PrintWriter writer, ExecutableElement method, String size_parameter_name) { + writer.print(size_parameter_name); + if (method.getAnnotation(CachedResult.class) != null) { + writer.print(", " + CACHED_BUFFER_NAME); + } + } - private static String getClassName(InterfaceDeclaration interface_decl, String opengl_name) { - Extension extension_annotation = interface_decl.getAnnotation(Extension.class); - if ( extension_annotation != null && !"".equals(extension_annotation.className()) ) { - return extension_annotation.className(); - } - StringBuilder result = new StringBuilder(); - for ( int i = 0; i < opengl_name.length(); i++ ) { - int ch = opengl_name.codePointAt(i); - if ( ch == '_' ) { - i++; - result.appendCodePoint(Character.toUpperCase(opengl_name.codePointAt(i))); - } else - result.appendCodePoint(ch); - } - return result.toString(); - } + private static String getClassName(TypeElement interface_decl, String opengl_name) { + Extension extension_annotation = interface_decl.getAnnotation(Extension.class); + if (extension_annotation != null && !"".equals(extension_annotation.className())) { + return extension_annotation.className(); + } + StringBuilder result = new StringBuilder(); + for (int i = 0; i < opengl_name.length(); i++) { + int ch = opengl_name.codePointAt(i); + if (ch == '_') { + i++; + result.appendCodePoint(Character.toUpperCase(opengl_name.codePointAt(i))); + } else { + result.appendCodePoint(ch); + } + } + return result.toString(); + } - public static boolean hasMethodBufferObjectParameter(MethodDeclaration method) { - for ( ParameterDeclaration param : method.getParameters() ) { - if ( param.getAnnotation(BufferObject.class) != null ) { - return true; - } - } - return false; - } + public static boolean hasMethodBufferObjectParameter(ExecutableElement method) { + for (VariableElement param : method.getParameters()) { + if (param.getAnnotation(BufferObject.class) != null) { + return true; + } + } + return false; + } - public static String getQualifiedClassName(InterfaceDeclaration interface_decl) { - return interface_decl.getPackage().getQualifiedName() + "." + getSimpleClassName(interface_decl); - } + public static String getQualifiedClassName(TypeElement interface_decl) { + return interface_decl.getEnclosingElement().asType().toString() + "." + getSimpleClassName(interface_decl); + } - public static String getSimpleClassName(InterfaceDeclaration interface_decl) { - return getClassName(interface_decl, interface_decl.getSimpleName()); - } + public static String getSimpleClassName(TypeElement interface_decl) { + return getClassName(interface_decl, interface_decl.getSimpleName().toString()); + } - public static Class getNIOBufferType(TypeMirror t) { - Class param_type = getJavaType(t); - if ( Buffer.class.isAssignableFrom(param_type) ) - return param_type; - else if ( param_type == CharSequence.class || param_type == CharSequence[].class || param_type == PointerBuffer.class ) - return ByteBuffer.class; - else - return null; - } + public static Class getNIOBufferType(TypeMirror t) { + Class param_type = getJavaType(t); + if (Buffer.class.isAssignableFrom(param_type)) { + return param_type; + } else if (param_type == CharSequence.class || param_type == CharSequence[].class || param_type == PointerBuffer.class) { + return ByteBuffer.class; + } else { + return null; + } + } - public static String getSimpleNativeMethodName(MethodDeclaration method, boolean generate_error_checks, boolean context_specific) { - String method_name; - Alternate alt_annotation = method.getAnnotation(Alternate.class); - method_name = alt_annotation == null || alt_annotation.nativeAlt() ? method.getSimpleName() : alt_annotation.value(); - if ( isMethodIndirect(generate_error_checks, context_specific, method) ) - method_name = OVERLOADED_METHOD_PREFIX + method_name; - return method_name; - } + public static String getSimpleNativeMethodName(ExecutableElement method, boolean generate_error_checks, boolean context_specific) { + String method_name; + Alternate alt_annotation = method.getAnnotation(Alternate.class); + method_name = alt_annotation == null || alt_annotation.nativeAlt() ? method.getSimpleName().toString() : alt_annotation.value(); + if (isMethodIndirect(generate_error_checks, context_specific, method)) { + method_name = OVERLOADED_METHOD_PREFIX + method_name; + } + return method_name; + } - static boolean isReturnParameter(MethodDeclaration method, ParameterDeclaration param) { - GLreturn string_annotation = method.getAnnotation(GLreturn.class); - if ( string_annotation == null || !string_annotation.value().equals(param.getSimpleName()) ) - return false; + static boolean isReturnParameter(ExecutableElement method, VariableElement param) { + GLreturn string_annotation = method.getAnnotation(GLreturn.class); + if (string_annotation == null || !string_annotation.value().equals(param.getSimpleName().toString())) { + return false; + } - if ( param.getAnnotation(OutParameter.class) == null ) - throw new RuntimeException("The parameter specified in @GLreturn is not annotated with @OutParameter in method: " + method); + if (param.getAnnotation(OutParameter.class) == null) { + throw new RuntimeException("The parameter specified in @GLreturn is not annotated with @OutParameter in method: " + method); + } - if ( param.getAnnotation(Check.class) != null ) - throw new RuntimeException("The parameter specified in @GLreturn is annotated with @Check in method: " + method); + if (param.getAnnotation(Check.class) != null) { + throw new RuntimeException("The parameter specified in @GLreturn is annotated with @Check in method: " + method); + } - if ( param.getAnnotation(GLchar.class) != null && Utils.getJavaType(param.getType()).equals(ByteBuffer.class) && string_annotation.maxLength().length() == 0 ) - throw new RuntimeException("The @GLreturn annotation is missing a maxLength parameter in method: " + method); + if (param.getAnnotation(GLchar.class) != null && Utils.getJavaType(param.asType()).equals(ByteBuffer.class) && string_annotation.maxLength().length() == 0) { + throw new RuntimeException("The @GLreturn annotation is missing a maxLength parameter in method: " + method); + } - return true; - } + return true; + } - static String getStringOffset(MethodDeclaration method, ParameterDeclaration param) { - String offset = null; - for ( ParameterDeclaration p : method.getParameters() ) { - if ( param != null && p.getSimpleName().equals(param.getSimpleName()) ) - break; + static String getStringOffset(ExecutableElement method, VariableElement param) { + String offset = null; + for (VariableElement p : method.getParameters()) { + if (param != null && p.getSimpleName().equals(param.getSimpleName())) { + break; + } - if ( p.getAnnotation(NullTerminated.class) != null ) - continue; + if (p.getAnnotation(NullTerminated.class) != null) { + continue; + } - final Class type = Utils.getJavaType(p.getType()); - if ( type.equals(CharSequence.class) ) { - if ( offset == null ) - offset = p.getSimpleName() + ".length()"; - else - offset += " + " + p.getSimpleName() + ".length()"; - //if ( p.getAnnotation(NullTerminated.class) != null ) offset += " + 1"; - } else if ( type.equals(CharSequence[].class) ) { - if ( offset == null ) - offset = "APIUtil.getTotalLength(" + p.getSimpleName() + ")"; - else - offset += " + APIUtil.getTotalLength(" + p.getSimpleName() + ")"; - //if ( p.getAnnotation(NullTerminated.class) != null ) offset += " + " + p.getSimpleName() + ".length"; - } + final Class type = Utils.getJavaType(p.asType()); + if (type.equals(CharSequence.class)) { + if (offset == null) { + offset = p.getSimpleName() + ".length()"; + } else { + offset += " + " + p.getSimpleName() + ".length()"; + } + //if ( p.getAnnotation(NullTerminated.class) != null ) offset += " + 1"; + } else if (type.equals(CharSequence[].class)) { + if (offset == null) { + offset = "APIUtil.getTotalLength(" + p.getSimpleName() + ")"; + } else { + offset += " + APIUtil.getTotalLength(" + p.getSimpleName() + ")"; + } + //if ( p.getAnnotation(NullTerminated.class) != null ) offset += " + " + p.getSimpleName() + ".length"; + } - } - return offset; - } + } + return offset; + } - static void printGLReturnPre(PrintWriter writer, MethodDeclaration method, GLreturn return_annotation, TypeMap type_map) { - final String return_type = getMethodReturnType(method, return_annotation, true); + static void printGLReturnPre(PrintWriter writer, ExecutableElement method, GLreturn return_annotation, TypeMap type_map) { + final String return_type = getMethodReturnType(method, return_annotation, true); - if ( "String".equals(return_type) ) { - if ( !return_annotation.forceMaxLength() ) { - writer.println("IntBuffer " + return_annotation.value() + "_length = APIUtil.getLengths(" + type_map.getAPIUtilParam(false) + ");"); - writer.print("\t\t"); - } - writer.print("ByteBuffer " + return_annotation.value() + " = APIUtil.getBufferByte(" + type_map.getAPIUtilParam(true) + return_annotation.maxLength()); - /* - Params that use the return buffer will advance its position while filling it. When we return, the position will be - at the right spot for grabbing the returned string bytes. We only have to make sure that the original buffer was - large enough to hold everything, so that no re-allocations happen while filling. - */ - final String offset = getStringOffset(method, null); - if ( offset != null ) - writer.print(" + " + offset); - writer.println(");"); - } else { - final String buffer_type = "Boolean".equals(return_type) ? "Byte" : return_type; - writer.print(buffer_type + "Buffer " + return_annotation.value() + " = APIUtil.getBuffer" + buffer_type + "(" + type_map.getAPIUtilParam(false)); - if ( "Byte".equals(buffer_type) ) - writer.print((type_map.getAPIUtilParam(false).length() > 0 ? ", " : "") + "1"); - writer.println(");"); - } + if ("String".equals(return_type)) { + if (!return_annotation.forceMaxLength()) { + writer.println("IntBuffer " + return_annotation.value() + "_length = APIUtil.getLengths(" + type_map.getAPIUtilParam(false) + ");"); + writer.print("\t\t"); + } + writer.print("ByteBuffer " + return_annotation.value() + " = APIUtil.getBufferByte(" + type_map.getAPIUtilParam(true) + return_annotation.maxLength()); + /* + Params that use the return buffer will advance its position while filling it. When we return, the position will be + at the right spot for grabbing the returned string bytes. We only have to make sure that the original buffer was + large enough to hold everything, so that no re-allocations happen while filling. + */ + final String offset = getStringOffset(method, null); + if (offset != null) { + writer.print(" + " + offset); + } + writer.println(");"); + } else { + final String buffer_type = "Boolean".equals(return_type) ? "Byte" : return_type; + writer.print(buffer_type + "Buffer " + return_annotation.value() + " = APIUtil.getBuffer" + buffer_type + "(" + type_map.getAPIUtilParam(false)); + if ("Byte".equals(buffer_type)) { + writer.print((type_map.getAPIUtilParam(false).length() > 0 ? ", " : "") + "1"); + } + writer.println(");"); + } - final Code code_annotation = method.getAnnotation(Code.class); - if ( code_annotation != null && code_annotation.tryBlock() ) { - writer.println("\t\ttry {"); - writer.print("\t\t\t"); - } else - writer.print("\t\t"); - } + final Code code_annotation = method.getAnnotation(Code.class); + if (code_annotation != null && code_annotation.tryBlock()) { + writer.println("\t\ttry {"); + writer.print("\t\t\t"); + } else { + writer.print("\t\t"); + } + } - static void printGLReturnPost(PrintWriter writer, MethodDeclaration method, GLreturn return_annotation, TypeMap type_map) { - final String return_type = getMethodReturnType(method, return_annotation, true); + static void printGLReturnPost(PrintWriter writer, ExecutableElement method, GLreturn return_annotation, TypeMap type_map) { + final String return_type = getMethodReturnType(method, return_annotation, true); - if ( "String".equals(return_type) ) { - writer.print("\t\t" + return_annotation.value() + ".limit("); - final String offset = getStringOffset(method, null); - if ( offset != null ) - writer.print(offset + " + "); - if ( return_annotation.forceMaxLength() ) - writer.print(return_annotation.maxLength()); - else - writer.print(return_annotation.value() + "_length.get(0)"); - writer.println(");"); - writer.println("\t\treturn APIUtil.getString(" + type_map.getAPIUtilParam(true) + return_annotation.value() + ");"); - } else { - writer.print("\t\treturn " + return_annotation.value() + ".get(0)"); - if ( "Boolean".equals(return_type) ) - writer.print(" == 1"); - writer.println(";"); - } - } + if ("String".equals(return_type)) { + writer.print("\t\t" + return_annotation.value() + ".limit("); + final String offset = getStringOffset(method, null); + if (offset != null) { + writer.print(offset + " + "); + } + if (return_annotation.forceMaxLength()) { + writer.print(return_annotation.maxLength()); + } else { + writer.print(return_annotation.value() + "_length.get(0)"); + } + writer.println(");"); + writer.println("\t\treturn APIUtil.getString(" + type_map.getAPIUtilParam(true) + return_annotation.value() + ");"); + } else { + writer.print("\t\treturn " + return_annotation.value() + ".get(0)"); + if ("Boolean".equals(return_type)) { + writer.print(" == 1"); + } + writer.println(";"); + } + } + + public static Collection getFields(TypeElement d) { + Collection fields = ElementFilter.fieldsIn(new HashSet(d.getEnclosedElements())); + return fields; + } + + public static Collection getMethods(TypeElement d) { + Collection fields = ElementFilter.methodsIn(new HashSet(d.getEnclosedElements())); + return fields; + } } diff --git a/src/java/org/lwjgl/util/generator/openal/ALTypeMap.java b/src/java/org/lwjgl/util/generator/openal/ALTypeMap.java index e1aed20e..9a20d804 100644 --- a/src/java/org/lwjgl/util/generator/openal/ALTypeMap.java +++ b/src/java/org/lwjgl/util/generator/openal/ALTypeMap.java @@ -41,42 +41,44 @@ package org.lwjgl.util.generator.openal; * $Id: ALTypeMap.java 2983 2008-04-07 18:36:09Z matzon $ */ -import org.lwjgl.util.generator.Signedness; -import org.lwjgl.util.generator.TypeMap; - -import com.sun.mirror.declaration.*; -import com.sun.mirror.type.*; import java.io.*; import java.lang.annotation.Annotation; -import java.util.*; import java.nio.*; +import java.util.*; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.type.TypeKind; +import org.lwjgl.util.generator.Signedness; +import org.lwjgl.util.generator.TypeMap; public class ALTypeMap implements TypeMap { - private static final Map native_types_to_primitive; + private static final Map native_types_to_primitive; static { - native_types_to_primitive = new HashMap(); - native_types_to_primitive.put(ALboolean.class, PrimitiveType.Kind.BOOLEAN); - native_types_to_primitive.put(ALbyte.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(ALenum.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(ALfloat.class, PrimitiveType.Kind.FLOAT); - native_types_to_primitive.put(ALdouble.class, PrimitiveType.Kind.DOUBLE); - native_types_to_primitive.put(ALint.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(ALshort.class, PrimitiveType.Kind.SHORT); - native_types_to_primitive.put(ALsizei.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(ALubyte.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(ALuint.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(ALvoid.class, PrimitiveType.Kind.BYTE); + native_types_to_primitive = new HashMap<>(); + native_types_to_primitive.put(ALboolean.class, TypeKind.BOOLEAN); + native_types_to_primitive.put(ALbyte.class, TypeKind.BYTE); + native_types_to_primitive.put(ALenum.class, TypeKind.INT); + native_types_to_primitive.put(ALfloat.class, TypeKind.FLOAT); + native_types_to_primitive.put(ALdouble.class, TypeKind.DOUBLE); + native_types_to_primitive.put(ALint.class, TypeKind.INT); + native_types_to_primitive.put(ALshort.class, TypeKind.SHORT); + native_types_to_primitive.put(ALsizei.class, TypeKind.INT); + native_types_to_primitive.put(ALubyte.class, TypeKind.BYTE); + native_types_to_primitive.put(ALuint.class, TypeKind.INT); + native_types_to_primitive.put(ALvoid.class, TypeKind.BYTE); } - public PrimitiveType.Kind getPrimitiveTypeFromNativeType(Class native_type) { - PrimitiveType.Kind kind = native_types_to_primitive.get(native_type); + @Override + public TypeKind getPrimitiveTypeFromNativeType(Class native_type) { + TypeKind kind = native_types_to_primitive.get(native_type); if (kind == null) throw new RuntimeException("Unsupported type " + native_type); return kind; } + @Override public Signedness getSignednessFromType(Class type) { if (ALuint.class.equals(type)) return Signedness.UNSIGNED; @@ -90,6 +92,7 @@ public class ALTypeMap implements TypeMap { return Signedness.NONE; } + @Override public String translateAnnotation(Class annotation_type) { if (annotation_type.equals(ALuint.class)) return "i"; @@ -109,7 +112,8 @@ public class ALTypeMap implements TypeMap { throw new RuntimeException(annotation_type + " is not allowed"); } - public Class getNativeTypeFromPrimitiveType(PrimitiveType.Kind kind) { + @Override + public Class getNativeTypeFromPrimitiveType(TypeKind kind) { Class type; switch (kind) { case INT: @@ -170,50 +174,62 @@ public class ALTypeMap implements TypeMap { return new Class[]{}; } + @Override public void printCapabilitiesInit(final PrintWriter writer) { throw new UnsupportedOperationException(); } + @Override public String getCapabilities() { throw new UnsupportedOperationException(); } + @Override public String getAPIUtilParam(boolean comma) { return ""; } - public void printErrorCheckMethod(final PrintWriter writer, final MethodDeclaration method, final String tabs) { + @Override + public void printErrorCheckMethod(final PrintWriter writer, final ExecutableElement method, final String tabs) { writer.println(tabs + "Util.checkALError();"); } + @Override public String getRegisterNativesFunctionName() { return "extal_InitializeClass"; } + @Override public String getTypedefPostfix() { return ""; } + @Override public String getFunctionPrefix() { return "ALAPIENTRY"; } + @Override public void printNativeIncludes(PrintWriter writer) { writer.println("#include \"extal.h\""); } + @Override public Class getStringElementType() { return ALubyte.class; } + @Override public Class getStringArrayType() { return ALubyte.class; } + @Override public Class getByteBufferArrayType() { return ALubyte.class; } + @Override public Class[] getValidAnnotationTypes(Class type) { Class[] valid_types; if (Buffer.class.isAssignableFrom(type)) @@ -227,10 +243,12 @@ public class ALTypeMap implements TypeMap { return valid_types; } + @Override public Class getVoidType() { return ALvoid.class; } + @Override public Class getInverseType(Class type) { if (ALuint.class.equals(type)) return ALint.class; @@ -240,6 +258,7 @@ public class ALTypeMap implements TypeMap { return null; } + @Override public String getAutoTypeFromAnnotation(AnnotationMirror annotation) { return null; } diff --git a/src/java/org/lwjgl/util/generator/opencl/CLCapabilitiesGenerator.java b/src/java/org/lwjgl/util/generator/opencl/CLCapabilitiesGenerator.java index fabeb1fa..9a7249d8 100644 --- a/src/java/org/lwjgl/util/generator/opencl/CLCapabilitiesGenerator.java +++ b/src/java/org/lwjgl/util/generator/opencl/CLCapabilitiesGenerator.java @@ -29,18 +29,15 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - package org.lwjgl.util.generator.opencl; -import org.lwjgl.util.generator.*; - import java.io.PrintWriter; -import java.util.Collection; import java.util.Iterator; - -import com.sun.mirror.declaration.InterfaceDeclaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; +import java.util.Set; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import org.lwjgl.util.generator.*; /** * CLCapabilities generator. @@ -49,111 +46,125 @@ import com.sun.mirror.declaration.TypeDeclaration; */ public class CLCapabilitiesGenerator { - static void generateClassPrologue(final PrintWriter writer) { - writer.println("public final class " + CLGeneratorProcessorFactory.CLCAPS_CLASS_NAME + " {"); - writer.println(); - } + static void generateClassPrologue(final PrintWriter writer) { + writer.println("public final class " + CLGeneratorProcessor.CLCAPS_CLASS_NAME + " {"); + writer.println(); + } - static void generateSymbolAddresses(final PrintWriter writer, final InterfaceDeclaration d) { - final Alias alias_annotation = d.getAnnotation(Alias.class); - final boolean aliased = alias_annotation != null && alias_annotation.postfix().length() > 0; + static void generateSymbolAddresses(ProcessingEnvironment env, final PrintWriter writer, final TypeElement d) { + if (d.getAnnotation(CLPlatformExtension.class) == null && d.getAnnotation(CLDeviceExtension.class) == null && !d.getSimpleName().toString().startsWith("CL")) { + throw new RuntimeException("An OpenCL extension is missing an extension type annotation: " + d.getSimpleName()); + } + final Alias alias_annotation = d.getAnnotation(Alias.class); + final boolean aliased = alias_annotation != null && alias_annotation.postfix().length() > 0; - boolean foundNative = false; - for ( final MethodDeclaration method : d.getMethods() ) { - if ( method.getAnnotation(Alternate.class) != null || method.getAnnotation(Reuse.class) != null ) - continue; + boolean foundNative = false; + for (final ExecutableElement method : Utils.getMethods( d)) { + if (method.getAnnotation(Alternate.class) != null || method.getAnnotation(Reuse.class) != null) { + continue; + } - if ( !foundNative ) { - //writer.println("\t// " + d.getSimpleName()); - writer.println("\tstatic final boolean " + CLGeneratorProcessorFactory.getExtensionName(d.getSimpleName()) + ";"); - foundNative = true; - } - writer.print("\tstatic final long " + Utils.getFunctionAddressName(d, method) + " = CL.getFunctionAddress("); + if (!foundNative) { + //writer.println("\t// " + d.getSimpleName()); + writer.println("\tstatic final boolean " + CLGeneratorProcessor.getExtensionName(d.getSimpleName().toString() + ";")); + foundNative = true; + } + writer.print("\tstatic final long " + Utils.getFunctionAddressName(d, method) + " = CL.getFunctionAddress("); - if ( aliased ) - writer.println("new String [] {\"" + Utils.getFunctionAddressName(d, method) + "\",\"" + method.getSimpleName() + alias_annotation.postfix() + "\"});"); - else - writer.println("\"" + Utils.getFunctionAddressName(d, method) + "\");"); - } + if (aliased) { + writer.println("new String [] {\"" + Utils.getFunctionAddressName(d, method) + "\",\"" + method.getSimpleName() + alias_annotation.postfix() + "\"});"); + } else { + writer.println("\"" + Utils.getFunctionAddressName(d, method) + "\");"); + } + } - if ( foundNative ) - writer.println(); - } + if (foundNative) { + writer.println(); + } + } - static void generateConstructor(final PrintWriter writer, final Collection interface_decls) { - writer.println("\tprivate " + CLGeneratorProcessorFactory.CLCAPS_CLASS_NAME + "() {}"); - writer.println(); - writer.println("\tstatic {"); + static void generateConstructor(ProcessingEnvironment env, final PrintWriter writer, final Set interface_decls) { + writer.println("\tprivate " + CLGeneratorProcessor.CLCAPS_CLASS_NAME + "() {}"); + writer.println(); + writer.println("\tstatic {"); - for ( final TypeDeclaration d : interface_decls ) { - if ( d.getMethods().isEmpty() ) - continue; + for (final TypeElement d : interface_decls) { + if (d.getKind().isInterface()) { + if (Utils.getMethods( d).isEmpty()) { + continue; + } - //writer.println("\t\tif ( " + getExtensionSupportedName(d.getSimpleName()) + "() )"); - //writer.println("\t\t\t" + SUPPORTED_EXTS + ".add(\"" + CLGeneratorProcessorFactory.getExtensionName(d.getSimpleName()) + "\");"); - writer.println("\t\t" + CLGeneratorProcessorFactory.getExtensionName(d.getSimpleName()) + " = " + getExtensionSupportedName(d.getSimpleName()) + "();"); - } + //writer.println("\t\tif ( " + getExtensionSupportedName(d.getSimpleName()) + "() )"); + //writer.println("\t\t\t" + SUPPORTED_EXTS + ".add(\"" + CLGeneratorProcessor.getExtensionName(d.getSimpleName()) + "\");"); + writer.println("\t\t" + CLGeneratorProcessor.getExtensionName(d.getSimpleName().toString()) + " = " + getExtensionSupportedName(d.getSimpleName().toString()) + "();"); + } + } - writer.println("\t}\n"); - } + writer.println("\t}\n"); + } - static void generateExtensionChecks(final PrintWriter writer, final InterfaceDeclaration d) { - Iterator methods = d.getMethods().iterator(); - if ( !methods.hasNext() ) - return; + static void generateExtensionChecks(ProcessingEnvironment env, final PrintWriter writer, TypeElement d) { + Iterator methods = Utils.getMethods( d).iterator(); + if (!methods.hasNext()) { + return; + } - writer.println("\tprivate static boolean " + getExtensionSupportedName(d.getSimpleName()) + "() {"); - writer.println("\t\treturn "); + writer.println("\tprivate static boolean " + getExtensionSupportedName(d.getSimpleName().toString()) + "() {"); + writer.println("\t\treturn "); - boolean first = true; - while ( methods.hasNext() ) { - MethodDeclaration method = methods.next(); - if ( method.getAnnotation(Alternate.class) != null ) - continue; + boolean first = true; + while (methods.hasNext()) { + ExecutableElement method = methods.next(); + if (method.getAnnotation(Alternate.class) != null) { + continue; + } - if ( !first ) - writer.println(" &"); - else - first = false; + if (!first) { + writer.println(" &"); + } else { + first = false; + } - final boolean optional = method.getAnnotation(Optional.class) != null; + final boolean optional = method.getAnnotation(Optional.class) != null; - writer.print("\t\t\t"); - if ( optional ) - writer.print('('); - writer.print(Utils.getFunctionAddressName(d, method) + " != 0"); - if ( optional ) - writer.print(" || true)"); - } - writer.println(";"); - writer.println("\t}"); - writer.println(); - } + writer.print("\t\t\t"); + if (optional) { + writer.print('('); + } + writer.print(Utils.getFunctionAddressName(d, method) + " != 0"); + if (optional) { + writer.print(" || true)"); + } + } + writer.println(";"); + writer.println("\t}"); + writer.println(); + } - private static String getExtensionSupportedName(final String class_name) { - return "is" + class_name + "Supported"; - } + private static String getExtensionSupportedName(final String class_name) { + return "is" + class_name + "Supported"; + } - public static void generateCapabilitiesGetters(final PrintWriter writer) { - writer.println("\tpublic static CLPlatformCapabilities getPlatformCapabilities(final CLPlatform platform) {\n" + - "\t\tplatform.checkValid();\n" + - "\n" + - "\t\tCLPlatformCapabilities caps = (CLPlatformCapabilities)platform.getCapabilities();\n" + - "\t\tif ( caps == null )\n" + - "\t\t\tplatform.setCapabilities(caps = new CLPlatformCapabilities(platform));\n" + - "\n" + - "\t\treturn caps;\n" + - "\t}\n"); + public static void generateCapabilitiesGetters(final PrintWriter writer) { + writer.println("\tpublic static CLPlatformCapabilities getPlatformCapabilities(final CLPlatform platform) {\n" + + "\t\tplatform.checkValid();\n" + + "\n" + + "\t\tCLPlatformCapabilities caps = (CLPlatformCapabilities)platform.getCapabilities();\n" + + "\t\tif ( caps == null )\n" + + "\t\t\tplatform.setCapabilities(caps = new CLPlatformCapabilities(platform));\n" + + "\n" + + "\t\treturn caps;\n" + + "\t}\n"); - writer.println("\tpublic static CLDeviceCapabilities getDeviceCapabilities(final CLDevice device) {\n" + - "\t\tdevice.checkValid();\n" + - "\n" + - "\t\tCLDeviceCapabilities caps = (CLDeviceCapabilities)device.getCapabilities();\n" + - "\t\tif ( caps == null )\n" + - "\t\t\tdevice.setCapabilities(caps = new CLDeviceCapabilities(device));\n" + - "\n" + - "\t\treturn caps;\n" + - "\t}\n"); + writer.println("\tpublic static CLDeviceCapabilities getDeviceCapabilities(final CLDevice device) {\n" + + "\t\tdevice.checkValid();\n" + + "\n" + + "\t\tCLDeviceCapabilities caps = (CLDeviceCapabilities)device.getCapabilities();\n" + + "\t\tif ( caps == null )\n" + + "\t\t\tdevice.setCapabilities(caps = new CLDeviceCapabilities(device));\n" + + "\n" + + "\t\treturn caps;\n" + + "\t}\n"); - } -} \ No newline at end of file + } +} diff --git a/src/java/org/lwjgl/util/generator/opencl/CLGeneratorProcessor.java b/src/java/org/lwjgl/util/generator/opencl/CLGeneratorProcessor.java new file mode 100644 index 00000000..5b7d046d --- /dev/null +++ b/src/java/org/lwjgl/util/generator/opencl/CLGeneratorProcessor.java @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjgl.util.generator.opencl; + +import java.io.IOException; +import java.io.PrintWriter; +import java.lang.annotation.Annotation; +import java.util.Set; +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.annotation.processing.SupportedOptions; +import javax.annotation.processing.SupportedSourceVersion; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.TypeElement; +import javax.lang.model.util.ElementFilter; +import org.lwjgl.PointerWrapper; +import org.lwjgl.opencl.CLDevice; +import org.lwjgl.opencl.CLPlatform; + +/** + * Generator tool for creating the OpenCL capabilities classes + * + * @author Spasi + */ +@SupportedAnnotationTypes({"*"}) +@SupportedSourceVersion(SourceVersion.RELEASE_7) +@SupportedOptions({"generatechecks", "contextspecific"}) +public class CLGeneratorProcessor extends AbstractProcessor { + + public static final String CLCAPS_CLASS_NAME = "CLCapabilities"; + public static final String PLATFORM_CAPS_CLASS_NAME = "CLPlatformCapabilities"; + public static final String DEVICE_CAPS_CLASS_NAME = "CLDeviceCapabilities"; + + private static final String EXTENSION_PREFIX = "CL_"; + private static final String CORE_PREFIX = "Open"; + + private static boolean first_round = true; + + static String getExtensionName(String interface_name) { + if (interface_name.startsWith("CL")) { + return CORE_PREFIX + interface_name; + } else { + return EXTENSION_PREFIX + interface_name; + } + } + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + if (roundEnv.processingOver() || !first_round) { + System.exit(0); + return true; + } + try { + Set templates = ElementFilter.typesIn(roundEnv.getRootElements()); + /** + * provide the full set of ex-InterfaceDeclaration + * annotated templates elements + */ + generateCLCapabilitiesSource(templates); + generateCLPDCapabilitiesSource(templates, CLPlatformExtension.class, PLATFORM_CAPS_CLASS_NAME, CLPlatform.class, "platform"); + generateCLPDCapabilitiesSource(templates, CLDeviceExtension.class, DEVICE_CAPS_CLASS_NAME, CLDevice.class, "device"); + first_round = false; + return true; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static void printHeader(final PrintWriter writer) { + writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */"); + writer.println(); + writer.println("package org.lwjgl.opencl;"); + writer.println(); + } + + private void generateCLCapabilitiesSource(Set templates) throws IOException { + final PrintWriter writer = new PrintWriter(processingEnv.getFiler().createSourceFile("org.lwjgl.opencl." + CLCAPS_CLASS_NAME, processingEnv.getElementUtils().getPackageElement("org.lwjgl.opencl")).openWriter()); + printHeader(writer); + + CLCapabilitiesGenerator.generateClassPrologue(writer); + for (TypeElement d : templates) { + if (d.getKind().isInterface()) { + CLCapabilitiesGenerator.generateSymbolAddresses(processingEnv, writer, d); + } + } + writer.println(); + + CLCapabilitiesGenerator.generateConstructor(processingEnv, writer, templates); + + CLCapabilitiesGenerator.generateCapabilitiesGetters(writer); + for (TypeElement d : templates) { + if (d.getKind().isInterface()) { + CLCapabilitiesGenerator.generateExtensionChecks(processingEnv, writer, d); + } + } + + writer.println("}"); + writer.close(); + } + + private void generateCLPDCapabilitiesSource(Set templates, final Class capsType, final String capsName, final Class objectType, final String objectName) throws IOException { + final PrintWriter writer = new PrintWriter(processingEnv.getFiler().createSourceFile("org.lwjgl.opencl." + capsName, processingEnv.getElementUtils().getPackageElement("org.lwjgl.opencl")).openWriter()); + printHeader(writer); + writer.println("import java.util.*;"); + writer.println(); + + CLPDCapabilitiesGenerator.generateClassPrologue(writer, capsName); + + for (TypeElement t : templates) { + if (t.getKind().isInterface() && t.getAnnotation(capsType) != null) { + CLPDCapabilitiesGenerator.generateExtensions(writer, (TypeElement) t); + } + } + writer.println(); + + CLPDCapabilitiesGenerator.generateConstructor(processingEnv, writer, templates, capsType, capsName, objectType, objectName); + + CLPDCapabilitiesGenerator.generateGetters(writer); + + CLPDCapabilitiesGenerator.generateToString(writer, templates, capsType); + + writer.println("}"); + writer.close(); + } +} diff --git a/src/java/org/lwjgl/util/generator/opencl/CLGeneratorProcessorFactory.java b/src/java/org/lwjgl/util/generator/opencl/CLGeneratorProcessorFactory.java deleted file mode 100644 index d881fc1b..00000000 --- a/src/java/org/lwjgl/util/generator/opencl/CLGeneratorProcessorFactory.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (c) 2002-2008 LWJGL Project - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'LWJGL' nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package org.lwjgl.util.generator.opencl; - -import org.lwjgl.PointerWrapper; -import org.lwjgl.opencl.CLDevice; -import org.lwjgl.opencl.CLPlatform; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.lang.annotation.Annotation; -import java.util.Arrays; -import java.util.Collection; -import java.util.Set; - -import com.sun.mirror.apt.*; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.InterfaceDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.util.DeclarationFilter; - -import static java.util.Collections.*; - -/** - * Generator tool for creating the OpenCL capabilities classes - * - * @author Spasi - */ -public class CLGeneratorProcessorFactory implements AnnotationProcessorFactory, RoundCompleteListener { - - public static final String CLCAPS_CLASS_NAME = "CLCapabilities"; - public static final String PLATFORM_CAPS_CLASS_NAME = "CLPlatformCapabilities"; - public static final String DEVICE_CAPS_CLASS_NAME = "CLDeviceCapabilities"; - - private static final String EXTENSION_PREFIX = "CL_"; - private static final String CORE_PREFIX = "Open"; - - private static boolean first_round = true; - - // Process any set of annotations - private static final Collection supportedAnnotations = unmodifiableCollection(Arrays.asList("*")); - - public Collection supportedAnnotationTypes() { - return supportedAnnotations; - } - - public Collection supportedOptions() { - return unmodifiableCollection(Arrays.asList("-Acontextspecific")); - } - - public void roundComplete(RoundCompleteEvent event) { - first_round = false; - } - - public AnnotationProcessor getProcessorFor(Set atds, AnnotationProcessorEnvironment env) { - // Only process the initial types, not the generated ones - if ( first_round ) { - env.addListener(this); - return new GeneratorProcessor(env); - } else - return AnnotationProcessors.NO_OP; - } - - static String getExtensionName(String interface_name) { - if ( interface_name.startsWith("CL") ) - return CORE_PREFIX + interface_name; - else - return EXTENSION_PREFIX + interface_name; - } - - private static class GeneratorProcessor implements AnnotationProcessor { - - private final AnnotationProcessorEnvironment env; - - GeneratorProcessor(AnnotationProcessorEnvironment env) { - this.env = env; - } - - public void process() { - try { - generateCLCapabilitiesSource(); - generateCLPDCapabilitiesSource(CLPlatformExtension.class, PLATFORM_CAPS_CLASS_NAME, CLPlatform.class, "platform"); - generateCLPDCapabilitiesSource(CLDeviceExtension.class, DEVICE_CAPS_CLASS_NAME, CLDevice.class, "device"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private static void printHeader(final PrintWriter writer) { - writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */"); - writer.println(); - writer.println("package org.lwjgl.opencl;"); - writer.println(); - } - - private void generateCLCapabilitiesSource() throws IOException { - final PrintWriter writer = env.getFiler().createTextFile(Filer.Location.SOURCE_TREE, "org.lwjgl.opencl", new File(CLCAPS_CLASS_NAME + ".java"), null); - printHeader(writer); - - CLCapabilitiesGenerator.generateClassPrologue(writer); - - final Collection templates = DeclarationFilter.getFilter(InterfaceDeclaration.class).filter(env.getSpecifiedTypeDeclarations()); - - for ( final TypeDeclaration t : templates ) { - if ( t.getAnnotation(CLPlatformExtension.class) == null && t.getAnnotation(CLDeviceExtension.class) == null && !t.getSimpleName().startsWith("CL") ) - throw new RuntimeException("An OpenCL extension is missing an extension type annotation: " + t.getSimpleName()); - - CLCapabilitiesGenerator.generateSymbolAddresses(writer, (InterfaceDeclaration)t); - } - writer.println(); - - CLCapabilitiesGenerator.generateConstructor(writer, templates); - - CLCapabilitiesGenerator.generateCapabilitiesGetters(writer); - - for ( final TypeDeclaration template : templates ) - CLCapabilitiesGenerator.generateExtensionChecks(writer, (InterfaceDeclaration)template); - - writer.println("}"); - writer.close(); - } - - private void generateCLPDCapabilitiesSource(final Class capsType, final String capsName, final Class objectType, final String objectName) throws IOException { - final PrintWriter writer = env.getFiler().createTextFile(Filer.Location.SOURCE_TREE, "org.lwjgl.opencl", new File(capsName + ".java"), null); - printHeader(writer); - writer.println("import java.util.*;"); - writer.println(); - - CLPDCapabilitiesGenerator.generateClassPrologue(writer, capsName); - - final Collection templates = DeclarationFilter.getFilter(InterfaceDeclaration.class).filter(env.getSpecifiedTypeDeclarations()); - - for ( final TypeDeclaration t : templates ) { - if ( t.getAnnotation(capsType) != null ) - CLPDCapabilitiesGenerator.generateExtensions(writer, (InterfaceDeclaration)t); - } - writer.println(); - - CLPDCapabilitiesGenerator.generateConstructor(writer, templates, capsType, capsName, objectType, objectName); - - CLPDCapabilitiesGenerator.generateGetters(writer); - - CLPDCapabilitiesGenerator.generateToString(writer, templates, capsType); - - writer.println("}"); - writer.close(); - } - - } -} \ No newline at end of file diff --git a/src/java/org/lwjgl/util/generator/opencl/CLPDCapabilitiesGenerator.java b/src/java/org/lwjgl/util/generator/opencl/CLPDCapabilitiesGenerator.java index 99a58c34..6b57b65e 100644 --- a/src/java/org/lwjgl/util/generator/opencl/CLPDCapabilitiesGenerator.java +++ b/src/java/org/lwjgl/util/generator/opencl/CLPDCapabilitiesGenerator.java @@ -32,16 +32,15 @@ package org.lwjgl.util.generator.opencl; +import java.io.PrintWriter; +import java.lang.annotation.Annotation; +import java.util.Set; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.TypeElement; import org.lwjgl.PointerWrapper; import org.lwjgl.util.generator.Extension; import org.lwjgl.util.generator.Private; - -import java.io.PrintWriter; -import java.lang.annotation.Annotation; -import java.util.Collection; - -import com.sun.mirror.declaration.InterfaceDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; +import org.lwjgl.util.generator.Utils; /** * CL platform/device capabilities generator. @@ -68,16 +67,16 @@ public class CLPDCapabilitiesGenerator { writer.println(); } - static void generateExtensions(final PrintWriter writer, final InterfaceDeclaration d) { + static void generateExtensions(final PrintWriter writer, final TypeElement d) { writer.print("\t"); if ( d.getAnnotation(Private.class) == null ) writer.print("public "); - writer.println("final boolean " + CLGeneratorProcessorFactory.getExtensionName(d.getSimpleName()) + ";"); + writer.println("final boolean " + CLGeneratorProcessor.getExtensionName(d.getSimpleName().toString()) + ";"); } - static void generateConstructor(final PrintWriter writer, final Collection templates, + static void generateConstructor(ProcessingEnvironment env, final PrintWriter writer, final Set templates, final Class capsType, final String capsName, final Class objectType, final String objectName) { writer.println("\tpublic " + capsName + "(final " + objectType.getSimpleName() + ' ' + objectName + ") {"); @@ -103,11 +102,11 @@ public class CLPDCapabilitiesGenerator { writer.println("\t\tfinal Set extensions = APIUtil.getExtensions(extensionList);"); - for ( final TypeDeclaration t : templates ) { + for ( final TypeElement t : templates ) { if ( t.getAnnotation(capsType) == null ) continue; - final String extName = CLGeneratorProcessorFactory.getExtensionName(t.getSimpleName()); + final String extName = CLGeneratorProcessor.getExtensionName(t.getSimpleName().toString()); String nativeName = extName.toLowerCase(); Extension ext = t.getAnnotation(Extension.class); @@ -115,7 +114,7 @@ public class CLPDCapabilitiesGenerator { nativeName = ext.nativeName(); writer.print("\t\t" + extName + " = extensions.contains(\"" + nativeName + "\")"); - if ( !t.getMethods().isEmpty() ) + if ( !Utils.getMethods( t).isEmpty() ) writer.print(" && CLCapabilities." + extName); writer.println(";"); } @@ -133,18 +132,18 @@ public class CLPDCapabilitiesGenerator { writer.println("\t}\n"); } - public static void generateToString(final PrintWriter writer, final Collection templates, final Class capsType) { + public static void generateToString(final PrintWriter writer, final Set templates, final Class capsType) { writer.println("\tpublic String toString() {"); writer.println("\t\tfinal StringBuilder buf = new StringBuilder();\n"); writer.println("\t\tbuf.append(\"OpenCL \").append(majorVersion).append('.').append(minorVersion);"); writer.println(); writer.println("\t\tbuf.append(\" - Extensions: \");"); - for ( final TypeDeclaration t : templates ) { + for ( final TypeElement t : templates ) { if ( t.getAnnotation(capsType) == null ) continue; - writer.println("\t\tif ( " + CLGeneratorProcessorFactory.getExtensionName(t.getSimpleName()) + " ) buf.append(\"" + CLGeneratorProcessorFactory.getExtensionName(t.getSimpleName()).toLowerCase() + " \");"); + writer.println("\t\tif ( " + CLGeneratorProcessor.getExtensionName(t.getSimpleName().toString()) + " ) buf.append(\"" + CLGeneratorProcessor.getExtensionName(t.getSimpleName().toString()).toLowerCase() + " \");"); } writer.println("\n\t\treturn buf.toString();"); diff --git a/src/java/org/lwjgl/util/generator/opencl/CLTypeMap.java b/src/java/org/lwjgl/util/generator/opencl/CLTypeMap.java index 9b6433ac..ba4b3153 100644 --- a/src/java/org/lwjgl/util/generator/opencl/CLTypeMap.java +++ b/src/java/org/lwjgl/util/generator/opencl/CLTypeMap.java @@ -39,61 +39,65 @@ package org.lwjgl.util.generator.opencl; * @author Spasi */ -import org.lwjgl.PointerBuffer; -import org.lwjgl.util.generator.*; -import org.lwjgl.util.generator.opengl.GLreturn; - import java.io.PrintWriter; import java.lang.annotation.Annotation; import java.nio.*; import java.util.HashMap; import java.util.Map; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeKind; +import org.lwjgl.PointerBuffer; +import org.lwjgl.util.generator.*; +import org.lwjgl.util.generator.opengl.GLreturn; -import com.sun.mirror.declaration.AnnotationMirror; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.declaration.ParameterDeclaration; -import com.sun.mirror.type.PrimitiveType; public class CLTypeMap implements TypeMap { - private static final Map native_types_to_primitive; + private static final Map native_types_to_primitive; static { - native_types_to_primitive = new HashMap(); - native_types_to_primitive.put(cl_void.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(cl_byte.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(cl_char.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(cl_uchar.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(cl_short.class, PrimitiveType.Kind.SHORT); - native_types_to_primitive.put(cl_bool.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(cl_int.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(cl_uint.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(cl_long.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(size_t.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(cl_bitfield.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(cl_float.class, PrimitiveType.Kind.FLOAT); - native_types_to_primitive.put(cl_double.class, PrimitiveType.Kind.DOUBLE); + native_types_to_primitive = new HashMap<>(); + native_types_to_primitive.put(cl_void.class, TypeKind.BYTE); + native_types_to_primitive.put(cl_byte.class, TypeKind.BYTE); + native_types_to_primitive.put(cl_char.class, TypeKind.BYTE); + native_types_to_primitive.put(cl_uchar.class, TypeKind.BYTE); + native_types_to_primitive.put(cl_short.class, TypeKind.SHORT); + native_types_to_primitive.put(cl_bool.class, TypeKind.INT); + native_types_to_primitive.put(cl_int.class, TypeKind.INT); + native_types_to_primitive.put(cl_uint.class, TypeKind.INT); + native_types_to_primitive.put(cl_long.class, TypeKind.LONG); + native_types_to_primitive.put(size_t.class, TypeKind.LONG); + native_types_to_primitive.put(cl_bitfield.class, TypeKind.LONG); + native_types_to_primitive.put(cl_float.class, TypeKind.FLOAT); + native_types_to_primitive.put(cl_double.class, TypeKind.DOUBLE); } - public PrimitiveType.Kind getPrimitiveTypeFromNativeType(Class native_type) { - PrimitiveType.Kind kind = native_types_to_primitive.get(native_type); + @Override + public TypeKind getPrimitiveTypeFromNativeType(Class native_type) { + TypeKind kind = native_types_to_primitive.get(native_type); if ( kind == null ) throw new RuntimeException("Unsupported type " + native_type); return kind; } + @Override public void printCapabilitiesInit(final PrintWriter writer) { } + @Override public String getCapabilities() { return "CLCapabilities"; } + @Override public String getAPIUtilParam(boolean comma) { return ""; } - public void printErrorCheckMethod(final PrintWriter writer, final MethodDeclaration method, final String tabs) { + @Override + public void printErrorCheckMethod(final PrintWriter writer, final ExecutableElement method, final String tabs) { final Check check = method.getAnnotation(Check.class); if ( check != null ) // Get the error code from an IntBuffer output parameter writer.println(tabs + "Util.checkCLError(" + check.value() + ".get(" + check.value() + ".position()));"); @@ -103,8 +107,8 @@ public class CLTypeMap implements TypeMap { writer.println(tabs + "Util.checkCLError(__result);"); else { boolean hasErrCodeParam = false; - for ( final ParameterDeclaration param : method.getParameters() ) { - if ( "errcode_ret".equals(param.getSimpleName()) && Utils.getJavaType(param.getType()) == IntBuffer.class ) { + for ( final VariableElement param : method.getParameters() ) { + if ( "errcode_ret".equals(param.getSimpleName().toString()) && Utils.getJavaType(param.asType()) == IntBuffer.class ) { hasErrCodeParam = true; break; } @@ -115,10 +119,12 @@ public class CLTypeMap implements TypeMap { } } + @Override public String getRegisterNativesFunctionName() { return "extcl_InitializeClass"; } + @Override public Signedness getSignednessFromType(Class type) { if ( cl_uint.class.equals(type) ) return Signedness.UNSIGNED; @@ -128,6 +134,7 @@ public class CLTypeMap implements TypeMap { return Signedness.NONE; } + @Override public String translateAnnotation(Class annotation_type) { if ( annotation_type.equals(cl_uint.class) || annotation_type.equals(cl_int.class) ) return "i"; @@ -143,7 +150,8 @@ public class CLTypeMap implements TypeMap { throw new RuntimeException(annotation_type + " is not allowed"); } - public Class getNativeTypeFromPrimitiveType(PrimitiveType.Kind kind) { + @Override + public Class getNativeTypeFromPrimitiveType(TypeKind kind) { Class type; switch ( kind ) { case INT: @@ -173,18 +181,22 @@ public class CLTypeMap implements TypeMap { return type; } + @Override public Class getVoidType() { return cl_void.class; } + @Override public Class getStringElementType() { return cl_char.class; } + @Override public Class getStringArrayType() { return cl_char.class; } + @Override public Class getByteBufferArrayType() { return cl_uchar.class; } @@ -229,18 +241,22 @@ public class CLTypeMap implements TypeMap { return new Class[] { }; } + @Override public String getTypedefPostfix() { return "CL_API_ENTRY "; } + @Override public String getFunctionPrefix() { return "CL_API_CALL"; } + @Override public void printNativeIncludes(PrintWriter writer) { writer.println("#include \"extcl.h\""); } + @Override public Class[] getValidAnnotationTypes(Class type) { Class[] valid_types; if ( Buffer.class.isAssignableFrom(type) || PointerBuffer.class.isAssignableFrom(type) ) @@ -260,10 +276,12 @@ public class CLTypeMap implements TypeMap { return valid_types; } + @Override public Class getInverseType(Class type) { return null; } + @Override public String getAutoTypeFromAnnotation(AnnotationMirror annotation) { return null; } diff --git a/src/java/org/lwjgl/util/generator/opencl/cl_void.java b/src/java/org/lwjgl/util/generator/opencl/cl_void.java index 6cf56311..e102cf4d 100644 --- a/src/java/org/lwjgl/util/generator/opencl/cl_void.java +++ b/src/java/org/lwjgl/util/generator/opencl/cl_void.java @@ -35,11 +35,10 @@ import org.lwjgl.util.generator.NativeType; import java.lang.annotation.ElementType; import java.lang.annotation.Target; - -import com.sun.mirror.type.PrimitiveType; +import javax.lang.model.type.TypeKind; @NativeType @Target({ ElementType.PARAMETER, ElementType.METHOD }) public @interface cl_void { - PrimitiveType.Kind value() default PrimitiveType.Kind.BYTE; + TypeKind value() default TypeKind.BYTE; } \ No newline at end of file diff --git a/src/java/org/lwjgl/util/generator/opengl/GLCapabilitiesGenerator.java b/src/java/org/lwjgl/util/generator/opengl/GLCapabilitiesGenerator.java index b15a4ddf..9c1ba618 100644 --- a/src/java/org/lwjgl/util/generator/opengl/GLCapabilitiesGenerator.java +++ b/src/java/org/lwjgl/util/generator/opengl/GLCapabilitiesGenerator.java @@ -32,17 +32,19 @@ package org.lwjgl.util.generator.opengl; -import org.lwjgl.util.generator.*; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.Iterator; - -import com.sun.mirror.declaration.InterfaceDeclaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.type.InterfaceType; +import java.util.List; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.TypeMirror; +import org.lwjgl.util.generator.*; /** * Generator visitor for the context capabilities generator tool @@ -84,32 +86,32 @@ public class GLCapabilitiesGenerator { return EXTENSION_PREFIX + interface_name; } - public static void generateSuperClassAdds(PrintWriter writer, InterfaceDeclaration d) { - Collection super_interfaces = d.getSuperinterfaces(); + public static void generateSuperClassAdds(PrintWriter writer, TypeElement d, ProcessingEnvironment env) { + List super_interfaces = d.getInterfaces(); if ( super_interfaces.size() > 1 ) throw new RuntimeException(d + " extends more than one other interface"); if ( super_interfaces.size() == 1 ) { - InterfaceType super_interface = super_interfaces.iterator().next(); + TypeMirror super_interface = super_interfaces.iterator().next(); writer.print("\t\tif (" + CACHED_EXTS_VAR_NAME + ".contains(\""); - writer.println(translateFieldName(d.getSimpleName()) + "\"))"); + writer.println(translateFieldName(d.getSimpleName().toString()) + "\"))"); writer.print("\t\t\t"); - generateAddExtension(writer, super_interface.getDeclaration()); + generateAddExtension(writer, env.getElementUtils().getTypeElement(super_interface.toString())); } } - public static void generateInitializer(PrintWriter writer, InterfaceDeclaration d) { - String translated_field_name = translateFieldName(d.getSimpleName()); + public static void generateInitializer(PrintWriter writer, TypeElement d, ProcessingEnvironment env) { + String translated_field_name = translateFieldName(d.getSimpleName().toString()); writer.print("\t\tthis." + translated_field_name + " = "); writer.print(CACHED_EXTS_VAR_NAME + ".contains(\""); writer.print(translated_field_name + "\")"); - Collection super_interfaces = d.getSuperinterfaces(); - if ( super_interfaces.size() > 1 ) + List super_interfaces = d.getInterfaces(); + if ( super_interfaces.size() > 1 ) throw new RuntimeException(d + " extends more than one other interface"); if ( super_interfaces.size() == 1 ) { - InterfaceType super_interface = super_interfaces.iterator().next(); + TypeMirror super_interface = super_interfaces.iterator().next(); writer.println(); writer.print("\t\t\t&& " + CACHED_EXTS_VAR_NAME + ".contains(\""); - writer.print(translateFieldName(super_interface.getDeclaration().getSimpleName()) + "\")"); + writer.print(translateFieldName(env.getElementUtils().getTypeElement(super_interface.toString()).getSimpleName().toString()) + "\")"); } Alias alias_annotation = d.getAnnotation(Alias.class); if ( alias_annotation != null ) { @@ -163,30 +165,30 @@ public class GLCapabilitiesGenerator { writer.println("\t}"); } - public static void generateUnloadStubs(PrintWriter writer, InterfaceDeclaration d) { - if ( d.getMethods().size() > 0 ) { + public static void generateUnloadStubs(ProcessingEnvironment env, PrintWriter writer, TypeElement d) { + if ( Utils.getMethods( d).size() > 0 ) { writer.print("\t\tGLContext.resetNativeStubs(" + Utils.getSimpleClassName(d)); writer.println(".class);"); } } - public static void generateInitStubs(PrintWriter writer, InterfaceDeclaration d, boolean context_specific) { - if ( d.getMethods().size() > 0 ) { + public static void generateInitStubs(ProcessingEnvironment env, PrintWriter writer, TypeElement d, boolean context_specific) { + if ( Utils.getMethods( d).size() > 0 ) { if ( context_specific ) { final Alias alias_annotation = d.getAnnotation(Alias.class); if ( d.getAnnotation(ForceInit.class) != null ) - writer.println("\t\t" + CACHED_EXTS_VAR_NAME + ".add(\"" + translateFieldName(d.getSimpleName()) + "\");"); + writer.println("\t\t" + CACHED_EXTS_VAR_NAME + ".add(\"" + translateFieldName(d.getSimpleName().toString()) + "\");"); writer.print("\t\tif ("); if ( alias_annotation != null ) writer.print("("); writer.print(CACHED_EXTS_VAR_NAME + ".contains(\""); - writer.print(translateFieldName(d.getSimpleName()) + "\")"); + writer.print(translateFieldName(d.getSimpleName().toString()) + "\")"); if ( alias_annotation != null ) { writer.print(" || " + CACHED_EXTS_VAR_NAME + ".contains(\""); writer.print(translateFieldName(alias_annotation.value()) + "\"))"); } - writer.print(" && !" + getAddressesInitializerName(d.getSimpleName()) + "("); + writer.print(" && !" + getAddressesInitializerName(d.getSimpleName().toString()) + "("); if ( d.getAnnotation(DeprecatedGL.class) != null ) writer.print("forwardCompatible"); if ( d.getAnnotation(Dependent.class) != null ) { @@ -201,27 +203,27 @@ public class GLCapabilitiesGenerator { } else writer.println("))"); writer.print("\t\t\tremove(" + CACHED_EXTS_VAR_NAME + ", \""); - writer.println(translateFieldName(d.getSimpleName()) + "\");"); + writer.println(translateFieldName(d.getSimpleName().toString()) + "\");"); if ( alias_annotation != null ) writer.println("\t\t}"); } else { writer.print("\t\tGLContext." + Utils.STUB_INITIALIZER_NAME + "(" + Utils.getSimpleClassName(d)); - writer.println(".class, " + CACHED_EXTS_VAR_NAME + ", \"" + translateFieldName(d.getSimpleName()) + "\");"); + writer.println(".class, " + CACHED_EXTS_VAR_NAME + ", \"" + translateFieldName(d.getSimpleName().toString()) + "\");"); } } } - private static void generateAddExtension(PrintWriter writer, InterfaceDeclaration d) { + private static void generateAddExtension(PrintWriter writer, TypeElement d) { writer.print(CACHED_EXTS_VAR_NAME + ".add(\""); - writer.println(translateFieldName(d.getSimpleName()) + "\");"); + writer.println(translateFieldName(d.getSimpleName().toString()) + "\");"); } - public static void generateAddressesInitializers(PrintWriter writer, InterfaceDeclaration d) { - Iterator methods = d.getMethods().iterator(); + public static void generateAddressesInitializers(ProcessingEnvironment env, PrintWriter writer, TypeElement d) { + Iterator methods = Utils.getMethods( d).iterator(); if ( !methods.hasNext() ) return; - writer.print("\tprivate boolean " + getAddressesInitializerName(d.getSimpleName()) + "("); + writer.print("\tprivate boolean " + getAddressesInitializerName(d.getSimpleName().toString()) + "("); boolean optional; boolean deprecated = d.getAnnotation(DeprecatedGL.class) != null; @@ -242,7 +244,7 @@ public class GLCapabilitiesGenerator { boolean first = true; while ( methods.hasNext() ) { - MethodDeclaration method = methods.next(); + ExecutableElement method = methods.next(); if ( method.getAnnotation(Alternate.class) != null ) continue; @@ -309,9 +311,9 @@ public class GLCapabilitiesGenerator { writer.println(); } - public static void generateSymbolAddresses(PrintWriter writer, InterfaceDeclaration d) { + public static void generateSymbolAddresses(ProcessingEnvironment env, PrintWriter writer, TypeElement d) { boolean first = true; - for ( final MethodDeclaration method : d.getMethods() ) { + for ( final ExecutableElement method : Utils.getMethods( d) ) { if ( method.getAnnotation(Alternate.class) != null || method.getAnnotation(Reuse.class) != null ) continue; @@ -323,7 +325,7 @@ public class GLCapabilitiesGenerator { } } - public static void generateField(PrintWriter writer, InterfaceDeclaration d) { - writer.println("\tpublic final boolean " + translateFieldName(d.getSimpleName()) + ";"); + public static void generateField(PrintWriter writer, TypeElement d) { + writer.println("\tpublic final boolean " + translateFieldName(d.getSimpleName().toString()) + ";"); } } \ No newline at end of file diff --git a/src/java/org/lwjgl/util/generator/opengl/GLESCapabilitiesGenerator.java b/src/java/org/lwjgl/util/generator/opengl/GLESCapabilitiesGenerator.java index 06d5e9a3..633b083e 100644 --- a/src/java/org/lwjgl/util/generator/opengl/GLESCapabilitiesGenerator.java +++ b/src/java/org/lwjgl/util/generator/opengl/GLESCapabilitiesGenerator.java @@ -32,17 +32,18 @@ package org.lwjgl.util.generator.opengl; -import org.lwjgl.util.generator.*; import java.io.PrintWriter; import java.util.Arrays; -import java.util.Collection; import java.util.EnumSet; import java.util.Iterator; - -import com.sun.mirror.declaration.InterfaceDeclaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.type.InterfaceType; +import java.util.List; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.TypeMirror; +import org.lwjgl.util.generator.*; /** * Generator visitor for the context capabilities generator tool @@ -81,32 +82,32 @@ public class GLESCapabilitiesGenerator { return EXTENSION_PREFIX + interface_name; } - public static void generateSuperClassAdds(PrintWriter writer, InterfaceDeclaration d) { - Collection super_interfaces = d.getSuperinterfaces(); + public static void generateSuperClassAdds(PrintWriter writer, TypeElement d, ProcessingEnvironment env) { + List super_interfaces = d.getInterfaces(); if ( super_interfaces.size() > 1 ) throw new RuntimeException(d + " extends more than one other interface"); if ( super_interfaces.size() == 1 ) { - InterfaceType super_interface = super_interfaces.iterator().next(); + TypeMirror super_interface = super_interfaces.iterator().next(); writer.print("\t\tif (" + CACHED_EXTS_VAR_NAME + ".contains(\""); - writer.println(translateFieldName(d.getSimpleName()) + "\"))"); + writer.println(translateFieldName(d.getSimpleName().toString() + "\"))")); writer.print("\t\t\t"); - generateAddExtension(writer, super_interface.getDeclaration()); + generateAddExtension(writer, env.getElementUtils().getTypeElement(super_interface.toString())); } } - public static void generateInitializer(PrintWriter writer, InterfaceDeclaration d) { - String translated_field_name = translateFieldName(d.getSimpleName()); + public static void generateInitializer(PrintWriter writer, TypeElement d,ProcessingEnvironment env) { + String translated_field_name = translateFieldName(d.getSimpleName().toString()); writer.print("\t\tthis." + translated_field_name + " = "); writer.print(CACHED_EXTS_VAR_NAME + ".contains(\""); writer.print(translated_field_name + "\")"); - Collection super_interfaces = d.getSuperinterfaces(); + List super_interfaces = d.getInterfaces(); if ( super_interfaces.size() > 1 ) throw new RuntimeException(d + " extends more than one other interface"); if ( super_interfaces.size() == 1 ) { - InterfaceType super_interface = super_interfaces.iterator().next(); + TypeMirror super_interface = super_interfaces.iterator().next(); writer.println(); writer.print("\t\t\t&& " + CACHED_EXTS_VAR_NAME + ".contains(\""); - writer.print(translateFieldName(super_interface.getDeclaration().getSimpleName()) + "\")"); + writer.print(translateFieldName(env.getElementUtils().getTypeElement(super_interface.toString()).getSimpleName() + "\")")); } Alias alias_annotation = d.getAnnotation(Alias.class); if ( alias_annotation != null ) { @@ -153,31 +154,31 @@ public class GLESCapabilitiesGenerator { writer.println("\t}"); } - public static void generateUnloadStubs(PrintWriter writer, InterfaceDeclaration d) { + public static void generateUnloadStubs(ProcessingEnvironment env, PrintWriter writer, TypeElement d) { // TODO: Remove GLES - if ( d.getMethods().size() > 0 && !d.getSimpleName().startsWith("GLES") ) { + if (Utils.getMethods( d).size() > 0 && !d.getSimpleName().toString().startsWith("GLES") ) { writer.print("\t\tGLContext.resetNativeStubs(" + Utils.getSimpleClassName(d)); writer.println(".class);"); } } - public static void generateInitStubs(PrintWriter writer, InterfaceDeclaration d, boolean context_specific) { - if ( d.getMethods().size() > 0 ) { + public static void generateInitStubs(ProcessingEnvironment env, PrintWriter writer, TypeElement d, boolean context_specific) { + if ( Utils.getMethods( d).size() > 0 ) { if ( context_specific ) { final Alias alias_annotation = d.getAnnotation(Alias.class); if ( d.getAnnotation(ForceInit.class) != null ) - writer.println("\t\t" + CACHED_EXTS_VAR_NAME + ".add(\"" + translateFieldName(d.getSimpleName()) + "\");"); + writer.println("\t\t" + CACHED_EXTS_VAR_NAME + ".add(\"" + translateFieldName(d.getSimpleName().toString()) + "\");"); writer.print("\t\tif ("); if ( alias_annotation != null ) writer.print("("); writer.print(CACHED_EXTS_VAR_NAME + ".contains(\""); - writer.print(translateFieldName(d.getSimpleName()) + "\")"); + writer.print(translateFieldName(d.getSimpleName().toString()) + "\")"); if ( alias_annotation != null ) { writer.print(" || " + CACHED_EXTS_VAR_NAME + ".contains(\""); writer.print(translateFieldName(alias_annotation.value()) + "\"))"); } - writer.print(" && !" + getAddressesInitializerName(d.getSimpleName()) + "("); + writer.print(" && !" + getAddressesInitializerName(d.getSimpleName().toString()) + "("); if ( d.getAnnotation(Dependent.class) != null ) writer.print("supported_extensions"); if ( alias_annotation != null ) { @@ -187,27 +188,27 @@ public class GLESCapabilitiesGenerator { } else writer.println("))"); writer.print("\t\t\tremove(" + CACHED_EXTS_VAR_NAME + ", \""); - writer.println(translateFieldName(d.getSimpleName()) + "\");"); + writer.println(translateFieldName(d.getSimpleName().toString()) + "\");"); if ( alias_annotation != null ) writer.println("\t\t}"); } else { writer.print("\t\tGLContext." + Utils.STUB_INITIALIZER_NAME + "(" + Utils.getSimpleClassName(d)); - writer.println(".class, " + CACHED_EXTS_VAR_NAME + ", \"" + translateFieldName(d.getSimpleName()) + "\");"); + writer.println(".class, " + CACHED_EXTS_VAR_NAME + ", \"" + translateFieldName(d.getSimpleName().toString()) + "\");"); } } } - private static void generateAddExtension(PrintWriter writer, InterfaceDeclaration d) { + private static void generateAddExtension(PrintWriter writer, TypeElement d) { writer.print(CACHED_EXTS_VAR_NAME + ".add(\""); - writer.println(translateFieldName(d.getSimpleName()) + "\");"); + writer.println(translateFieldName(d.getSimpleName().toString()) + "\");"); } - public static void generateAddressesInitializers(PrintWriter writer, InterfaceDeclaration d) { - Iterator methods = d.getMethods().iterator(); + public static void generateAddressesInitializers(ProcessingEnvironment env, PrintWriter writer, TypeElement d) { + Iterator methods = Utils.getMethods( d).iterator(); if ( !methods.hasNext() ) return; - writer.print("\tprivate boolean " + getAddressesInitializerName(d.getSimpleName()) + "("); + writer.print("\tprivate boolean " + getAddressesInitializerName(d.getSimpleName().toString()) + "("); boolean optional; Dependent dependent = d.getAnnotation(Dependent.class); @@ -223,7 +224,7 @@ public class GLESCapabilitiesGenerator { boolean first = true; while ( methods.hasNext() ) { - MethodDeclaration method = methods.next(); + ExecutableElement method = methods.next(); if ( method.getAnnotation(Alternate.class) != null ) continue; @@ -287,9 +288,9 @@ public class GLESCapabilitiesGenerator { writer.println(); } - public static void generateSymbolAddresses(PrintWriter writer, InterfaceDeclaration d) { + public static void generateSymbolAddresses(ProcessingEnvironment env, PrintWriter writer, TypeElement d) { boolean first = true; - for ( final MethodDeclaration method : d.getMethods() ) { + for ( final ExecutableElement method : Utils.getMethods( d) ) { if ( method.getAnnotation(Alternate.class) != null || method.getAnnotation(Reuse.class) != null ) continue; @@ -301,8 +302,8 @@ public class GLESCapabilitiesGenerator { } } - public static void generateField(PrintWriter writer, InterfaceDeclaration d) { - writer.println("\tpublic final boolean " + translateFieldName(d.getSimpleName()) + ";"); + public static void generateField(PrintWriter writer, TypeElement d) { + writer.println("\tpublic final boolean " + translateFieldName(d.getSimpleName().toString()) + ";"); } } \ No newline at end of file diff --git a/src/java/org/lwjgl/util/generator/opengl/GLESGeneratorProcessor.java b/src/java/org/lwjgl/util/generator/opengl/GLESGeneratorProcessor.java new file mode 100644 index 00000000..062bf268 --- /dev/null +++ b/src/java/org/lwjgl/util/generator/opengl/GLESGeneratorProcessor.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjgl.util.generator.opengl; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Map; +import java.util.Set; +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.annotation.processing.SupportedOptions; +import javax.annotation.processing.SupportedSourceVersion; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.TypeElement; +import javax.lang.model.util.ElementFilter; +import org.lwjgl.util.generator.Utils; + +/** + * Generator tool for creating the ContexCapabilities class + * + * @author elias_naur + * @version $Revision: 3316 $ $Id: ContextGeneratorProcessorFactory.java 3316 + * 2010-04-09 23:57:40Z spasi $ + */ +@SupportedAnnotationTypes({"*"}) +@SupportedSourceVersion(SourceVersion.RELEASE_7) +@SupportedOptions({"contextspecific", "generatechecks"}) +public class GLESGeneratorProcessor extends AbstractProcessor { + + private static boolean first_round = true; + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + if (roundEnv.processingOver() || !first_round) { + System.exit(0); + return true; + } + Map options = processingEnv.getOptions(); + boolean generate_error_checks = options.containsKey("generatechecks"); + boolean context_specific = options.containsKey("contextspecific"); + try { + generateContextCapabilitiesSource(ElementFilter.typesIn(roundEnv.getRootElements()), context_specific, generate_error_checks); + first_round = false; + return true; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private void generateContextCapabilitiesSource(Set templates, boolean context_specific, boolean generate_error_checks) throws IOException { + PrintWriter writer = new PrintWriter(processingEnv.getFiler().createSourceFile("org.lwjgl.opengles." + Utils.CONTEXT_CAPS_CLASS_NAME, processingEnv.getElementUtils().getPackageElement("org.lwjgl.opengles")).openWriter()); + writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */"); + writer.println(); + writer.println("package org.lwjgl.opengles;"); + writer.println(); + writer.println("import org.lwjgl.LWJGLException;"); + writer.println("import org.lwjgl.LWJGLUtil;"); + writer.println("import java.util.Set;"); + writer.println("import java.util.HashSet;"); + writer.println(); + GLESCapabilitiesGenerator.generateClassPrologue(writer, context_specific, generate_error_checks); + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + if (Utils.isFinal(interface_decl)) { + GLESCapabilitiesGenerator.generateField(writer, interface_decl); + } + } + } + writer.println(); + if (context_specific) { + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + GLESCapabilitiesGenerator.generateSymbolAddresses(processingEnv, writer, interface_decl); + } + } + writer.println(); + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + GLESCapabilitiesGenerator.generateAddressesInitializers(processingEnv, writer, interface_decl); + } + } + writer.println(); + } + + if (context_specific) { + writer.println("\tprivate static void remove(Set supported_extensions, String extension) {"); + writer.println("\t\tLWJGLUtil.log(extension + \" was reported as available but an entry point is missing\");"); + writer.println("\t\tsupported_extensions.remove(extension);"); + writer.println("\t}\n"); + } + + GLESCapabilitiesGenerator.generateInitStubsPrologue(writer, context_specific); + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + GLESCapabilitiesGenerator.generateSuperClassAdds(writer, interface_decl, processingEnv); + } + } + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + if ("GLES20".equals(interface_decl.getSimpleName().toString())) { + continue; + } + GLESCapabilitiesGenerator.generateInitStubs(processingEnv, writer, interface_decl, context_specific); + } + } + GLESCapabilitiesGenerator.generateInitStubsEpilogue(writer, context_specific); + writer.println(); + writer.println("\tstatic void unloadAllStubs() {"); + if (!context_specific) { + writer.println("\t\tif (!loaded_stubs)"); + writer.println("\t\t\treturn;"); + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + GLESCapabilitiesGenerator.generateUnloadStubs(processingEnv, writer, interface_decl); + } + } + writer.println("\t\tloaded_stubs = false;"); + } + writer.println("\t}"); + writer.println(); + GLESCapabilitiesGenerator.generateInitializerPrologue(writer); + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + if (Utils.isFinal(interface_decl)) { + GLESCapabilitiesGenerator.generateInitializer(writer, interface_decl, processingEnv); + } + } + } + writer.println("\t}"); + writer.println("}"); + writer.close(); + } + +} diff --git a/src/java/org/lwjgl/util/generator/opengl/GLESGeneratorProcessorFactory.java b/src/java/org/lwjgl/util/generator/opengl/GLESGeneratorProcessorFactory.java deleted file mode 100644 index 2c2c730e..00000000 --- a/src/java/org/lwjgl/util/generator/opengl/GLESGeneratorProcessorFactory.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (c) 2002-2008 LWJGL Project - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'LWJGL' nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package org.lwjgl.util.generator.opengl; - -import org.lwjgl.util.generator.Utils; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Arrays; -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -import com.sun.mirror.apt.*; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.InterfaceDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.util.DeclarationFilter; - -import static java.util.Collections.*; - -/** - * Generator tool for creating the ContexCapabilities class - * - * @author elias_naur - * @version $Revision: 3316 $ - * $Id: ContextGeneratorProcessorFactory.java 3316 2010-04-09 23:57:40Z spasi $ - */ -public class GLESGeneratorProcessorFactory implements AnnotationProcessorFactory, RoundCompleteListener { - - private static boolean first_round = true; - - // Process any set of annotations - private static final Collection supportedAnnotations = - unmodifiableCollection(Arrays.asList("*")); - - public Collection supportedAnnotationTypes() { - return supportedAnnotations; - } - - public Collection supportedOptions() { - return unmodifiableCollection(Arrays.asList("-Acontextspecific", "-Ageneratechecks")); - } - - public void roundComplete(RoundCompleteEvent event) { - first_round = false; - } - - public AnnotationProcessor getProcessorFor(Set atds, AnnotationProcessorEnvironment env) { - // Only process the initial types, not the generated ones - if ( first_round ) { - env.addListener(this); - return new GeneratorProcessor(env); - } else - return AnnotationProcessors.NO_OP; - } - - private static class GeneratorProcessor implements AnnotationProcessor { - - private final AnnotationProcessorEnvironment env; - - GeneratorProcessor(AnnotationProcessorEnvironment env) { - this.env = env; - } - - public void process() { - Map options = env.getOptions(); - boolean generate_error_checks = options.containsKey("-Ageneratechecks"); - boolean context_specific = options.containsKey("-Acontextspecific"); - try { - generateContextCapabilitiesSource(context_specific, generate_error_checks); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private void generateContextCapabilitiesSource(boolean context_specific, boolean generate_error_checks) throws IOException { - PrintWriter writer = env.getFiler().createTextFile(Filer.Location.SOURCE_TREE, "org.lwjgl.opengles", new File(Utils.CONTEXT_CAPS_CLASS_NAME + ".java"), null); - writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */"); - writer.println(); - writer.println("package org.lwjgl.opengles;"); - writer.println(); - writer.println("import org.lwjgl.LWJGLException;"); - writer.println("import org.lwjgl.LWJGLUtil;"); - writer.println("import java.util.Set;"); - writer.println("import java.util.HashSet;"); - writer.println(); - GLESCapabilitiesGenerator.generateClassPrologue(writer, context_specific, generate_error_checks); - DeclarationFilter filter = DeclarationFilter.getFilter(InterfaceDeclaration.class); - Collection interface_decls = filter.filter(env.getSpecifiedTypeDeclarations()); - for ( TypeDeclaration typedecl : interface_decls ) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - if ( Utils.isFinal(interface_decl) ) - GLESCapabilitiesGenerator.generateField(writer, interface_decl); - } - writer.println(); - if ( context_specific ) { - for ( TypeDeclaration typedecl : interface_decls ) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - GLESCapabilitiesGenerator.generateSymbolAddresses(writer, interface_decl); - } - writer.println(); - for ( TypeDeclaration typedecl : interface_decls ) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - GLESCapabilitiesGenerator.generateAddressesInitializers(writer, interface_decl); - } - writer.println(); - } - - if ( context_specific ) { - writer.println("\tprivate static void remove(Set supported_extensions, String extension) {"); - writer.println("\t\tLWJGLUtil.log(extension + \" was reported as available but an entry point is missing\");"); - writer.println("\t\tsupported_extensions.remove(extension);"); - writer.println("\t}\n"); - } - - GLESCapabilitiesGenerator.generateInitStubsPrologue(writer, context_specific); - for ( TypeDeclaration typedecl : interface_decls ) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - GLESCapabilitiesGenerator.generateSuperClassAdds(writer, interface_decl); - } - for ( TypeDeclaration typedecl : interface_decls ) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - if ( "GLES20".equals(interface_decl.getSimpleName()) ) - continue; - GLESCapabilitiesGenerator.generateInitStubs(writer, interface_decl, context_specific); - } - GLESCapabilitiesGenerator.generateInitStubsEpilogue(writer, context_specific); - writer.println(); - writer.println("\tstatic void unloadAllStubs() {"); - if ( !context_specific ) { - writer.println("\t\tif (!loaded_stubs)"); - writer.println("\t\t\treturn;"); - for ( TypeDeclaration typedecl : interface_decls ) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - GLESCapabilitiesGenerator.generateUnloadStubs(writer, interface_decl); - } - writer.println("\t\tloaded_stubs = false;"); - } - writer.println("\t}"); - writer.println(); - GLESCapabilitiesGenerator.generateInitializerPrologue(writer); - for ( TypeDeclaration typedecl : interface_decls ) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - if ( Utils.isFinal(interface_decl) ) - GLESCapabilitiesGenerator.generateInitializer(writer, interface_decl); - } - writer.println("\t}"); - writer.println("}"); - writer.close(); - } - } -} diff --git a/src/java/org/lwjgl/util/generator/opengl/GLESTypeMap.java b/src/java/org/lwjgl/util/generator/opengl/GLESTypeMap.java index 3383da57..0db02658 100644 --- a/src/java/org/lwjgl/util/generator/opengl/GLESTypeMap.java +++ b/src/java/org/lwjgl/util/generator/opengl/GLESTypeMap.java @@ -41,77 +41,82 @@ package org.lwjgl.util.generator.opengl; * $Id: GLTypeMap.java 3287 2010-03-14 23:24:40Z spasi $ */ -import org.lwjgl.util.generator.NativeTypeTranslator; -import org.lwjgl.util.generator.PointerWrapper; -import org.lwjgl.util.generator.Signedness; -import org.lwjgl.util.generator.TypeMap; - import java.io.PrintWriter; import java.lang.annotation.Annotation; import java.nio.*; import java.util.HashMap; import java.util.Map; - -import com.sun.mirror.declaration.AnnotationMirror; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.type.PrimitiveType; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.type.TypeKind; +import org.lwjgl.util.generator.NativeTypeTranslator; +import org.lwjgl.util.generator.PointerWrapper; +import org.lwjgl.util.generator.Signedness; +import org.lwjgl.util.generator.TypeMap; public class GLESTypeMap implements TypeMap { - private static final Map, PrimitiveType.Kind> native_types_to_primitive; + private static final Map, TypeKind> native_types_to_primitive; static { - native_types_to_primitive = new HashMap, PrimitiveType.Kind>(); - native_types_to_primitive.put(GLbitfield.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(GLclampf.class, PrimitiveType.Kind.FLOAT); - native_types_to_primitive.put(GLfloat.class, PrimitiveType.Kind.FLOAT); - native_types_to_primitive.put(GLint.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(GLshort.class, PrimitiveType.Kind.SHORT); - native_types_to_primitive.put(GLsizeiptr.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(GLuint.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(GLboolean.class, PrimitiveType.Kind.BOOLEAN); - native_types_to_primitive.put(GLchar.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(GLhalf.class, PrimitiveType.Kind.SHORT); - native_types_to_primitive.put(GLsizei.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(GLushort.class, PrimitiveType.Kind.SHORT); - native_types_to_primitive.put(GLbyte.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(GLenum.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(GLintptr.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(GLubyte.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(GLvoid.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(EGLint64NV.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(EGLuint64NV.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(GLint64.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(GLuint64.class, PrimitiveType.Kind.LONG); + native_types_to_primitive = new HashMap<>(); + native_types_to_primitive.put(GLbitfield.class, TypeKind.INT); + native_types_to_primitive.put(GLclampf.class, TypeKind.FLOAT); + native_types_to_primitive.put(GLfloat.class, TypeKind.FLOAT); + native_types_to_primitive.put(GLint.class, TypeKind.INT); + native_types_to_primitive.put(GLshort.class, TypeKind.SHORT); + native_types_to_primitive.put(GLsizeiptr.class, TypeKind.LONG); + native_types_to_primitive.put(GLuint.class, TypeKind.INT); + native_types_to_primitive.put(GLboolean.class, TypeKind.BOOLEAN); + native_types_to_primitive.put(GLchar.class, TypeKind.BYTE); + native_types_to_primitive.put(GLhalf.class, TypeKind.SHORT); + native_types_to_primitive.put(GLsizei.class, TypeKind.INT); + native_types_to_primitive.put(GLushort.class, TypeKind.SHORT); + native_types_to_primitive.put(GLbyte.class, TypeKind.BYTE); + native_types_to_primitive.put(GLenum.class, TypeKind.INT); + native_types_to_primitive.put(GLintptr.class, TypeKind.LONG); + native_types_to_primitive.put(GLubyte.class, TypeKind.BYTE); + native_types_to_primitive.put(GLvoid.class, TypeKind.BYTE); + native_types_to_primitive.put(EGLint64NV.class, TypeKind.LONG); + native_types_to_primitive.put(EGLuint64NV.class, TypeKind.LONG); + native_types_to_primitive.put(GLint64.class, TypeKind.LONG); + native_types_to_primitive.put(GLuint64.class, TypeKind.LONG); } - public PrimitiveType.Kind getPrimitiveTypeFromNativeType(Class native_type) { - PrimitiveType.Kind kind = native_types_to_primitive.get(native_type); + @Override + public TypeKind getPrimitiveTypeFromNativeType(Class native_type) { + TypeKind kind = native_types_to_primitive.get(native_type); if ( kind == null ) throw new RuntimeException("Unsupported type " + native_type); return kind; } + @Override public void printCapabilitiesInit(final PrintWriter writer) { writer.println("\t\tContextCapabilities caps = GLContext.getCapabilities();"); } + @Override public String getCapabilities() { return "caps"; } + @Override public String getAPIUtilParam(boolean comma) { return ""; } - public void printErrorCheckMethod(final PrintWriter writer, final MethodDeclaration method, final String tabs) { + @Override + public void printErrorCheckMethod(final PrintWriter writer, final ExecutableElement method, final String tabs) { writer.println(tabs + "Util.checkGLError();"); } + @Override public String getRegisterNativesFunctionName() { return "extgl_InitializeClass"; } + @Override public Signedness getSignednessFromType(Class type) { if ( GLuint.class.equals(type) ) return Signedness.UNSIGNED; @@ -133,6 +138,7 @@ public class GLESTypeMap implements TypeMap { return Signedness.NONE; } + @Override public String translateAnnotation(Class annotation_type) { if ( annotation_type.equals(GLuint64.class) || annotation_type.equals(GLint64.class) ) return "i64"; @@ -154,7 +160,8 @@ public class GLESTypeMap implements TypeMap { throw new RuntimeException(annotation_type + " is not allowed"); } - public Class getNativeTypeFromPrimitiveType(PrimitiveType.Kind kind) { + @Override + public Class getNativeTypeFromPrimitiveType(TypeKind kind) { Class type; switch ( kind ) { case INT: @@ -181,18 +188,22 @@ public class GLESTypeMap implements TypeMap { return type; } + @Override public Class getVoidType() { return GLvoid.class; } + @Override public Class getStringElementType() { return GLubyte.class; } + @Override public Class getStringArrayType() { return GLchar.class; } + @Override public Class getByteBufferArrayType() { return GLubyte.class; } @@ -231,18 +242,22 @@ public class GLESTypeMap implements TypeMap { return new Class[] { }; } + @Override public String getTypedefPostfix() { return "GL_APICALL "; } + @Override public String getFunctionPrefix() { return "GL_APIENTRY"; } + @Override public void printNativeIncludes(PrintWriter writer) { writer.println("#include \"extgl.h\""); } + @Override public Class[] getValidAnnotationTypes(Class type) { Class[] valid_types; if ( Buffer.class.isAssignableFrom(type) ) @@ -260,6 +275,7 @@ public class GLESTypeMap implements TypeMap { return valid_types; } + @Override public Class getInverseType(Class type) { if ( GLuint64.class.equals(type) ) return GLint64.class; @@ -279,6 +295,7 @@ public class GLESTypeMap implements TypeMap { return null; } + @Override public String getAutoTypeFromAnnotation(AnnotationMirror annotation) { Class annotation_class = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType()); if ( annotation_class.equals(GLint.class) ) diff --git a/src/java/org/lwjgl/util/generator/opengl/GLGeneratorProcessor.java b/src/java/org/lwjgl/util/generator/opengl/GLGeneratorProcessor.java new file mode 100644 index 00000000..8c036b63 --- /dev/null +++ b/src/java/org/lwjgl/util/generator/opengl/GLGeneratorProcessor.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjgl.util.generator.opengl; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Map; +import java.util.Set; +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.annotation.processing.SupportedOptions; +import javax.annotation.processing.SupportedSourceVersion; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.TypeElement; +import javax.lang.model.util.ElementFilter; +import org.lwjgl.util.generator.Utils; + +/** + * + * Generator tool for creating the ContexCapabilities class + * + * @author elias_naur + * @version $Revision: 3316 $ $Id: ContextGeneratorProcessorFactory.java 3316 + * 2010-04-09 23:57:40Z spasi $ + */ +@SupportedAnnotationTypes({"*"}) +@SupportedSourceVersion(SourceVersion.RELEASE_7) +@SupportedOptions({"generatechecks", "contextspecific"}) +public class GLGeneratorProcessor extends AbstractProcessor { + + private static boolean first_round = true; + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + if (roundEnv.processingOver() || !first_round) { + System.exit(0); + return true; + } + Map options = processingEnv.getOptions(); + boolean generate_error_checks = options.containsKey("generatechecks"); + boolean context_specific = options.containsKey("contextspecific"); + try { + generateContextCapabilitiesSource(ElementFilter.typesIn(roundEnv.getRootElements()), context_specific, generate_error_checks); + first_round = false; + return true; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private void generateContextCapabilitiesSource(Set templates, boolean context_specific, boolean generate_error_checks) throws IOException { + PrintWriter writer = new PrintWriter(processingEnv.getFiler().createSourceFile("org.lwjgl.opengl." + Utils.CONTEXT_CAPS_CLASS_NAME, processingEnv.getElementUtils().getPackageElement("org.lwjgl.opengl")).openWriter()); + writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */"); + writer.println(); + writer.println("package org.lwjgl.opengl;"); + writer.println(); + writer.println("import org.lwjgl.LWJGLException;"); + writer.println("import org.lwjgl.LWJGLUtil;"); + writer.println("import java.util.Set;"); + writer.println("import java.util.HashSet;"); + writer.println(); + GLCapabilitiesGenerator.generateClassPrologue(writer, context_specific, generate_error_checks); + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + if (Utils.isFinal(interface_decl)) { + GLCapabilitiesGenerator.generateField(writer, interface_decl); + } + } + } + writer.println(); + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + GLCapabilitiesGenerator.generateSymbolAddresses(processingEnv, writer, interface_decl); + } + } + writer.println(); + if (context_specific) { + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + GLCapabilitiesGenerator.generateAddressesInitializers(processingEnv, writer, interface_decl); + } + } + writer.println(); + } + + writer.println("\tprivate static void remove(Set supported_extensions, String extension) {"); + writer.println("\t\tLWJGLUtil.log(extension + \" was reported as available but an entry point is missing\");"); + writer.println("\t\tsupported_extensions.remove(extension);"); + writer.println("\t}\n"); + + GLCapabilitiesGenerator.generateInitStubsPrologue(writer, context_specific); + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + GLCapabilitiesGenerator.generateSuperClassAdds(writer, interface_decl, processingEnv); + } + } + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + String simple_name = interface_decl.getSimpleName().toString(); + if ("GL11".equals(simple_name)) { + continue; + } + GLCapabilitiesGenerator.generateInitStubs(processingEnv, writer, interface_decl, context_specific); + } + } + GLCapabilitiesGenerator.generateInitStubsEpilogue(writer, context_specific); + writer.println(); + writer.println("\tstatic void unloadAllStubs() {"); + if (!context_specific) { + writer.println("\t\tif (!loaded_stubs)"); + writer.println("\t\t\treturn;"); + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + GLCapabilitiesGenerator.generateUnloadStubs(processingEnv, writer, interface_decl); + } + } + writer.println("\t\tloaded_stubs = false;"); + } + writer.println("\t}"); + writer.println(); + GLCapabilitiesGenerator.generateInitializerPrologue(writer); + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + if (Utils.isFinal(interface_decl)) { + GLCapabilitiesGenerator.generateInitializer(writer, interface_decl, processingEnv); + } + } + } + writer.println("\t\ttracker.init();"); + writer.println("\t}"); + writer.println("}"); + writer.close(); + } +} diff --git a/src/java/org/lwjgl/util/generator/opengl/GLGeneratorProcessorFactory.java b/src/java/org/lwjgl/util/generator/opengl/GLGeneratorProcessorFactory.java deleted file mode 100644 index db50e48a..00000000 --- a/src/java/org/lwjgl/util/generator/opengl/GLGeneratorProcessorFactory.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (c) 2002-2008 LWJGL Project - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'LWJGL' nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package org.lwjgl.util.generator.opengl; - -import org.lwjgl.util.generator.Utils; - -import static java.util.Collections.unmodifiableCollection; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Arrays; -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -import com.sun.mirror.apt.AnnotationProcessor; -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.apt.AnnotationProcessorFactory; -import com.sun.mirror.apt.AnnotationProcessors; -import com.sun.mirror.apt.Filer; -import com.sun.mirror.apt.RoundCompleteEvent; -import com.sun.mirror.apt.RoundCompleteListener; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.InterfaceDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.util.DeclarationFilter; - -/** - * - * Generator tool for creating the ContexCapabilities class - * - * @author elias_naur - * @version $Revision: 3316 $ - * $Id: ContextGeneratorProcessorFactory.java 3316 2010-04-09 23:57:40Z spasi $ - */ -public class GLGeneratorProcessorFactory implements AnnotationProcessorFactory, RoundCompleteListener { - private static boolean first_round = true; - - // Process any set of annotations - private static final Collection supportedAnnotations = - unmodifiableCollection(Arrays.asList("*")); - - public Collection supportedAnnotationTypes() { - return supportedAnnotations; - } - - public Collection supportedOptions() { - return unmodifiableCollection(Arrays.asList("-Acontextspecific", "-Ageneratechecks")); - } - - public void roundComplete(RoundCompleteEvent event) { - first_round = false; - } - - public AnnotationProcessor getProcessorFor(Set atds, AnnotationProcessorEnvironment env) { - // Only process the initial types, not the generated ones - if (first_round) { - env.addListener(this); - return new GeneratorProcessor(env); - } else - return AnnotationProcessors.NO_OP; - } - - private static class GeneratorProcessor implements AnnotationProcessor { - private final AnnotationProcessorEnvironment env; - - GeneratorProcessor(AnnotationProcessorEnvironment env) { - this.env = env; - } - - public void process() { - Map options = env.getOptions(); - boolean generate_error_checks = options.containsKey("-Ageneratechecks"); - boolean context_specific = options.containsKey("-Acontextspecific"); - try { - generateContextCapabilitiesSource(context_specific, generate_error_checks); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private void generateContextCapabilitiesSource(boolean context_specific, boolean generate_error_checks) throws IOException { - PrintWriter writer = env.getFiler().createTextFile(Filer.Location.SOURCE_TREE, "org.lwjgl.opengl", new File(Utils.CONTEXT_CAPS_CLASS_NAME + ".java"), null); - writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */"); - writer.println(); - writer.println("package org.lwjgl.opengl;"); - writer.println(); - writer.println("import org.lwjgl.LWJGLException;"); - writer.println("import org.lwjgl.LWJGLUtil;"); - writer.println("import java.util.Set;"); - writer.println("import java.util.HashSet;"); - writer.println(); - GLCapabilitiesGenerator.generateClassPrologue(writer, context_specific, generate_error_checks); - DeclarationFilter filter = DeclarationFilter.getFilter(InterfaceDeclaration.class); - Collection interface_decls = filter.filter(env.getSpecifiedTypeDeclarations()); - for (TypeDeclaration typedecl : interface_decls) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - if (Utils.isFinal(interface_decl)) - GLCapabilitiesGenerator.generateField(writer, interface_decl); - } - writer.println(); - for (TypeDeclaration typedecl : interface_decls) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - GLCapabilitiesGenerator.generateSymbolAddresses(writer, interface_decl); - } - writer.println(); - if (context_specific) { - for (TypeDeclaration typedecl : interface_decls) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - GLCapabilitiesGenerator.generateAddressesInitializers(writer, interface_decl); - } - writer.println(); - } - - writer.println("\tprivate static void remove(Set supported_extensions, String extension) {"); - writer.println("\t\tLWJGLUtil.log(extension + \" was reported as available but an entry point is missing\");"); - writer.println("\t\tsupported_extensions.remove(extension);"); - writer.println("\t}\n"); - - GLCapabilitiesGenerator.generateInitStubsPrologue(writer, context_specific); - for (TypeDeclaration typedecl : interface_decls) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - GLCapabilitiesGenerator.generateSuperClassAdds(writer, interface_decl); - } - for (TypeDeclaration typedecl : interface_decls) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - String simple_name = interface_decl.getSimpleName(); - if ( "GL11".equals(simple_name) ) - continue; - GLCapabilitiesGenerator.generateInitStubs(writer, interface_decl, context_specific); - } - GLCapabilitiesGenerator.generateInitStubsEpilogue(writer, context_specific); - writer.println(); - writer.println("\tstatic void unloadAllStubs() {"); - if (!context_specific) { - writer.println("\t\tif (!loaded_stubs)"); - writer.println("\t\t\treturn;"); - for (TypeDeclaration typedecl : interface_decls) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - GLCapabilitiesGenerator.generateUnloadStubs(writer, interface_decl); - } - writer.println("\t\tloaded_stubs = false;"); - } - writer.println("\t}"); - writer.println(); - GLCapabilitiesGenerator.generateInitializerPrologue(writer); - for (TypeDeclaration typedecl : interface_decls) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - if (Utils.isFinal(interface_decl)) - GLCapabilitiesGenerator.generateInitializer(writer, interface_decl); - } - writer.println("\t\ttracker.init();"); - writer.println("\t}"); - writer.println("}"); - writer.close(); - } - } -} diff --git a/src/java/org/lwjgl/util/generator/opengl/GLReferencesGeneratorProcessor.java b/src/java/org/lwjgl/util/generator/opengl/GLReferencesGeneratorProcessor.java new file mode 100644 index 00000000..6ef0d2a5 --- /dev/null +++ b/src/java/org/lwjgl/util/generator/opengl/GLReferencesGeneratorProcessor.java @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2002-2008 LWJGL Project + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'LWJGL' nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.lwjgl.util.generator.opengl; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Set; +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.ProcessingEnvironment; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.annotation.processing.SupportedOptions; +import javax.annotation.processing.SupportedSourceVersion; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.util.ElementFilter; +import org.lwjgl.util.generator.Alternate; +import org.lwjgl.util.generator.CachedReference; +import org.lwjgl.util.generator.Utils; + +/** + * + * Generator tool for creating the References class + * + * @author elias_naur + * @version $Revision: 3237 $ $Id: ReferencesGeneratorProcessorFactory.java 3237 + * 2009-09-08 15:07:15Z spasi $ + */ +@SupportedAnnotationTypes({"*"}) +@SupportedSourceVersion(SourceVersion.RELEASE_7) +@SupportedOptions({"generatechecks", "contextspecific"}) +public class GLReferencesGeneratorProcessor extends AbstractProcessor { + + private static final String REFERENCES_CLASS_NAME = "References"; + private static final String REFERENCES_PARAMETER_NAME = "references"; + + private static boolean first_round = true; + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + if (roundEnv.processingOver() || !first_round) { + System.exit(0); + return true; + } + try { + generateReferencesSource(processingEnv, ElementFilter.typesIn(roundEnv.getRootElements())); + first_round = false; + return true; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static void generateClearsFromParameters(PrintWriter writer, TypeElement interface_decl, ExecutableElement method) { + for (VariableElement param : method.getParameters()) { + CachedReference cached_reference_annotation = param.getAnnotation(CachedReference.class); + if (cached_reference_annotation != null && cached_reference_annotation.name().length() == 0) { + Class nio_type = Utils.getNIOBufferType(param.asType()); + String reference_name = Utils.getReferenceName(interface_decl, method, param); + writer.println("\t\tthis." + reference_name + " = null;"); + } + } + } + + private static void generateCopiesFromParameters(PrintWriter writer, TypeElement interface_decl, ExecutableElement method) { + for (VariableElement param : method.getParameters()) { + CachedReference cached_reference_annotation = param.getAnnotation(CachedReference.class); + if (cached_reference_annotation != null && cached_reference_annotation.name().length() == 0) { + Class nio_type = Utils.getNIOBufferType(param.asType()); + String reference_name = Utils.getReferenceName(interface_decl, method, param); + writer.print("\t\t\tthis." + reference_name + " = "); + writer.println(REFERENCES_PARAMETER_NAME + "." + reference_name + ";"); + } + } + } + + private static void generateClearsFromMethods(ProcessingEnvironment env, PrintWriter writer, TypeElement interface_decl) { + for (ExecutableElement method : Utils.getMethods( interface_decl)) { + if (method.getAnnotation(Alternate.class) != null) { + continue; + } + + generateClearsFromParameters(writer, interface_decl, method); + } + } + + private static void generateCopiesFromMethods(ProcessingEnvironment env, PrintWriter writer, TypeElement interface_decl) { + for (ExecutableElement method : Utils.getMethods( interface_decl)) { + if (method.getAnnotation(Alternate.class) != null) { + continue; + } + + generateCopiesFromParameters(writer, interface_decl, method); + } + } + + private static void generateReferencesFromParameters(PrintWriter writer, TypeElement interface_decl, ExecutableElement method) { + for (VariableElement param : method.getParameters()) { + CachedReference cached_reference_annotation = param.getAnnotation(CachedReference.class); + if (cached_reference_annotation != null && cached_reference_annotation.name().length() == 0) { + Class nio_type = Utils.getNIOBufferType(param.asType()); + if (nio_type == null) { + throw new RuntimeException(param + " in method " + method + " in " + interface_decl + " is annotated with " + + cached_reference_annotation.annotationType().getSimpleName() + " but the parameter is not a NIO buffer"); + } + writer.print("\t" + nio_type.getName() + " " + Utils.getReferenceName(interface_decl, method, param)); + writer.println(";"); + } + } + } + + private static void generateReferencesFromMethods(ProcessingEnvironment env, PrintWriter writer, TypeElement interface_decl) { + for (ExecutableElement method : Utils.getMethods( interface_decl)) { + if (method.getAnnotation(Alternate.class) != null) { + continue; + } + + generateReferencesFromParameters(writer, interface_decl, method); + } + } + + private void generateReferencesSource(ProcessingEnvironment env, Set templates) throws IOException { + PrintWriter writer = new PrintWriter(processingEnv.getFiler().createSourceFile("org.lwjgl.opengl." + REFERENCES_CLASS_NAME, processingEnv.getElementUtils().getPackageElement("org.lwjgl.opengl")).openWriter()); + writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */"); + writer.println(); + writer.println("package org.lwjgl.opengl;"); + writer.println(); + writer.println("class " + REFERENCES_CLASS_NAME + " extends BaseReferences {"); + writer.println("\t" + REFERENCES_CLASS_NAME + "(ContextCapabilities caps) {"); + writer.println("\t\tsuper(caps);"); + writer.println("\t}"); + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + generateReferencesFromMethods(env, writer, interface_decl); + } + } + writer.println(); + writer.println("\tvoid copy(" + REFERENCES_CLASS_NAME + " " + REFERENCES_PARAMETER_NAME + ", int mask) {"); + writer.println("\t\tsuper.copy(" + REFERENCES_PARAMETER_NAME + ", mask);"); + writer.println("\t\tif ( (mask & GL11.GL_CLIENT_VERTEX_ARRAY_BIT) != 0 ) {"); + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + generateCopiesFromMethods(processingEnv, writer, interface_decl); + } + } + writer.println("\t\t}"); + writer.println("\t}"); + writer.println("\tvoid clear() {"); + writer.println("\t\tsuper.clear();"); + for (TypeElement interface_decl : templates) { + if (interface_decl.getKind().isInterface()) { + generateClearsFromMethods(processingEnv, writer, interface_decl); + } + } + writer.println("\t}"); + writer.println("}"); + writer.close(); + } + +} diff --git a/src/java/org/lwjgl/util/generator/opengl/GLReferencesGeneratorProcessorFactory.java b/src/java/org/lwjgl/util/generator/opengl/GLReferencesGeneratorProcessorFactory.java deleted file mode 100644 index 6424de78..00000000 --- a/src/java/org/lwjgl/util/generator/opengl/GLReferencesGeneratorProcessorFactory.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) 2002-2008 LWJGL Project - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'LWJGL' nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package org.lwjgl.util.generator.opengl; - -import org.lwjgl.util.generator.Alternate; -import org.lwjgl.util.generator.CachedReference; -import org.lwjgl.util.generator.Utils; - -import static java.util.Collections.emptyList; -import static java.util.Collections.unmodifiableCollection; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Arrays; -import java.util.Collection; -import java.util.Set; - -import com.sun.mirror.apt.AnnotationProcessor; -import com.sun.mirror.apt.AnnotationProcessorEnvironment; -import com.sun.mirror.apt.AnnotationProcessorFactory; -import com.sun.mirror.apt.AnnotationProcessors; -import com.sun.mirror.apt.Filer; -import com.sun.mirror.apt.RoundCompleteEvent; -import com.sun.mirror.apt.RoundCompleteListener; -import com.sun.mirror.declaration.AnnotationTypeDeclaration; -import com.sun.mirror.declaration.InterfaceDeclaration; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.declaration.ParameterDeclaration; -import com.sun.mirror.declaration.TypeDeclaration; -import com.sun.mirror.util.DeclarationFilter; - -/** - * - * Generator tool for creating the References class - * - * @author elias_naur - * @version $Revision: 3237 $ - * $Id: ReferencesGeneratorProcessorFactory.java 3237 2009-09-08 15:07:15Z spasi $ - */ -public class GLReferencesGeneratorProcessorFactory implements AnnotationProcessorFactory, RoundCompleteListener { - private static final String REFERENCES_CLASS_NAME = "References"; - private static final String REFERENCES_PARAMETER_NAME = "references"; - - private static boolean first_round = true; - - // Process any set of annotations - private static final Collection supportedAnnotations = - unmodifiableCollection(Arrays.asList("*")); - - public Collection supportedAnnotationTypes() { - return supportedAnnotations; - } - - public Collection supportedOptions() { - return emptyList(); - } - - public void roundComplete(RoundCompleteEvent event) { - first_round = false; - } - - public AnnotationProcessor getProcessorFor(Set atds, AnnotationProcessorEnvironment env) { - // Only process the initial types, not the generated ones - if (first_round) { - env.addListener(this); - return new GeneratorProcessor(env); - } else - return AnnotationProcessors.NO_OP; - } - - private static class GeneratorProcessor implements AnnotationProcessor { - private final AnnotationProcessorEnvironment env; - - GeneratorProcessor(AnnotationProcessorEnvironment env) { - this.env = env; - } - - public void process() { - try { - generateReferencesSource(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private static void generateClearsFromParameters(PrintWriter writer, InterfaceDeclaration interface_decl, MethodDeclaration method) { - for (ParameterDeclaration param : method.getParameters()) { - CachedReference cached_reference_annotation = param.getAnnotation(CachedReference.class); - if (cached_reference_annotation != null && cached_reference_annotation.name().length() == 0) { - Class nio_type = Utils.getNIOBufferType(param.getType()); - String reference_name = Utils.getReferenceName(interface_decl, method, param); - writer.println("\t\tthis." + reference_name + " = null;"); - } - } - } - - private static void generateCopiesFromParameters(PrintWriter writer, InterfaceDeclaration interface_decl, MethodDeclaration method) { - for (ParameterDeclaration param : method.getParameters()) { - CachedReference cached_reference_annotation = param.getAnnotation(CachedReference.class); - if (cached_reference_annotation != null && cached_reference_annotation.name().length() == 0) { - Class nio_type = Utils.getNIOBufferType(param.getType()); - String reference_name = Utils.getReferenceName(interface_decl, method, param); - writer.print("\t\t\tthis." + reference_name + " = "); - writer.println(REFERENCES_PARAMETER_NAME + "." + reference_name + ";"); - } - } - } - - private static void generateClearsFromMethods(PrintWriter writer, InterfaceDeclaration interface_decl) { - for (MethodDeclaration method : interface_decl.getMethods()) { - if ( method.getAnnotation(Alternate.class) != null ) - continue; - - generateClearsFromParameters(writer, interface_decl, method); - } - } - - private static void generateCopiesFromMethods(PrintWriter writer, InterfaceDeclaration interface_decl) { - for (MethodDeclaration method : interface_decl.getMethods()) { - if ( method.getAnnotation(Alternate.class) != null ) - continue; - - generateCopiesFromParameters(writer, interface_decl, method); - } - } - - private static void generateReferencesFromParameters(PrintWriter writer, InterfaceDeclaration interface_decl, MethodDeclaration method) { - for (ParameterDeclaration param : method.getParameters()) { - CachedReference cached_reference_annotation = param.getAnnotation(CachedReference.class); - if (cached_reference_annotation != null && cached_reference_annotation.name().length() == 0) { - Class nio_type = Utils.getNIOBufferType(param.getType()); - if (nio_type == null) - throw new RuntimeException(param + " in method " + method + " in " + interface_decl + " is annotated with " - + cached_reference_annotation.annotationType().getSimpleName() + " but the parameter is not a NIO buffer"); - writer.print("\t" + nio_type.getName() + " " + Utils.getReferenceName(interface_decl, method, param)); - writer.println(";"); - } - } - } - - private static void generateReferencesFromMethods(PrintWriter writer, InterfaceDeclaration interface_decl) { - for (MethodDeclaration method : interface_decl.getMethods()) { - if ( method.getAnnotation(Alternate.class) != null ) - continue; - - generateReferencesFromParameters(writer, interface_decl, method); - } - } - - private void generateReferencesSource() throws IOException { - PrintWriter writer = env.getFiler().createTextFile(Filer.Location.SOURCE_TREE, "org.lwjgl.opengl", new File(REFERENCES_CLASS_NAME + ".java"), null); - writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */"); - writer.println(); - writer.println("package org.lwjgl.opengl;"); - writer.println(); - writer.println("class " + REFERENCES_CLASS_NAME + " extends BaseReferences {"); - writer.println("\t" + REFERENCES_CLASS_NAME + "(ContextCapabilities caps) {"); - writer.println("\t\tsuper(caps);"); - writer.println("\t}"); - DeclarationFilter filter = DeclarationFilter.getFilter(InterfaceDeclaration.class); - Collection interface_decls = filter.filter(env.getSpecifiedTypeDeclarations()); - for (TypeDeclaration typedecl : interface_decls) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - generateReferencesFromMethods(writer, interface_decl); - } - writer.println(); - writer.println("\tvoid copy(" + REFERENCES_CLASS_NAME + " " + REFERENCES_PARAMETER_NAME + ", int mask) {"); - writer.println("\t\tsuper.copy(" + REFERENCES_PARAMETER_NAME + ", mask);"); - writer.println("\t\tif ( (mask & GL11.GL_CLIENT_VERTEX_ARRAY_BIT) != 0 ) {"); - for (TypeDeclaration typedecl : interface_decls) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - generateCopiesFromMethods(writer, interface_decl); - } - writer.println("\t\t}"); - writer.println("\t}"); - writer.println("\tvoid clear() {"); - writer.println("\t\tsuper.clear();"); - for (TypeDeclaration typedecl : interface_decls) { - InterfaceDeclaration interface_decl = (InterfaceDeclaration)typedecl; - generateClearsFromMethods(writer, interface_decl); - } - writer.println("\t}"); - writer.println("}"); - writer.close(); - } - } -} diff --git a/src/java/org/lwjgl/util/generator/opengl/GLTypeMap.java b/src/java/org/lwjgl/util/generator/opengl/GLTypeMap.java index 46797e21..24586632 100644 --- a/src/java/org/lwjgl/util/generator/opengl/GLTypeMap.java +++ b/src/java/org/lwjgl/util/generator/opengl/GLTypeMap.java @@ -29,7 +29,6 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - package org.lwjgl.util.generator.opengl; /** @@ -37,10 +36,9 @@ package org.lwjgl.util.generator.opengl; * OpenGL sepcific generator behaviour * * @author elias_naur - * @version $Revision: 3392 $ - * $Id: GLTypeMap.java 3392 2010-07-27 15:33:22Z spasi $ + * @version $Revision: 3392 $ $Id: GLTypeMap.java 3392 2010-07-27 15:33:22Z + * spasi $ */ - import org.lwjgl.PointerBuffer; import org.lwjgl.util.generator.NativeTypeTranslator; import org.lwjgl.util.generator.PointerWrapper; @@ -52,280 +50,314 @@ import java.lang.annotation.Annotation; import java.nio.*; import java.util.HashMap; import java.util.Map; - -import com.sun.mirror.declaration.AnnotationMirror; -import com.sun.mirror.declaration.MethodDeclaration; -import com.sun.mirror.type.PrimitiveType; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.type.TypeKind; +import static javax.lang.model.type.TypeKind.BOOLEAN; +import static javax.lang.model.type.TypeKind.BYTE; +import static javax.lang.model.type.TypeKind.DOUBLE; +import static javax.lang.model.type.TypeKind.FLOAT; +import static javax.lang.model.type.TypeKind.INT; +import static javax.lang.model.type.TypeKind.LONG; +import static javax.lang.model.type.TypeKind.SHORT; public class GLTypeMap implements TypeMap { - private static final Map native_types_to_primitive; + private static final Map native_types_to_primitive; - static { - native_types_to_primitive = new HashMap(); - native_types_to_primitive.put(GLbitfield.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(GLcharARB.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(GLclampf.class, PrimitiveType.Kind.FLOAT); - native_types_to_primitive.put(GLfloat.class, PrimitiveType.Kind.FLOAT); - native_types_to_primitive.put(GLint.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(GLshort.class, PrimitiveType.Kind.SHORT); - native_types_to_primitive.put(GLsizeiptr.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(GLuint.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(GLboolean.class, PrimitiveType.Kind.BOOLEAN); - native_types_to_primitive.put(GLchar.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(GLdouble.class, PrimitiveType.Kind.DOUBLE); - native_types_to_primitive.put(GLhalf.class, PrimitiveType.Kind.SHORT); - native_types_to_primitive.put(GLintptrARB.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(GLsizei.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(GLushort.class, PrimitiveType.Kind.SHORT); - native_types_to_primitive.put(GLbyte.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(GLclampd.class, PrimitiveType.Kind.DOUBLE); - native_types_to_primitive.put(GLenum.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(GLhandleARB.class, PrimitiveType.Kind.INT); - native_types_to_primitive.put(GLintptr.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(GLsizeiptrARB.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(GLubyte.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(GLvoid.class, PrimitiveType.Kind.BYTE); - native_types_to_primitive.put(GLint64EXT.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(GLuint64EXT.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(GLint64.class, PrimitiveType.Kind.LONG); - native_types_to_primitive.put(GLuint64.class, PrimitiveType.Kind.LONG); - } + static { + native_types_to_primitive = new HashMap<>(); + native_types_to_primitive.put(GLbitfield.class, TypeKind.INT); + native_types_to_primitive.put(GLcharARB.class, TypeKind.BYTE); + native_types_to_primitive.put(GLclampf.class, TypeKind.FLOAT); + native_types_to_primitive.put(GLfloat.class, TypeKind.FLOAT); + native_types_to_primitive.put(GLint.class, TypeKind.INT); + native_types_to_primitive.put(GLshort.class, TypeKind.SHORT); + native_types_to_primitive.put(GLsizeiptr.class, TypeKind.LONG); + native_types_to_primitive.put(GLuint.class, TypeKind.INT); + native_types_to_primitive.put(GLboolean.class, TypeKind.BOOLEAN); + native_types_to_primitive.put(GLchar.class, TypeKind.BYTE); + native_types_to_primitive.put(GLdouble.class, TypeKind.DOUBLE); + native_types_to_primitive.put(GLhalf.class, TypeKind.SHORT); + native_types_to_primitive.put(GLintptrARB.class, TypeKind.LONG); + native_types_to_primitive.put(GLsizei.class, TypeKind.INT); + native_types_to_primitive.put(GLushort.class, TypeKind.SHORT); + native_types_to_primitive.put(GLbyte.class, TypeKind.BYTE); + native_types_to_primitive.put(GLclampd.class, TypeKind.DOUBLE); + native_types_to_primitive.put(GLenum.class, TypeKind.INT); + native_types_to_primitive.put(GLhandleARB.class, TypeKind.INT); + native_types_to_primitive.put(GLintptr.class, TypeKind.LONG); + native_types_to_primitive.put(GLsizeiptrARB.class, TypeKind.LONG); + native_types_to_primitive.put(GLubyte.class, TypeKind.BYTE); + native_types_to_primitive.put(GLvoid.class, TypeKind.BYTE); + native_types_to_primitive.put(GLint64EXT.class, TypeKind.LONG); + native_types_to_primitive.put(GLuint64EXT.class, TypeKind.LONG); + native_types_to_primitive.put(GLint64.class, TypeKind.LONG); + native_types_to_primitive.put(GLuint64.class, TypeKind.LONG); + } - public PrimitiveType.Kind getPrimitiveTypeFromNativeType(Class native_type) { - PrimitiveType.Kind kind = native_types_to_primitive.get(native_type); - if ( kind == null ) - throw new RuntimeException("Unsupported type " + native_type); - return kind; - } + @Override + public TypeKind getPrimitiveTypeFromNativeType(Class native_type) { + TypeKind kind = native_types_to_primitive.get(native_type); + if (kind == null) { + throw new RuntimeException("Unsupported type " + native_type); + } + return kind; + } - public void printCapabilitiesInit(final PrintWriter writer) { - writer.println("\t\tContextCapabilities caps = GLContext.getCapabilities();"); - } + @Override + public void printCapabilitiesInit(final PrintWriter writer) { + writer.println("\t\tContextCapabilities caps = GLContext.getCapabilities();"); + } - public String getCapabilities() { - return "caps"; - } + @Override + public String getCapabilities() { + return "caps"; + } - public String getAPIUtilParam(boolean comma) { - return comma ? "caps, " : "caps"; - } + @Override + public String getAPIUtilParam(boolean comma) { + return comma ? "caps, " : "caps"; + } - public void printErrorCheckMethod(final PrintWriter writer, final MethodDeclaration method, final String tabs) { - writer.println(tabs + "Util.checkGLError();"); - } + @Override + public void printErrorCheckMethod(final PrintWriter writer, final ExecutableElement method, final String tabs) { + writer.println(tabs + "Util.checkGLError();"); + } - public String getRegisterNativesFunctionName() { - return "extgl_InitializeClass"; - } + @Override + public String getRegisterNativesFunctionName() { + return "extgl_InitializeClass"; + } - public Signedness getSignednessFromType(Class type) { - if ( GLuint.class.equals(type) ) - return Signedness.UNSIGNED; - else if ( GLint.class.equals(type) ) - return Signedness.SIGNED; - else if ( GLushort.class.equals(type) ) - return Signedness.UNSIGNED; - else if ( GLshort.class.equals(type) ) - return Signedness.SIGNED; - else if ( GLubyte.class.equals(type) ) - return Signedness.UNSIGNED; - else if ( GLbyte.class.equals(type) ) - return Signedness.SIGNED; - else if ( GLuint64EXT.class.equals(type) ) - return Signedness.UNSIGNED; - else if ( GLint64EXT.class.equals(type) ) - return Signedness.SIGNED; - else if ( GLuint64.class.equals(type) ) - return Signedness.UNSIGNED; - else if ( GLint64.class.equals(type) ) - return Signedness.SIGNED; - else - return Signedness.NONE; - } + @Override + public Signedness getSignednessFromType(Class type) { + if (GLuint.class.equals(type)) { + return Signedness.UNSIGNED; + } else if (GLint.class.equals(type)) { + return Signedness.SIGNED; + } else if (GLushort.class.equals(type)) { + return Signedness.UNSIGNED; + } else if (GLshort.class.equals(type)) { + return Signedness.SIGNED; + } else if (GLubyte.class.equals(type)) { + return Signedness.UNSIGNED; + } else if (GLbyte.class.equals(type)) { + return Signedness.SIGNED; + } else if (GLuint64EXT.class.equals(type)) { + return Signedness.UNSIGNED; + } else if (GLint64EXT.class.equals(type)) { + return Signedness.SIGNED; + } else if (GLuint64.class.equals(type)) { + return Signedness.UNSIGNED; + } else if (GLint64.class.equals(type)) { + return Signedness.SIGNED; + } else { + return Signedness.NONE; + } + } - public String translateAnnotation(Class annotation_type) { - if ( annotation_type.equals(GLuint.class) || annotation_type.equals(GLint.class) ) - return "i"; - else if ( annotation_type.equals(GLushort.class) || annotation_type.equals(GLshort.class) ) - return "s"; - else if ( annotation_type.equals(GLubyte.class) || annotation_type.equals(GLbyte.class) ) - return "b"; - else if ( annotation_type.equals(GLfloat.class) || annotation_type.equals(GLclampf.class) ) - return "f"; - else if ( annotation_type.equals(GLdouble.class) || annotation_type.equals(GLclampd.class) ) - return "d"; - else if ( annotation_type.equals(GLhalf.class) ) - return "h"; - else if ( annotation_type.equals(GLuint64EXT.class) || annotation_type.equals(GLint64EXT.class) || annotation_type.equals(GLuint64.class) || annotation_type.equals(GLint64.class) ) - return "i64"; - else if ( annotation_type.equals(GLboolean.class) || annotation_type.equals(GLvoid.class) ) - return ""; - else - throw new RuntimeException(annotation_type + " is not allowed"); - } + @Override + public String translateAnnotation(Class annotation_type) { + if (annotation_type.equals(GLuint.class) || annotation_type.equals(GLint.class)) { + return "i"; + } else if (annotation_type.equals(GLushort.class) || annotation_type.equals(GLshort.class)) { + return "s"; + } else if (annotation_type.equals(GLubyte.class) || annotation_type.equals(GLbyte.class)) { + return "b"; + } else if (annotation_type.equals(GLfloat.class) || annotation_type.equals(GLclampf.class)) { + return "f"; + } else if (annotation_type.equals(GLdouble.class) || annotation_type.equals(GLclampd.class)) { + return "d"; + } else if (annotation_type.equals(GLhalf.class)) { + return "h"; + } else if (annotation_type.equals(GLuint64EXT.class) || annotation_type.equals(GLint64EXT.class) || annotation_type.equals(GLuint64.class) || annotation_type.equals(GLint64.class)) { + return "i64"; + } else if (annotation_type.equals(GLboolean.class) || annotation_type.equals(GLvoid.class)) { + return ""; + } else { + throw new RuntimeException(annotation_type + " is not allowed"); + } + } - public Class getNativeTypeFromPrimitiveType(PrimitiveType.Kind kind) { - Class type; - switch ( kind ) { - case INT: - type = GLint.class; - break; - case DOUBLE: - type = GLdouble.class; - break; - case FLOAT: - type = GLfloat.class; - break; - case SHORT: - type = GLshort.class; - break; - case BYTE: - type = GLbyte.class; - break; - case LONG: - type = GLint64EXT.class; - break; - case BOOLEAN: - type = GLboolean.class; - break; - default: - throw new RuntimeException(kind + " is not allowed"); - } - return type; - } + @Override + public Class getNativeTypeFromPrimitiveType(TypeKind kind) { + Class type; + switch (kind) { + case INT: + type = GLint.class; + break; + case DOUBLE: + type = GLdouble.class; + break; + case FLOAT: + type = GLfloat.class; + break; + case SHORT: + type = GLshort.class; + break; + case BYTE: + type = GLbyte.class; + break; + case LONG: + type = GLint64EXT.class; + break; + case BOOLEAN: + type = GLboolean.class; + break; + default: + throw new RuntimeException(kind + " is not allowed"); + } + return type; + } - public Class getVoidType() { - return GLvoid.class; - } + @Override + public Class getVoidType() { + return GLvoid.class; + } - public Class getStringElementType() { - return GLubyte.class; - } + @Override + public Class getStringElementType() { + return GLubyte.class; + } - public Class getStringArrayType() { - return GLchar.class; - } + @Override + public Class getStringArrayType() { + return GLchar.class; + } - public Class getByteBufferArrayType() { - return GLchar.class; - } + @Override + public Class getByteBufferArrayType() { + return GLchar.class; + } - private static Class[] getValidBufferTypes(Class type) { - if ( type.equals(IntBuffer.class) ) - return new Class[] { GLbitfield.class, GLenum.class, GLhandleARB.class, GLint.class, - GLsizei.class, GLuint.class, GLvoid.class }; - else if ( type.equals(FloatBuffer.class) ) - return new Class[] { GLclampf.class, GLfloat.class }; - else if ( type.equals(ByteBuffer.class) ) - return new Class[] { GLboolean.class, GLbyte.class, GLcharARB.class, GLchar.class, GLubyte.class, GLvoid.class }; - else if ( type.equals(ShortBuffer.class) ) - return new Class[] { GLhalf.class, GLshort.class, GLushort.class }; - else if ( type.equals(DoubleBuffer.class) ) - return new Class[] { GLclampd.class, GLdouble.class }; - else if ( type.equals(LongBuffer.class) ) - return new Class[] { GLint64EXT.class, GLuint64EXT.class, GLint64.class, GLuint64.class }; - else - return new Class[] { }; - } + private static Class[] getValidBufferTypes(Class type) { + if (type.equals(IntBuffer.class)) { + return new Class[]{GLbitfield.class, GLenum.class, GLhandleARB.class, GLint.class, + GLsizei.class, GLuint.class, GLvoid.class}; + } else if (type.equals(FloatBuffer.class)) { + return new Class[]{GLclampf.class, GLfloat.class}; + } else if (type.equals(ByteBuffer.class)) { + return new Class[]{GLboolean.class, GLbyte.class, GLcharARB.class, GLchar.class, GLubyte.class, GLvoid.class}; + } else if (type.equals(ShortBuffer.class)) { + return new Class[]{GLhalf.class, GLshort.class, GLushort.class}; + } else if (type.equals(DoubleBuffer.class)) { + return new Class[]{GLclampd.class, GLdouble.class}; + } else if (type.equals(LongBuffer.class)) { + return new Class[]{GLint64EXT.class, GLuint64EXT.class, GLint64.class, GLuint64.class}; + } else { + return new Class[]{}; + } + } - private static Class[] getValidPrimitiveTypes(Class type) { - if ( type.equals(long.class) ) - return new Class[] { GLintptrARB.class, GLuint.class, GLintptr.class, GLsizeiptrARB.class, GLsizeiptr.class, GLint64EXT.class, GLuint64EXT.class, GLint64.class, GLuint64.class }; - else if ( type.equals(int.class) ) - return new Class[] { GLbitfield.class, GLenum.class, GLhandleARB.class, GLint.class, GLuint.class, - GLsizei.class }; - else if ( type.equals(double.class) ) - return new Class[] { GLclampd.class, GLdouble.class }; - else if ( type.equals(float.class) ) - return new Class[] { GLclampf.class, GLfloat.class }; - else if ( type.equals(short.class) ) - return new Class[] { GLhalf.class, GLshort.class, GLushort.class }; - else if ( type.equals(byte.class) ) - return new Class[] { GLbyte.class, GLcharARB.class, GLchar.class, GLubyte.class }; - else if ( type.equals(boolean.class) ) - return new Class[] { GLboolean.class }; - else if ( type.equals(void.class) ) - return new Class[] { GLvoid.class, GLreturn.class }; - else - return new Class[] { }; - } + private static Class[] getValidPrimitiveTypes(Class type) { + if (type.equals(long.class)) { + return new Class[]{GLintptrARB.class, GLuint.class, GLintptr.class, GLsizeiptrARB.class, GLsizeiptr.class, GLint64EXT.class, GLuint64EXT.class, GLint64.class, GLuint64.class}; + } else if (type.equals(int.class)) { + return new Class[]{GLbitfield.class, GLenum.class, GLhandleARB.class, GLint.class, GLuint.class, + GLsizei.class}; + } else if (type.equals(double.class)) { + return new Class[]{GLclampd.class, GLdouble.class}; + } else if (type.equals(float.class)) { + return new Class[]{GLclampf.class, GLfloat.class}; + } else if (type.equals(short.class)) { + return new Class[]{GLhalf.class, GLshort.class, GLushort.class}; + } else if (type.equals(byte.class)) { + return new Class[]{GLbyte.class, GLcharARB.class, GLchar.class, GLubyte.class}; + } else if (type.equals(boolean.class)) { + return new Class[]{GLboolean.class}; + } else if (type.equals(void.class)) { + return new Class[]{GLvoid.class, GLreturn.class}; + } else { + return new Class[]{}; + } + } - public String getTypedefPostfix() { - return ""; - } + @Override + public String getTypedefPostfix() { + return ""; + } - public String getFunctionPrefix() { - return "APIENTRY"; - } + @Override + public String getFunctionPrefix() { + return "APIENTRY"; + } - public void printNativeIncludes(PrintWriter writer) { - writer.println("#include \"extgl.h\""); - } + @Override + public void printNativeIncludes(PrintWriter writer) { + writer.println("#include \"extgl.h\""); + } - public Class[] getValidAnnotationTypes(Class type) { - Class[] valid_types; - if ( Buffer.class.isAssignableFrom(type) ) - valid_types = getValidBufferTypes(type); - else if ( type.isPrimitive() ) - valid_types = getValidPrimitiveTypes(type); - else if ( String.class.equals(type) ) - valid_types = new Class[] { GLubyte.class }; - else if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(type) ) - valid_types = new Class[] { PointerWrapper.class }; - else if (void.class.equals(type) ) - valid_types = new Class[] { GLreturn.class }; - else if ( PointerBuffer.class.equals(type) ) - valid_types = new Class[] { GLintptr.class, GLintptrARB.class, GLsizeiptr.class, GLsizeiptrARB.class }; - else - valid_types = new Class[] { }; - return valid_types; - } + @Override + public Class[] getValidAnnotationTypes(Class type) { + Class[] valid_types; + if (Buffer.class.isAssignableFrom(type)) { + valid_types = getValidBufferTypes(type); + } else if (type.isPrimitive()) { + valid_types = getValidPrimitiveTypes(type); + } else if (String.class.equals(type)) { + valid_types = new Class[]{GLubyte.class}; + } else if (org.lwjgl.PointerWrapper.class.isAssignableFrom(type)) { + valid_types = new Class[]{PointerWrapper.class}; + } else if (void.class.equals(type)) { + valid_types = new Class[]{GLreturn.class}; + } else if (PointerBuffer.class.equals(type)) { + valid_types = new Class[]{GLintptr.class, GLintptrARB.class, GLsizeiptr.class, GLsizeiptrARB.class}; + } else { + valid_types = new Class[]{}; + } + return valid_types; + } - public Class getInverseType(Class type) { - if ( GLuint.class.equals(type) ) - return GLint.class; - else if ( GLint.class.equals(type) ) - return GLuint.class; - else if ( GLushort.class.equals(type) ) - return GLshort.class; - else if ( GLshort.class.equals(type) ) - return GLushort.class; - else if ( GLubyte.class.equals(type) ) - return GLbyte.class; - else if ( GLbyte.class.equals(type) ) - return GLubyte.class; - else if ( GLuint64EXT.class.equals(type) ) - return GLint64EXT.class; - else if ( GLint64EXT.class.equals(type) ) - return GLuint64EXT.class; - else if ( GLuint64.class.equals(type) ) - return GLint64.class; - else if ( GLint64.class.equals(type) ) - return GLuint64.class; - else - return null; - } + @Override + public Class getInverseType(Class type) { + if (GLuint.class.equals(type)) { + return GLint.class; + } else if (GLint.class.equals(type)) { + return GLuint.class; + } else if (GLushort.class.equals(type)) { + return GLshort.class; + } else if (GLshort.class.equals(type)) { + return GLushort.class; + } else if (GLubyte.class.equals(type)) { + return GLbyte.class; + } else if (GLbyte.class.equals(type)) { + return GLubyte.class; + } else if (GLuint64EXT.class.equals(type)) { + return GLint64EXT.class; + } else if (GLint64EXT.class.equals(type)) { + return GLuint64EXT.class; + } else if (GLuint64.class.equals(type)) { + return GLint64.class; + } else if (GLint64.class.equals(type)) { + return GLuint64.class; + } else { + return null; + } + } - public String getAutoTypeFromAnnotation(AnnotationMirror annotation) { - Class annotation_class = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType()); - if ( annotation_class.equals(GLint.class) ) - return "GL11.GL_INT"; - else if ( annotation_class.equals(GLbyte.class) ) - return "GL11.GL_BYTE"; - else if ( annotation_class.equals(GLshort.class) ) - return "GL11.GL_SHORT"; - if ( annotation_class.equals(GLuint.class) ) - return "GL11.GL_UNSIGNED_INT"; - else if ( annotation_class.equals(GLubyte.class) ) - return "GL11.GL_UNSIGNED_BYTE"; - else if ( annotation_class.equals(GLushort.class) ) - return "GL11.GL_UNSIGNED_SHORT"; - else if ( annotation_class.equals(GLfloat.class) ) - return "GL11.GL_FLOAT"; - else if ( annotation_class.equals(GLdouble.class) ) - return "GL11.GL_DOUBLE"; - else - return null; - } + @Override + public String getAutoTypeFromAnnotation(AnnotationMirror annotation) { + Class annotation_class = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType()); + if (annotation_class.equals(GLint.class)) { + return "GL11.GL_INT"; + } else if (annotation_class.equals(GLbyte.class)) { + return "GL11.GL_BYTE"; + } else if (annotation_class.equals(GLshort.class)) { + return "GL11.GL_SHORT"; + } + if (annotation_class.equals(GLuint.class)) { + return "GL11.GL_UNSIGNED_INT"; + } else if (annotation_class.equals(GLubyte.class)) { + return "GL11.GL_UNSIGNED_BYTE"; + } else if (annotation_class.equals(GLushort.class)) { + return "GL11.GL_UNSIGNED_SHORT"; + } else if (annotation_class.equals(GLfloat.class)) { + return "GL11.GL_FLOAT"; + } else if (annotation_class.equals(GLdouble.class)) { + return "GL11.GL_DOUBLE"; + } else { + return null; + } + } } diff --git a/src/java/org/lwjgl/util/generator/opengl/GLvoid.java b/src/java/org/lwjgl/util/generator/opengl/GLvoid.java index 8cff6a29..6deb8ee7 100644 --- a/src/java/org/lwjgl/util/generator/opengl/GLvoid.java +++ b/src/java/org/lwjgl/util/generator/opengl/GLvoid.java @@ -42,11 +42,10 @@ import org.lwjgl.util.generator.NativeType; import java.lang.annotation.Target; import java.lang.annotation.ElementType; - -import com.sun.mirror.type.PrimitiveType; +import javax.lang.model.type.TypeKind; @NativeType @Target({ElementType.PARAMETER, ElementType.METHOD}) public @interface GLvoid { - PrimitiveType.Kind value() default PrimitiveType.Kind.BYTE; + TypeKind value() default TypeKind.BYTE; } diff --git a/src/native/macosx/org_lwjgl_opengl_MacOSXAWTMouse.m b/src/native/macosx/org_lwjgl_opengl_MacOSXAWTMouse.m index 16122a82..22500ee7 100644 --- a/src/native/macosx/org_lwjgl_opengl_MacOSXAWTMouse.m +++ b/src/native/macosx/org_lwjgl_opengl_MacOSXAWTMouse.m @@ -57,10 +57,11 @@ JNIEXPORT void JNICALL Java_org_lwjgl_opengl_MacOSXMouseEventQueue_nWarpCursor(J p.x = x; p.y = y; CGWarpMouseCursorPosition(p); + CGAssociateMouseAndMouseCursorPosition(true); } JNIEXPORT void JNICALL Java_org_lwjgl_opengl_MacOSXMouseEventQueue_getMouseDeltas(JNIEnv *env, jclass unused, jobject delta_buffer) { - CGMouseDelta dx, dy; + int32_t dx, dy; CGGetLastMouseDelta(&dx, &dy); int buffer_length = (*env)->GetDirectBufferCapacity(env, delta_buffer); if (buffer_length != 2) { diff --git a/src/templates/org/lwjgl/opengl/AMD_multi_draw_indirect.java b/src/templates/org/lwjgl/opengl/AMD_multi_draw_indirect.java index d6419399..fc21fd36 100644 --- a/src/templates/org/lwjgl/opengl/AMD_multi_draw_indirect.java +++ b/src/templates/org/lwjgl/opengl/AMD_multi_draw_indirect.java @@ -39,7 +39,7 @@ import org.lwjgl.util.generator.opengl.GLvoid; import java.nio.ByteBuffer; import java.nio.IntBuffer; -import com.sun.mirror.type.PrimitiveType; +import javax.lang.model.type.TypeKind; public interface AMD_multi_draw_indirect { @@ -50,7 +50,7 @@ public interface AMD_multi_draw_indirect { @Alternate("glMultiDrawArraysIndirectAMD") void glMultiDrawArraysIndirectAMD(@GLenum int mode, - @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 4 : stride >> 2) * primcount") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect, + @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 4 : stride >> 2) * primcount") @Const @GLvoid(TypeKind.INT) IntBuffer indirect, @GLsizei int primcount, @GLsizei int stride); @@ -63,7 +63,7 @@ public interface AMD_multi_draw_indirect { @Alternate("glMultiDrawElementsIndirectAMD") void glMultiDrawElementsIndirectAMD(@GLenum int mode, @GLenum int type, - @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 5 : stride >> 2) * primcount") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect, + @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 5 : stride >> 2) * primcount") @Const @GLvoid(TypeKind.INT) IntBuffer indirect, @GLsizei int primcount, @GLsizei int stride); diff --git a/src/templates/org/lwjgl/opengl/ARB_draw_indirect.java b/src/templates/org/lwjgl/opengl/ARB_draw_indirect.java index 523e3ccf..3df1b31d 100644 --- a/src/templates/org/lwjgl/opengl/ARB_draw_indirect.java +++ b/src/templates/org/lwjgl/opengl/ARB_draw_indirect.java @@ -38,7 +38,7 @@ import org.lwjgl.util.generator.opengl.GLvoid; import java.nio.ByteBuffer; import java.nio.IntBuffer; -import com.sun.mirror.type.PrimitiveType; +import javax.lang.model.type.TypeKind; public interface ARB_draw_indirect { @@ -62,13 +62,13 @@ public interface ARB_draw_indirect { @Reuse("GL40") @Alternate("glDrawArraysIndirect") - void glDrawArraysIndirect(@GLenum int mode, @BufferObject(BufferKind.IndirectBO) @Check("4") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect); + void glDrawArraysIndirect(@GLenum int mode, @BufferObject(BufferKind.IndirectBO) @Check("4") @Const @GLvoid(TypeKind.INT) IntBuffer indirect); @Reuse("GL40") void glDrawElementsIndirect(@GLenum int mode, @GLenum int type, @BufferObject(BufferKind.IndirectBO) @Check("5 * 4") @Const @GLvoid ByteBuffer indirect); @Reuse("GL40") @Alternate("glDrawElementsIndirect") - void glDrawElementsIndirect(@GLenum int mode, @GLenum int type, @BufferObject(BufferKind.IndirectBO) @Check("5") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect); + void glDrawElementsIndirect(@GLenum int mode, @GLenum int type, @BufferObject(BufferKind.IndirectBO) @Check("5") @Const @GLvoid(TypeKind.INT) IntBuffer indirect); } \ No newline at end of file diff --git a/src/templates/org/lwjgl/opengl/ARB_indirect_parameters.java b/src/templates/org/lwjgl/opengl/ARB_indirect_parameters.java index 74f3738e..e05ef093 100644 --- a/src/templates/org/lwjgl/opengl/ARB_indirect_parameters.java +++ b/src/templates/org/lwjgl/opengl/ARB_indirect_parameters.java @@ -40,7 +40,7 @@ import org.lwjgl.util.generator.opengl.GLvoid; import java.nio.ByteBuffer; import java.nio.IntBuffer; -import com.sun.mirror.type.PrimitiveType; +import javax.lang.model.type.TypeKind; public interface ARB_indirect_parameters { @@ -66,7 +66,7 @@ public interface ARB_indirect_parameters { @Alternate("glMultiDrawArraysIndirectCountARB") void glMultiDrawArraysIndirectCountARB(@GLenum int mode, - @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 4 : stride >> 2) * maxdrawcount") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect, + @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 4 : stride >> 2) * maxdrawcount") @Const @GLvoid(TypeKind.INT) IntBuffer indirect, @GLintptr long drawcount, @GLsizei int maxdrawcount, @GLsizei int stride); @@ -81,7 +81,7 @@ public interface ARB_indirect_parameters { @Alternate("glMultiDrawElementsIndirectCountARB") void glMultiDrawElementsIndirectCountARB(@GLenum int mode, @GLenum int type, - @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 5 : stride >> 2) * maxdrawcount") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect, + @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 5 : stride >> 2) * maxdrawcount") @Const @GLvoid(TypeKind.INT) IntBuffer indirect, @GLintptr long drawcount, @GLsizei int maxdrawcount, @GLsizei int stride); diff --git a/src/templates/org/lwjgl/opengl/ARB_multi_draw_indirect.java b/src/templates/org/lwjgl/opengl/ARB_multi_draw_indirect.java index e218e807..155390ea 100644 --- a/src/templates/org/lwjgl/opengl/ARB_multi_draw_indirect.java +++ b/src/templates/org/lwjgl/opengl/ARB_multi_draw_indirect.java @@ -39,7 +39,7 @@ import org.lwjgl.util.generator.opengl.GLvoid; import java.nio.ByteBuffer; import java.nio.IntBuffer; -import com.sun.mirror.type.PrimitiveType; +import javax.lang.model.type.TypeKind; public interface ARB_multi_draw_indirect { @@ -52,7 +52,7 @@ public interface ARB_multi_draw_indirect { @Reuse("GL43") @Alternate("glMultiDrawArraysIndirect") void glMultiDrawArraysIndirect(@GLenum int mode, - @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 4 : stride >> 2) * primcount") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect, + @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 4 : stride >> 2) * primcount") @Const @GLvoid(TypeKind.INT) IntBuffer indirect, @GLsizei int primcount, @GLsizei int stride); @@ -67,7 +67,7 @@ public interface ARB_multi_draw_indirect { @Alternate("glMultiDrawElementsIndirect") void glMultiDrawElementsIndirect(@GLenum int mode, @GLenum int type, - @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 5 : stride >> 2) * primcount") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect, + @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 5 : stride >> 2) * primcount") @Const @GLvoid(TypeKind.INT) IntBuffer indirect, @GLsizei int primcount, @GLsizei int stride); diff --git a/src/templates/org/lwjgl/opengl/GL40.java b/src/templates/org/lwjgl/opengl/GL40.java index 9dc62df0..256e646e 100644 --- a/src/templates/org/lwjgl/opengl/GL40.java +++ b/src/templates/org/lwjgl/opengl/GL40.java @@ -40,7 +40,7 @@ import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; -import com.sun.mirror.type.PrimitiveType; +import javax.lang.model.type.TypeKind; public interface GL40 { @@ -78,12 +78,12 @@ public interface GL40 { void glDrawArraysIndirect(@GLenum int mode, @BufferObject(BufferKind.IndirectBO) @Check("4 * 4") @Const @GLvoid ByteBuffer indirect); @Alternate("glDrawArraysIndirect") - void glDrawArraysIndirect(@GLenum int mode, @BufferObject(BufferKind.IndirectBO) @Check("4") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect); + void glDrawArraysIndirect(@GLenum int mode, @BufferObject(BufferKind.IndirectBO) @Check("4") @Const @GLvoid(TypeKind.INT) IntBuffer indirect); void glDrawElementsIndirect(@GLenum int mode, @GLenum int type, @BufferObject(BufferKind.IndirectBO) @Check("5 * 4") @Const @GLvoid ByteBuffer indirect); @Alternate("glDrawElementsIndirect") - void glDrawElementsIndirect(@GLenum int mode, @GLenum int type, @BufferObject(BufferKind.IndirectBO) @Check("5") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect); + void glDrawElementsIndirect(@GLenum int mode, @GLenum int type, @BufferObject(BufferKind.IndirectBO) @Check("5") @Const @GLvoid(TypeKind.INT) IntBuffer indirect); // --------------------------------------------------------------- // ----------------------[ ARB_gpu_shader5 ]---------------------- diff --git a/src/templates/org/lwjgl/opengl/GL43.java b/src/templates/org/lwjgl/opengl/GL43.java index 2aa2ebba..e25df91b 100644 --- a/src/templates/org/lwjgl/opengl/GL43.java +++ b/src/templates/org/lwjgl/opengl/GL43.java @@ -37,8 +37,8 @@ import org.lwjgl.util.generator.opengl.*; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; +import javax.lang.model.type.TypeKind; -import com.sun.mirror.type.PrimitiveType; public interface GL43 { @@ -549,7 +549,7 @@ public interface GL43 { @Alternate("glMultiDrawArraysIndirect") void glMultiDrawArraysIndirect(@GLenum int mode, - @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 4 : stride >> 2) * primcount") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect, + @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 4 : stride >> 2) * primcount") @Const @GLvoid(TypeKind.INT) IntBuffer indirect, @GLsizei int primcount, @GLsizei int stride); @@ -562,7 +562,7 @@ public interface GL43 { @Alternate("glMultiDrawElementsIndirect") void glMultiDrawElementsIndirect(@GLenum int mode, @GLenum int type, - @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 5 : stride >> 2) * primcount") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect, + @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 5 : stride >> 2) * primcount") @Const @GLvoid(TypeKind.INT) IntBuffer indirect, @GLsizei int primcount, @GLsizei int stride);