GlueGen v2.6.0-rc-20250712
GlueGen, Native Binding Generator for Java™ (public API).
CStructAnnotationProcessor.java
Go to the documentation of this file.
1/*
2 * Copyright (c) 2010, Michael Bien. All rights reserved.
3 * Copyright (c) 2013 JogAmp Community. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of Michael Bien nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL Michael Bien BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28package com.jogamp.gluegen.structgen;
29
30import com.jogamp.common.util.PropertyAccess;
31import com.jogamp.gluegen.CCodeUnit;
32import com.jogamp.gluegen.GlueGen;
33import com.jogamp.gluegen.JavaCodeUnit;
34import com.jogamp.gluegen.JavaEmitter;
35
36import java.io.BufferedReader;
37import java.io.File;
38import java.io.FileNotFoundException;
39import java.io.FileReader;
40import java.io.FileWriter;
41import java.io.IOException;
42import java.io.PrintWriter;
43import java.io.Reader;
44import java.util.ArrayList;
45import java.util.HashSet;
46import java.util.List;
47import java.util.Set;
48
49import javax.annotation.processing.AbstractProcessor;
50import javax.annotation.processing.Filer;
51import javax.annotation.processing.Messager;
52import javax.annotation.processing.ProcessingEnvironment;
53import javax.annotation.processing.RoundEnvironment;
54import javax.annotation.processing.SupportedAnnotationTypes;
55import javax.annotation.processing.SupportedSourceVersion;
56import javax.lang.model.SourceVersion;
57import javax.lang.model.element.Element;
58import javax.lang.model.element.TypeElement;
59import javax.lang.model.util.Elements;
60import javax.tools.Diagnostic.Kind;
61import javax.tools.FileObject;
62import javax.tools.StandardLocation;
63
64import jogamp.common.Debug;
65
66/**
67 * <p>
68 * If the <i>header file</i> is absolute, the <i>root path</i> is the parent folder of the folder containing the package source, i.e.:
69 * <pre>
70 * Header: /gluegen/src/junit/com/jogamp/test/structgen/TestStruct01.h
71 * Root: /gluegen/src/junit/..
72 * Root: /gluegen/src
73 * </pre>
74 * Otherwise the <i>user.dir</i> is being used as the <i>root path</i>
75 * and the relative <i>header file</i> is appended to it.
76 * </p>
77 * The property <code>jogamp.gluegen.structgen.output</code> allows setting a default <i>outputPath</i>
78 * for the generated sources, if the {@link ProcessingEnvironment}'s <code>structgen.output</code> option is not set.
79 * <p>
80 * If the <i>outputPath</i> is relative, it is appended to the <i>root path</i>,
81 * otherwise it is taken as-is.
82 * </p>
83 * <p>
84 * User can enable DEBUG while defining property <code>jogamp.gluegen.structgen.debug</code>.
85 * </p>
86 *
87 * @author Michael Bien, et al.
88 */
89@SupportedAnnotationTypes(value = {"com.jogamp.gluegen.structgen.CStruct", "com.jogamp.gluegen.structgen.CStructs"})
90@SupportedSourceVersion(SourceVersion.RELEASE_11)
91public class CStructAnnotationProcessor extends AbstractProcessor {
92 private static final String DEFAULT = "_default_";
93 static final boolean DEBUG;
94
95 static {
96 Debug.initSingleton();
97 DEBUG = PropertyAccess.isPropertyDefined("jogamp.gluegen.structgen.debug", true);
98 }
99
100 private static final String STRUCTGENOUTPUT_OPTION = "structgen.output";
101 private static final String STRUCTGENPRAGMA_ONCE = "structgen.enable.pragma.once";
102 private static final String STRUCTGENOUTPUT = PropertyAccess.getProperty("jogamp.gluegen."+STRUCTGENOUTPUT_OPTION, true, "gensrc");
103 private static final String STRUCTGENPRAGMAONCE = PropertyAccess.getProperty("jogamp.gluegen."+STRUCTGENPRAGMA_ONCE, true, "true");
104
105 private Filer filer;
106 private Messager messager;
107 private Elements eltUtils;
108 private String outputPath;
109 private boolean enablePragmaOnce;
110
111 private final static Set<String> generatedStructs = new HashSet<String>();
112
113
114 @Override
115 public void init(final ProcessingEnvironment processingEnv) {
116 super.init(processingEnv);
117
118 filer = processingEnv.getFiler();
119 messager = processingEnv.getMessager();
120 eltUtils = processingEnv.getElementUtils();
121
122 outputPath = processingEnv.getOptions().get(STRUCTGENOUTPUT_OPTION);
123 outputPath = outputPath == null ? STRUCTGENOUTPUT : outputPath;
124
125 final String enablePragmaOnceOpt = processingEnv.getOptions().get(STRUCTGENPRAGMAONCE);
126 enablePragmaOnce = Boolean.parseBoolean(enablePragmaOnceOpt == null ? STRUCTGENPRAGMAONCE : enablePragmaOnceOpt);
127 }
128
129 private File locateSource(final String packageName, final String relativeName) {
130 try {
131 if( DEBUG ) {
132 System.err.println("CStruct.locateSource.0: p "+packageName+", r "+relativeName);
133 }
134 final FileObject h = filer.getResource(StandardLocation.SOURCE_PATH, packageName, relativeName);
135 if( DEBUG ) {
136 System.err.println("CStruct.locateSource.1: h "+h.toUri());
137 }
138 final File f = new File( h.toUri().getPath() ); // URI is incomplete (no scheme), hence use path only!
139 if( f.exists() ) {
140 return f;
141 }
142 } catch (final IOException e) {
143 if(DEBUG) {
144 System.err.println("Caught "+e.getClass().getSimpleName()+": "+e.getMessage()); /* e.printStackTrace(); */
145 }
146 }
147 return null;
148 }
149
150 @Override
151 public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment env) {
152 final String user_dir = System.getProperty("user.dir");
153
154 final Set<? extends Element> cStructsElements = env.getElementsAnnotatedWith(CStructs.class);
155 for (final Element structsElement : cStructsElements) {
156 final String packageName = eltUtils.getPackageOf(structsElement).toString();
157 final CStructs cstructs = structsElement.getAnnotation(CStructs.class);
158 if( null != cstructs ) {
159 final CStruct[] cstructArray = cstructs.value();
160 for(final CStruct cstruct : cstructArray) {
161 processCStruct(cstruct, structsElement, packageName, user_dir);
162 }
163 }
164 }
165
166 final Set<? extends Element> cStructElements = env.getElementsAnnotatedWith(CStruct.class);
167 for (final Element structElement : cStructElements) {
168 final String packageName = eltUtils.getPackageOf(structElement).toString();
169 final CStruct cstruct = structElement.getAnnotation(CStruct.class);
170 if( null != cstruct ) {
171 processCStruct(cstruct, structElement, packageName, user_dir);
172 }
173 }
174 return true;
175 }
176
177 private void processCStruct(final CStruct struct, final Element element, final String packageName, final String user_dir) {
178 try {
179 final String headerRelPath = struct.header();
180 final Element enclElement = element.getEnclosingElement();
181 final boolean isPackageOrType = null == enclElement;
182
183 System.err.println("CStruct: "+struct+", package "+packageName+", header "+headerRelPath);
184 if(DEBUG) {
185 System.err.println("CStruct.0: user.dir: "+user_dir);
186 System.err.println("CStruct.0: element: "+element+", .simpleName "+element.getSimpleName());
187 System.err.print("CStruct.0: isPackageOrType "+isPackageOrType+", enclElement: "+enclElement);
188 if( !isPackageOrType ) {
189 if(!enclElement.toString().equals("unnamed module"))
190 System.err.println(", .simpleName "+enclElement.getSimpleName()+", .package "+eltUtils.getPackageOf(enclElement).toString());
191 else
192 System.err.println(", .simpleName "+enclElement.getSimpleName()+", .package <unnamed modules have no package>");
193 } else {
194 System.err.println("");
195 }
196 }
197 if( isPackageOrType && struct.name().equals(DEFAULT) ) {
198 throw new IllegalArgumentException("CStruct annotation on package or type must have name specified: "+struct+" @ "+element);
199 }
200
201 final File headerFile;
202 {
203 File f = locateSource(packageName, headerRelPath);
204 if( null == f ) {
205 f = locateSource("", headerRelPath);
206 if( null == f ) {
207 // bail out
208 throw new RuntimeException("Could not locate header "+headerRelPath+", package "+packageName);
209 }
210 }
211 headerFile = f;
212 }
213
214 final String rootOut, headerParent;
215 {
216 final String root0 = headerFile.getAbsolutePath();
217 headerParent = root0.substring(0, root0.length()-headerFile.getName().length()-1);
218 rootOut = headerParent.substring(0, headerParent.length()-packageName.length()) + "..";
219 }
220 System.err.println("CStruct: "+headerFile+", abs: "+headerFile.isAbsolute()+", headerParent "+headerParent+", rootOut "+rootOut+", enablePragmaOnce "+enablePragmaOnce);
221
222 generateStructBinding(element, struct, isPackageOrType, rootOut, packageName, headerFile, headerParent);
223 } catch (final IOException ex) {
224 throw new RuntimeException("IOException while processing!", ex);
225 }
226 }
227
228 private void generateStructBinding(final Element element, final CStruct struct, final boolean isPackageOrType, final String rootOut, final String pakage, final File header, final String headerParent) throws IOException {
229 final String declaredType = element.asType().toString();
230 final boolean useStructName = !struct.name().equals(DEFAULT);
231 final String structName = useStructName ? struct.name() : declaredType;
232 final boolean useJavaName = !struct.jname().equals(DEFAULT);
233
234 final String finalType = useJavaName ? struct.jname() : ( !isPackageOrType ? declaredType : structName );
235 System.err.println("CStruct: Generating struct accessor for struct: "+structName+" -> "+finalType+" [struct.name "+struct.name()+", struct.jname "+struct.jname()+", declaredType "+declaredType+"]");
236 if( generatedStructs.contains(finalType) ) {
237 messager.printMessage(Kind.NOTE, "struct "+structName+" already defined elsewhere, skipping.", element);
238 return;
239 }
240
241 final boolean outputDirAbs;
242 {
243 final File outputDirFile = new File(outputPath);
244 outputDirAbs = outputDirFile.isAbsolute();
245 }
246 final String outputPath1 = outputDirAbs ? outputPath : rootOut + File.separator + outputPath;
247 final String config = outputPath1 + File.separator + header.getName() + ".cfg";
248 final File configFile = new File(config);
249 if(DEBUG) {
250 System.err.println("CStruct: OutputDir: "+outputPath+", is-abs "+outputDirAbs);
251 System.err.println("CStruct: OutputPath: "+outputPath1);
252 System.err.println("CStruct: ConfigFile: "+configFile);
253 }
254
255 FileWriter writer = null;
256 try{
257 writer = new FileWriter(configFile);
258 writer.write("Package "+pakage+"\n");
259 writer.write("EmitStruct "+structName+"\n");
260 if( !useJavaName && (finalType != structName) ) {
261 // We allow renaming the structType to the element's declaredType (FIELD annotation only)
262 writer.write("RenameJavaType " + struct.name()+" " + declaredType +"\n");
263 }
264 } finally {
265 if( null != writer ) {
266 writer.close();
267 }
268 }
269 final List<String> cfgFiles = new ArrayList<String>();
270 cfgFiles.add(config);
271 final List<String> includePaths = new ArrayList<String>();
272 includePaths.add(headerParent);
273 includePaths.add(outputPath1);
274 final Reader reader;
275 final String filename = header.getPath();
276 try {
277 reader = new BufferedReader(new FileReader(filename));
278 } catch (final FileNotFoundException ex) {
279 throw new RuntimeException("input file not found", ex);
280 }
281 if( DEBUG ) {
282 GlueGen.setDebug(true);
283 }
284 new GlueGen().run(reader, filename, AnnotationProcessorJavaStructEmitter.class,
285 includePaths, cfgFiles, outputPath1, false /* copyCPPOutput2Stderr */,
286 enablePragmaOnce /* enablePragmaOnce */, false /* preserveGeneratedCPP */);
287 configFile.delete();
288 generatedStructs.add(finalType);
289 }
290
292
293 private boolean filter(final String simpleClassName) {
294 if( generatedStructs.contains(simpleClassName) ) {
295 System.err.println("skipping -> " + simpleClassName);
296 return false;
297 }
298
299 // look for recursive generated structs... keep it DRY
300 if( !simpleClassName.endsWith("32") &&
301 !simpleClassName.endsWith("64") ) {
302 System.err.println("generating -> " + simpleClassName);
303 generatedStructs.add(simpleClassName);
304 }
305 return true;
306 }
307
308 @Override
309 protected CCodeUnit openCUnit(final String filename, final String cUnitName) throws IOException {
310 if( !filter(cUnitName) ) {
311 return null;
312 }
313 return super.openCUnit(filename, cUnitName);
314 }
315
316 /**
317 * @param filename the class's full filename to open w/ write access
318 * @param packageName the package name of the class
319 * @param simpleClassName the simple class name, i.e. w/o package name or c-file basename
320 * @param generator informal optional object that is creating this unit, used to be mentioned in a warning message if not null.
321 * @throws IOException
322 */
323 @Override
324 protected JavaCodeUnit openJavaUnit(final String filename, final String packageName, final String simpleClassName) throws IOException {
325 if( !filter(simpleClassName) ) {
326 return null;
327 }
328 return super.openJavaUnit(filename, packageName, simpleClassName);
329 }
330 }
331
332}
Helper routines for accessing properties.
static final boolean isPropertyDefined(final String property, final boolean jnlpAlias)
static final String getProperty(final String propertyKey, final boolean jnlpAlias)
Query the property with the name propertyKey.
C code unit (a generated C source file), covering multiple FunctionEmitter allowing to unify output,...
Definition: CCodeUnit.java:37
Java code unit (a generated Java source file), covering multiple FunctionEmitter allowing to unify ou...
JavaCodeUnit openJavaUnit(final String filename, final String packageName, final String simpleClassName)
boolean process(final Set<? extends TypeElement > annotations, final RoundEnvironment env)
void init(final ProcessingEnvironment processingEnv)
String name() default "_default_"
The name of the struct.
String jname() default "_default_"
The optional java name of the struct.
String header()
Relative path to the header file.
Multiple CStruct elements.
Definition: CStructs.java:40
CStruct[] value()
Multiple CStruct elements.