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.
This commit is contained in:
Ioannis Tsakpinis 2014-09-14 17:07:56 +03:00
parent 202ce1d522
commit 774bd17ece
42 changed files with 4014 additions and 3819 deletions

View File

@ -16,8 +16,13 @@
</target>
<!-- Compiles the Java generator source code -->
<target name="generators" description="Compiles the native method generators">
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" includes="org/lwjgl/util/generator/**.java" source="1.5" target="1.5" taskname="generator">
<target name="generators" description="Compiles the native method generators">
<mkdir dir="${lwjgl.src}/generated/"/>
<mkdir dir="${lwjgl.src.native}/generated/openal"/>
<mkdir dir="${lwjgl.src.native}/generated/opengl"/>
<mkdir dir="${lwjgl.src.native}/generated/opengles"/>
<mkdir dir="${lwjgl.src.native}/generated/opencl"/>
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" includes="org/lwjgl/util/generator/**.java" taskname="generator">
<include name="org/lwjgl/util/generator/openal/**.java"/>
<include name="org/lwjgl/util/generator/opengl/**.java"/>
<include name="org/lwjgl/util/generator/opengles/**.java"/>
@ -25,7 +30,7 @@
<compilerarg value="-Xlint:none"/>
</javac>
<!-- Compile helper classes used by the templates -->
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" source="1.5" target="1.5" taskname="generator">
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" source="1.7" taskname="generator">
<include name="org/lwjgl/PointerWrapper.java"/>
<include name="org/lwjgl/PointerBuffer.java"/>
<!-- OpenGL -->
@ -60,40 +65,48 @@
**************************************************************************** -->
<!-- Generate OpenAL -->
<target name="generate-openal" depends="generators" description="Generates java and native source for AL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.al}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/openal"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Atypemap=org.lwjgl.util.generator.openal.ALTypeMap"/>
<fileset dir="${lwjgl.src.templates.al}" includes="${openal-template-pattern}"/>
</apply>
<target name="generate-openal" depends="generators" description="Generates java and native source for AL">
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.al}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/openal"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Atypemap=org.lwjgl.util.generator.openal.ALTypeMap"/>
<src>
<fileset dir="${lwjgl.src.templates.al}">
<include name="${openal-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenAL [DEBUG] -->
<target name="generate-openal-debug" depends="generators" description="Generates java and native source for AL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.al}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/openal"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Atypemap=org.lwjgl.util.generator.openal.ALTypeMap"/>
<arg value="-Ageneratechecks"/>
<fileset dir="${lwjgl.src.templates.al}" includes="${openal-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.al}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/openal"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Atypemap=org.lwjgl.util.generator.openal.ALTypeMap"/>
<compilerarg value="-Ageneratechecks"/>
<src>
<fileset dir="${lwjgl.src.templates.al}">
<include name="${openal-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- ********************************************************************************
@ -104,86 +117,106 @@
<!-- Generate OpenGL -->
<target name="generate-opengl" depends="generators" description="Generates java and native source for GL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/opengl"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Acontextspecific"/>
<arg value="-Atypemap=org.lwjgl.util.generator.opengl.GLTypeMap"/>
<fileset dir="${lwjgl.src.templates.gl}" includes="${opengl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.gl}" fork="true" taskname="processorGL">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/opengl"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Atypemap=org.lwjgl.util.generator.opengl.GLTypeMap"/>
<compilerarg value="-Acontextspecific"/>
<src>
<fileset dir="${lwjgl.src.templates.gl}">
<include name="${opengl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL [DEBUG] -->
<target name="generate-opengl-debug" depends="generators" description="Generates debug java and native source for GL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/opengl"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Ageneratechecks"/>
<arg value="-Acontextspecific"/>
<arg value="-Atypemap=org.lwjgl.util.generator.opengl.GLTypeMap"/>
<fileset dir="${lwjgl.src.templates.gl}" includes="${opengl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.gl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/opengl"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Ageneratechecks"/>
<compilerarg value="-Acontextspecific"/>
<compilerarg value="-Atypemap=org.lwjgl.util.generator.opengl.GLTypeMap"/>
<src>
<fileset dir="${lwjgl.src.templates.gl}">
<include name="${opengl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL references -->
<target name="generate-opengl-references" depends="generators" description="Generates java and native source for GL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opengl.GLReferencesGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<fileset dir="${lwjgl.src.templates.gl}" includes="${opengl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.gl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opengl.GLReferencesGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<src>
<fileset dir="${lwjgl.src.templates.gl}">
<include name="${opengl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL context capabilities -->
<target name="generate-opengl-capabilities" depends="generators" description="Generates java and native source for GL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opengl.GLGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-Acontextspecific"/>
<fileset dir="${lwjgl.src.templates.gl}" includes="${opengl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.gl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opengl.GLGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-Acontextspecific"/>
<src>
<fileset dir="${lwjgl.src.templates.gl}">
<include name="${opengl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL context capabilities [DEBUG] -->
<target name="generate-opengl-capabilities-debug" depends="generators" description="Generates debug java and native source for GL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opengl.GLGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-Ageneratechecks"/>
<arg value="-Acontextspecific"/>
<fileset dir="${lwjgl.src.templates.gl}" includes="${opengl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.gl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opengl.GLGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-Ageneratechecks"/>
<compilerarg value="-Acontextspecific"/>
<src>
<fileset dir="${lwjgl.src.templates.gl}">
<include name="${opengl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- ********************************************************************************
@ -194,72 +227,88 @@
<!-- Generate OpenGL ES -->
<target name="generate-opengles" depends="generators" description="Generates java and native source for GL ES">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gles}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/opengles"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<!--<arg value="-Acontextspecific"/>-->
<arg value="-Atypemap=org.lwjgl.util.generator.opengl.GLESTypeMap"/>
<fileset dir="${lwjgl.src.templates.gles}" includes="${opengles-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.gles}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/opengles"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<!--<compilerarg value="-Acontextspecific"/>-->
<compilerarg value="-Atypemap=org.lwjgl.util.generator.opengl.GLESTypeMap"/>
<src>
<fileset dir="${lwjgl.src.templates.gles}">
<include name="${opengles-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL ES [DEBUG] -->
<target name="generate-opengles-debug" depends="generators" description="Generates debug java and native source for GL ES">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gles}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/opengles"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Ageneratechecks"/>
<!--<arg value="-Acontextspecific"/>-->
<arg value="-Atypemap=org.lwjgl.util.generator.opengl.GLESTypeMap"/>
<fileset dir="${lwjgl.src.templates.gles}" includes="${opengles-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.gles}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/opengles"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Ageneratechecks"/>
<!--<compilerarg value="-Acontextspecific"/>-->
<compilerarg value="-Atypemap=org.lwjgl.util.generator.opengl.GLESTypeMap"/>
<src>
<fileset dir="${lwjgl.src.templates.gles}">
<include name="${opengles-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL ES context capabilities -->
<target name="generate-opengles-capabilities" depends="generators" description="Generates java and native source for GL ES">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gles}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opengl.GLESGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<!--<arg value="-Acontextspecific"/>-->
<fileset dir="${lwjgl.src.templates.gles}" includes="${opengles-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.gles}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opengl.GLESGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<!--<compilerarg value="-Acontextspecific"/>-->
<src>
<fileset dir="${lwjgl.src.templates.gles}">
<include name="${opengles-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL ES context capabilities [DEBUG] -->
<target name="generate-opengles-capabilities-debug" depends="generators" description="Generates debug java and native source for GL ES">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gles}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opengl.GLESGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-Ageneratechecks"/>
<!--<arg value="-Acontextspecific"/>-->
<fileset dir="${lwjgl.src.templates.gles}" includes="${opengles-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.gles}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opengl.GLESGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-Ageneratechecks"/>
<!--<compilerarg value="-Acontextspecific"/>-->
<src>
<fileset dir="${lwjgl.src.templates.gles}">
<include name="${opengles-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- ********************************************************************************
@ -270,71 +319,87 @@
<!-- Generate OpenCL -->
<target name="generate-opencl" depends="generators" description="Generates java and native source for CL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.cl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/opencl"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Acontextspecific"/>
<arg value="-Atypemap=org.lwjgl.util.generator.opencl.CLTypeMap"/>
<fileset dir="${lwjgl.src.templates.cl}" includes="${opencl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.cl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/opencl"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Acontextspecific"/>
<compilerarg value="-Atypemap=org.lwjgl.util.generator.opencl.CLTypeMap"/>
<src>
<fileset dir="${lwjgl.src.templates.cl}">
<include name="${opencl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenCL [DEBUG] -->
<target name="generate-opencl-debug" depends="generators" description="Generates debug java and native source for CL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.cl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/opencl"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Ageneratechecks"/>
<arg value="-Acontextspecific"/>
<arg value="-Atypemap=org.lwjgl.util.generator.opencl.CLTypeMap"/>
<fileset dir="${lwjgl.src.templates.cl}" includes="${opencl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.cl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/opencl"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Ageneratechecks"/>
<compilerarg value="-Acontextspecific"/>
<compilerarg value="-Atypemap=org.lwjgl.util.generator.opencl.CLTypeMap"/>
<src>
<fileset dir="${lwjgl.src.templates.cl}">
<include name="${opencl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenCL capabilities -->
<target name="generate-opencl-capabilities" depends="generators" description="Generates capabilities for CL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.cl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opencl.CLGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-Acontextspecific"/>
<fileset dir="${lwjgl.src.templates.cl}" includes="${opencl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.cl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opencl.CLGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-Acontextspecific"/>
<src>
<fileset dir="${lwjgl.src.templates.cl}">
<include name="${opencl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenCL capabilities [DEBUG] -->
<target name="generate-opencl-capabilities-debug" depends="generators" description="Generates debug capabilities for CL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.cl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opencl.CLGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-Ageneratechecks"/>
<arg value="-Acontextspecific"/>
<fileset dir="${lwjgl.src.templates.cl}" includes="${opencl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" srcdir="${lwjgl.src.templates.cl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opencl.CLGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-Ageneratechecks"/>
<compilerarg value="-Acontextspecific"/>
<src>
<fileset dir="${lwjgl.src.templates.cl}">
<include name="${opencl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
</project>

View File

@ -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<Modifier> 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<Modifier> 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<FieldDeclaration> 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<? extends VariableElement> 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(";");
}
}
}

View File

@ -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 <elias_naur@users.sourceforge.net>
* @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<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver() || !first_round) {
System.exit(0);
return true;
}
Map<String, String> 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=<path>");
}
if (typemap_classname == null) {
throw new RuntimeException("No TypeMap class name specified with -Atypemap=<class-name>");
}
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<TypeElement> 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;
}
}

View File

@ -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 <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
public class GeneratorProcessorFactory implements AnnotationProcessorFactory, RoundCompleteListener {
private static boolean first_round = true;
// Process any set of annotations
private static final Collection<String> supportedAnnotations =
unmodifiableCollection(Arrays.asList("*"));
private static final Collection<String> supportedOptions =
unmodifiableCollection(Arrays.asList("-Atypemap", "-Ageneratechecks", "-Acontextspecific"));
public Collection<String> supportedAnnotationTypes() {
return supportedAnnotations;
}
public Collection<String> supportedOptions() {
return supportedOptions;
}
public void roundComplete(RoundCompleteEvent event) {
first_round = false;
}
public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> 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<String, String> 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=<class-name>");
if ( bin_path == null )
throw new RuntimeException("No path specified for the bin directory with -Abinpath=<path>");
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;
}
}
}

View File

@ -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 <elias_naur@users.sourceforge.net>
* @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<Void, Void> {
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<Modifier> 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<?extends Annotation> 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<Modifier> 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<AnnotationMirror> annotations, TypeMirror type_mirror) {
for (AnnotationMirror annotation : annotations) {
NativeType native_type_annotation = NativeTypeTranslator.getAnnotation(annotation, NativeType.class);
if (native_type_annotation != null) {
Class<? extends Annotation> 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<? extends Annotation> 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<? extends AnnotationMirror> annotations, TypeMirror type_mirror) {
for (AnnotationMirror annotation : annotations) {
NativeType native_type_annotation = NativeTypeTranslator.getAnnotation(annotation, NativeType.class);
if (native_type_annotation != null) {
Class<? extends Annotation> 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<? extends MethodDeclaration> 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<? extends ExecutableElement> 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<InterfaceType> 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 <jni.h>");
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<? extends TypeMirror> 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 <jni.h>");
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<? extends ExecutableElement> 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<? extends MethodDeclaration> 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;
}
}

View File

@ -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<Void, Void> {
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");
}
}

File diff suppressed because it is too large Load Diff

View File

@ -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 <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
* @version $Revision$ $Id$
*/
public class JavaTypeTranslator implements TypeVisitor {
private Class type;
public class JavaTypeTranslator extends SimpleTypeVisitor6<Void, Void> {
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");
}
}

View File

@ -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<ParameterDeclaration> params, Mode mode) {
for (ParameterDeclaration param : params) {
private static void generateParameters(PrintWriter writer, List<? extends VariableElement> 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<ParameterDeclaration> params) {
private static void generateCallParameters(PrintWriter writer, TypeMap type_map, List<? extends VariableElement> 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<ParameterDeclaration> params) {
for (ParameterDeclaration param : params) {
final Class java_type = Utils.getJavaType(param.getType());
private static void generateStringDeallocations(PrintWriter writer, List<? extends VariableElement> 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<ParameterDeclaration> params) {
for ( ParameterDeclaration param : params ) {
private static boolean hasPointerArrayInits(List<? extends VariableElement> 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<ParameterDeclaration> params) {
for ( ParameterDeclaration param : params ) {
private static void generatePointerArrayInits(TypeMap type_map, PrintWriter writer, List<? extends VariableElement> 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) ) {

View File

@ -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 <elias_naur@users.sourceforge.net>
* @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$
* <p/>
* A TypeVisitor that translates (annotated) TypeMirrors to
* native types
* A TypeVisitor that translates (annotated) TypeMirrors to native types
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
*/
public class NativeTypeTranslator implements TypeVisitor {
public class NativeTypeTranslator extends SimpleTypeVisitor6<Void, Void> {
private Collection<Class> native_types;
private boolean is_indirect;
private final Declaration declaration;
private final TypeMap type_map;
private Collection<Class> 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<Class>();
native_types.add(type_map.getStringArrayType());
} else if ( Buffer.class.isAssignableFrom(type) ) {
is_indirect = true;
native_types = new ArrayList<Class>();
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<? extends Annotation> getClassFromType(DeclaredType t) {
try {
return (Class<? extends Annotation>) Class.forName(t.toString());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public static Class<? extends Annotation> getClassFromType(DeclaredType t) {
try {
return (Class<? extends Annotation>)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<Class>();
native_types.add(type_map.getStringElementType());
} else if ( Buffer.class.equals(c) ) {
native_types = new ArrayList<Class>();
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<Class>();
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<Class>();
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 extends Annotation> T getAnnotation(AnnotationMirror annotation, Class<T> 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<Class> translateAnnotations() {
List<Class> 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 extends Annotation> T getAnnotation(AnnotationMirror annotation, Class<T> 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<Class> translateAnnotations() {
Collection<Class> result = new ArrayList<Class>();
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");
}
}

View File

@ -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<Void,Void> {
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");
}
}

View File

@ -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 <elias_naur@users.sourceforge.net>
* @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<? extends MethodDeclaration> 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<Platform> 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<? extends ExecutableElement> 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<Platform> 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<ParameterDeclaration> 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<? extends VariableElement> 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(",");
}
}
}

View File

@ -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<Void, Void> {
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");
}
}

View File

@ -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 <elias_naur@users.sourceforge.net>
* @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<ParameterDeclaration, TypeInfo> getDefaultTypeInfoMap(MethodDeclaration method) {
Map<ParameterDeclaration, TypeInfo> map = new HashMap<ParameterDeclaration, TypeInfo>();
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<TypeInfo> getTypeInfos(TypeMap type_map, Declaration param, TypeMirror decl_type) {
Collection<AnnotationMirror> annotations = Utils.getSortedAnnotations(param.getAnnotationMirrors());
Map<Class, TypeInfo> types = new HashMap<Class, TypeInfo>();
Collection<TypeInfo> multityped_result = new ArrayList<TypeInfo>();
boolean add_default_type = true;
for (AnnotationMirror annotation : annotations) {
NativeType native_type_annotation = NativeTypeTranslator.getAnnotation(annotation, NativeType.class);
if (native_type_annotation != null) {
Class<? extends Annotation> 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<TypeInfo> result = new ArrayList<TypeInfo>();
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<ParameterDeclaration, Collection<TypeInfo>> getTypeInfoMap(TypeMap type_map, MethodDeclaration method) {
Map<ParameterDeclaration, Collection<TypeInfo>> map = new HashMap<ParameterDeclaration, Collection<TypeInfo>>();
for (ParameterDeclaration param : method.getParameters()) {
Collection<TypeInfo> types = getTypeInfos(type_map, param, param.getType());
map.put(param, types);
}
return map;
}
public static Map<VariableElement, TypeInfo> getDefaultTypeInfoMap(ExecutableElement method) {
Map<VariableElement, TypeInfo> map = new HashMap<>();
for (VariableElement param : method.getParameters()) {
TypeInfo type_info = getDefaultTypeInfo(param.asType());
map.put(param, type_info);
}
return map;
}
public static Collection<Map<ParameterDeclaration, TypeInfo>> getTypeInfoCrossProduct(TypeMap type_map, MethodDeclaration method) {
Collection<ParameterDeclaration> parameter_collection = method.getParameters();
ParameterDeclaration[] parameters = new ParameterDeclaration[parameter_collection.size()];
parameter_collection.toArray(parameters);
Collection<Map<ParameterDeclaration, TypeInfo>> cross_product = new ArrayList<Map<ParameterDeclaration, TypeInfo>>();
getCrossProductRecursive(0, parameters, getTypeInfoMap(type_map, method),
new HashMap<ParameterDeclaration, TypeInfo>(), cross_product);
return cross_product;
}
private static Collection<TypeInfo> getTypeInfos(ProcessingEnvironment env, TypeMap type_map, VariableElement param) {
List<? extends AnnotationMirror> annotations = param.getAnnotationMirrors();
GLvoid void_annotation = param.getAnnotation(GLvoid.class);
private static void getCrossProductRecursive(int index, ParameterDeclaration[] parameters, Map<ParameterDeclaration,
Collection<TypeInfo>> typeinfos_map, Map<ParameterDeclaration, TypeInfo> current_instance,
Collection<Map<ParameterDeclaration, TypeInfo>> cross_product) {
if (index == parameters.length) {
cross_product.add(current_instance);
return;
}
ParameterDeclaration param = parameters[index];
Collection<TypeInfo> typeinfos = typeinfos_map.get(param);
if (typeinfos != null) {
for (TypeInfo typeinfo : typeinfos) {
Map<ParameterDeclaration, TypeInfo> instance = new HashMap<ParameterDeclaration, TypeInfo>(current_instance);
instance.put(param, typeinfo);
getCrossProductRecursive(index + 1, parameters, typeinfos_map, instance, cross_product);
}
}
}
Map<Class, TypeInfo> types = new HashMap<>();
Collection<TypeInfo> 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<? extends Annotation> 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<TypeInfo> result = new ArrayList<>();
result.add(default_type_info);
return result;
} else {
return multityped_result;
}
}
private static Map<VariableElement, Collection<TypeInfo>> getTypeInfoMap(ProcessingEnvironment env, TypeMap type_map, ExecutableElement method) {
Map<VariableElement, Collection<TypeInfo>> map = new HashMap<>();
for (VariableElement param : method.getParameters()) {
Collection<TypeInfo> types = getTypeInfos(env, type_map, param);
map.put(param, types);
}
return map;
}
public static Collection<Map<VariableElement, TypeInfo>> getTypeInfoCrossProduct(ProcessingEnvironment env, TypeMap type_map, ExecutableElement method) {
List<? extends VariableElement> parameter_collection = method.getParameters();
Collection<Map<VariableElement, TypeInfo>> cross_product = new ArrayList<>();
getCrossProductRecursive(0, parameter_collection, getTypeInfoMap(env, type_map, method),
new HashMap<VariableElement, TypeInfo>(), cross_product);
return cross_product;
}
private static void getCrossProductRecursive(int index, List<? extends VariableElement> parameters, Map<VariableElement, Collection<TypeInfo>> typeinfos_map, Map<VariableElement, TypeInfo> current_instance, Collection<Map<VariableElement, TypeInfo>> 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<TypeInfo> typeinfos = typeinfos_map.get(param);
if (typeinfos != null) {
for (TypeInfo typeinfo : typeinfos) {
Map<VariableElement, TypeInfo> instance = new HashMap<>(current_instance);
instance.put(param, typeinfo);
getCrossProductRecursive(index + 1, parameters, typeinfos_map, instance, cross_product);
}
}
}
}

View File

@ -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<? extends Annotation> native_type);
TypeKind getPrimitiveTypeFromNativeType(Class<? extends Annotation> native_type);
String getTypedefPostfix();
String getFunctionPrefix();
void printNativeIncludes(PrintWriter writer);
@ -63,7 +64,7 @@ public interface TypeMap {
Class[] getValidAnnotationTypes(Class type);
Class<? extends Annotation> getVoidType();
String translateAnnotation(Class<? extends Annotation> annotation_type);
Class getNativeTypeFromPrimitiveType(PrimitiveType.Kind kind);
Class getNativeTypeFromPrimitiveType(TypeKind kind);
String getAutoTypeFromAnnotation(AnnotationMirror annotation);
Class<? extends Annotation> getInverseType(Class<? extends Annotation> type);
Signedness getSignednessFromType(Class<? extends Annotation> type);

View File

@ -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<ParameterDeclaration> params) {
private static void generateNativeTypedefsParameters(TypeMap type_map, PrintWriter writer, Collection<? extends VariableElement> 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<? extends MethodDeclaration> methods) {
for (MethodDeclaration method : methods) {
public static void generateNativeTypedefs(TypeMap type_map, PrintWriter writer, Collection<? extends ExecutableElement> methods) {
for (ExecutableElement method : methods) {
if ( method.getAnnotation(Alternate.class) == null && method.getAnnotation(Reuse.class) == null )
generateNativeTypedefs(type_map, writer, method);
}

View File

@ -36,423 +36,474 @@ package org.lwjgl.util.generator;
* Various utility methods to the generator.
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @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<AnnotationMirror> {
private static class AnnotationMirrorComparator implements Comparator<AnnotationMirror> {
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<AnnotationMirror> getSortedAnnotations(Collection<AnnotationMirror> annotations) {
List<AnnotationMirror> annotation_list = new ArrayList<AnnotationMirror>(annotations);
Collections.sort(annotation_list, new AnnotationMirrorComparator());
return annotation_list;
}
public static List<AnnotationMirror> getSortedAnnotations(List<? extends AnnotationMirror> annotations) {
List<AnnotationMirror> 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 * <p>");
}
if (overloadsComment != null) {
writer.println("\t * " + overloadsComment);
writer.println("\t * <p>");
}
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 + " * <p>");
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 + " * <p>");
}
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<VariableElement> getFields(TypeElement d) {
Collection<VariableElement> fields = ElementFilter.fieldsIn(new HashSet(d.getEnclosedElements()));
return fields;
}
public static Collection<ExecutableElement> getMethods(TypeElement d) {
Collection<ExecutableElement> fields = ElementFilter.methodsIn(new HashSet(d.getEnclosedElements()));
return fields;
}
}

View File

@ -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<Class, PrimitiveType.Kind> native_types_to_primitive;
private static final Map<Class, TypeKind> native_types_to_primitive;
static {
native_types_to_primitive = new HashMap<Class, PrimitiveType.Kind>();
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<? extends Annotation> getStringElementType() {
return ALubyte.class;
}
@Override
public Class<? extends Annotation> getStringArrayType() {
return ALubyte.class;
}
@Override
public Class<? extends Annotation> 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<? extends Annotation> getVoidType() {
return ALvoid.class;
}
@Override
public Class<? extends Annotation> 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;
}

View File

@ -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<TypeDeclaration> interface_decls) {
writer.println("\tprivate " + CLGeneratorProcessorFactory.CLCAPS_CLASS_NAME + "() {}");
writer.println();
writer.println("\tstatic {");
static void generateConstructor(ProcessingEnvironment env, final PrintWriter writer, final Set<? extends TypeElement> 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<? extends MethodDeclaration> methods = d.getMethods().iterator();
if ( !methods.hasNext() )
return;
static void generateExtensionChecks(ProcessingEnvironment env, final PrintWriter writer, TypeElement d) {
Iterator<? extends ExecutableElement> 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");
}
}
}
}

View File

@ -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<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver() || !first_round) {
System.exit(0);
return true;
}
try {
Set<TypeElement> 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<TypeElement> 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<TypeElement> templates, final Class<? extends Annotation> capsType, final String capsName, final Class<? extends PointerWrapper> 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();
}
}

View File

@ -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<String> supportedAnnotations = unmodifiableCollection(Arrays.asList("*"));
public Collection<String> supportedAnnotationTypes() {
return supportedAnnotations;
}
public Collection<String> supportedOptions() {
return unmodifiableCollection(Arrays.asList("-Acontextspecific"));
}
public void roundComplete(RoundCompleteEvent event) {
first_round = false;
}
public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> 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<TypeDeclaration> 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<? extends Annotation> capsType, final String capsName, final Class<? extends PointerWrapper> 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<TypeDeclaration> 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();
}
}
}

View File

@ -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<TypeDeclaration> templates,
static void generateConstructor(ProcessingEnvironment env, final PrintWriter writer, final Set<? extends TypeElement> templates,
final Class<? extends Annotation> capsType, final String capsName,
final Class<? extends PointerWrapper> objectType, final String objectName) {
writer.println("\tpublic " + capsName + "(final " + objectType.getSimpleName() + ' ' + objectName + ") {");
@ -103,11 +102,11 @@ public class CLPDCapabilitiesGenerator {
writer.println("\t\tfinal Set<String> 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<TypeDeclaration> templates, final Class<? extends Annotation> capsType) {
public static void generateToString(final PrintWriter writer, final Set<? extends TypeElement> templates, final Class<? extends Annotation> 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();");

View File

@ -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<Class, PrimitiveType.Kind> native_types_to_primitive;
private static final Map<Class, TypeKind> native_types_to_primitive;
static {
native_types_to_primitive = new HashMap<Class, PrimitiveType.Kind>();
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<? extends Annotation> getVoidType() {
return cl_void.class;
}
@Override
public Class<? extends Annotation> getStringElementType() {
return cl_char.class;
}
@Override
public Class<? extends Annotation> getStringArrayType() {
return cl_char.class;
}
@Override
public Class<? extends Annotation> 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<? extends Annotation> getInverseType(Class type) {
return null;
}
@Override
public String getAutoTypeFromAnnotation(AnnotationMirror annotation) {
return null;
}

View File

@ -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;
}

View File

@ -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<InterfaceType> super_interfaces = d.getSuperinterfaces();
public static void generateSuperClassAdds(PrintWriter writer, TypeElement d, ProcessingEnvironment env) {
List<? extends TypeMirror> 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<InterfaceType> super_interfaces = d.getSuperinterfaces();
if ( super_interfaces.size() > 1 )
List<? extends TypeMirror> 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<? extends MethodDeclaration> methods = d.getMethods().iterator();
public static void generateAddressesInitializers(ProcessingEnvironment env, PrintWriter writer, TypeElement d) {
Iterator<? extends ExecutableElement> 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()) + ";");
}
}

View File

@ -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<InterfaceType> super_interfaces = d.getSuperinterfaces();
public static void generateSuperClassAdds(PrintWriter writer, TypeElement d, ProcessingEnvironment env) {
List<? extends TypeMirror> 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<InterfaceType> super_interfaces = d.getSuperinterfaces();
List<? extends TypeMirror> 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<? extends MethodDeclaration> methods = d.getMethods().iterator();
public static void generateAddressesInitializers(ProcessingEnvironment env, PrintWriter writer, TypeElement d) {
Iterator<? extends ExecutableElement> 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()) + ";");
}
}

View File

@ -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 <elias_naur@users.sourceforge.net>
* @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<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver() || !first_round) {
System.exit(0);
return true;
}
Map<String, String> 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<TypeElement> 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();
}
}

View File

@ -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 <elias_naur@users.sourceforge.net>
* @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<String> supportedAnnotations =
unmodifiableCollection(Arrays.asList("*"));
public Collection<String> supportedAnnotationTypes() {
return supportedAnnotations;
}
public Collection<String> supportedOptions() {
return unmodifiableCollection(Arrays.asList("-Acontextspecific", "-Ageneratechecks"));
}
public void roundComplete(RoundCompleteEvent event) {
first_round = false;
}
public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> 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<String, String> 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<TypeDeclaration> 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();
}
}
}

View File

@ -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<Class<? extends Annotation>, PrimitiveType.Kind> native_types_to_primitive;
private static final Map<Class<? extends Annotation>, TypeKind> native_types_to_primitive;
static {
native_types_to_primitive = new HashMap<Class<? extends Annotation>, 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<? extends Annotation> native_type) {
PrimitiveType.Kind kind = native_types_to_primitive.get(native_type);
@Override
public TypeKind getPrimitiveTypeFromNativeType(Class<? extends Annotation> 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<? extends Annotation> 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<? extends Annotation> getNativeTypeFromPrimitiveType(PrimitiveType.Kind kind) {
@Override
public Class<? extends Annotation> getNativeTypeFromPrimitiveType(TypeKind kind) {
Class<? extends Annotation> type;
switch ( kind ) {
case INT:
@ -181,18 +188,22 @@ public class GLESTypeMap implements TypeMap {
return type;
}
@Override
public Class<? extends Annotation> getVoidType() {
return GLvoid.class;
}
@Override
public Class<? extends Annotation> getStringElementType() {
return GLubyte.class;
}
@Override
public Class<? extends Annotation> getStringArrayType() {
return GLchar.class;
}
@Override
public Class<? extends Annotation> 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<? extends Annotation> getInverseType(Class<? extends Annotation> 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) )

View File

@ -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 <elias_naur@users.sourceforge.net>
* @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<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver() || !first_round) {
System.exit(0);
return true;
}
Map<String, String> 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<TypeElement> 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();
}
}

View File

@ -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 <elias_naur@users.sourceforge.net>
* @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<String> supportedAnnotations =
unmodifiableCollection(Arrays.asList("*"));
public Collection<String> supportedAnnotationTypes() {
return supportedAnnotations;
}
public Collection<String> supportedOptions() {
return unmodifiableCollection(Arrays.asList("-Acontextspecific", "-Ageneratechecks"));
}
public void roundComplete(RoundCompleteEvent event) {
first_round = false;
}
public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> 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<String, String> 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<TypeDeclaration> 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();
}
}
}

View File

@ -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 <elias_naur@users.sourceforge.net>
* @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<? extends TypeElement> 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<TypeElement> 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();
}
}

View File

@ -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 <elias_naur@users.sourceforge.net>
* @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<String> supportedAnnotations =
unmodifiableCollection(Arrays.asList("*"));
public Collection<String> supportedAnnotationTypes() {
return supportedAnnotations;
}
public Collection<String> supportedOptions() {
return emptyList();
}
public void roundComplete(RoundCompleteEvent event) {
first_round = false;
}
public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> 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<TypeDeclaration> 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();
}
}
}

View File

@ -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 <elias_naur@users.sourceforge.net>
* @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<Class, PrimitiveType.Kind> native_types_to_primitive;
private static final Map<Class, TypeKind> native_types_to_primitive;
static {
native_types_to_primitive = new HashMap<Class, PrimitiveType.Kind>();
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<? extends Annotation> getVoidType() {
return GLvoid.class;
}
@Override
public Class<? extends Annotation> getVoidType() {
return GLvoid.class;
}
public Class<? extends Annotation> getStringElementType() {
return GLubyte.class;
}
@Override
public Class<? extends Annotation> getStringElementType() {
return GLubyte.class;
}
public Class<? extends Annotation> getStringArrayType() {
return GLchar.class;
}
@Override
public Class<? extends Annotation> getStringArrayType() {
return GLchar.class;
}
public Class<? extends Annotation> getByteBufferArrayType() {
return GLchar.class;
}
@Override
public Class<? extends Annotation> 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<? extends Annotation> 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<? extends Annotation> 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;
}
}
}

View File

@ -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;
}

View File

@ -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) {

View File

@ -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);

View File

@ -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);
}

View File

@ -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);

View File

@ -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);

View File

@ -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 ]----------------------

View File

@ -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);