Mon, 23 Aug 2010 15:13:33 -0700
6976747: JCDiagnostic: replace "boolean mandatory" with new "Set<JCDiagnostic.Flag>"
Reviewed-by: mcimadamore
1 /*
2 * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.processing;
28 import com.sun.tools.javac.util.*;
29 import javax.annotation.processing.*;
30 import javax.lang.model.SourceVersion;
31 import javax.lang.model.element.NestingKind;
32 import javax.lang.model.element.Modifier;
33 import javax.lang.model.element.Element;
34 import java.util.*;
36 import java.io.Closeable;
37 import java.io.InputStream;
38 import java.io.OutputStream;
39 import java.io.FilterOutputStream;
40 import java.io.Reader;
41 import java.io.Writer;
42 import java.io.FilterWriter;
43 import java.io.PrintWriter;
44 import java.io.IOException;
46 import javax.tools.*;
47 import static java.util.Collections.*;
49 import javax.tools.JavaFileManager.Location;
50 import static javax.tools.StandardLocation.SOURCE_OUTPUT;
51 import static javax.tools.StandardLocation.CLASS_OUTPUT;
53 /**
54 * The FilerImplementation class must maintain a number of
55 * constraints. First, multiple attempts to open the same path within
56 * the same invocation of the tool results in an IOException being
57 * thrown. For example, trying to open the same source file twice:
58 *
59 * <pre>
60 * createSourceFile("foo.Bar")
61 * ...
62 * createSourceFile("foo.Bar")
63 * </pre>
64 *
65 * is disallowed as is opening a text file that happens to have
66 * the same name as a source file:
67 *
68 * <pre>
69 * createSourceFile("foo.Bar")
70 * ...
71 * createTextFile(SOURCE_TREE, "foo", new File("Bar"), null)
72 * </pre>
73 *
74 * <p>Additionally, creating a source file that corresponds to an
75 * already created class file (or vice versa) also results in an
76 * IOException since each type can only be created once. However, if
77 * the Filer is used to create a text file named *.java that happens
78 * to correspond to an existing class file, a warning is *not*
79 * generated. Similarly, a warning is not generated for a binary file
80 * named *.class and an existing source file.
81 *
82 * <p>The reason for this difference is that source files and class
83 * files are registered with the tool and can get passed on as
84 * declarations to the next round of processing. Files that are just
85 * named *.java and *.class are not processed in that manner; although
86 * having extra source files and class files on the source path and
87 * class path can alter the behavior of the tool and any final
88 * compile.
89 *
90 * <p><b>This is NOT part of any supported API.
91 * If you write code that depends on this, you do so at your own risk.
92 * This code and its internal interfaces are subject to change or
93 * deletion without notice.</b>
94 */
95 public class JavacFiler implements Filer, Closeable {
96 // TODO: Implement different transaction model for updating the
97 // Filer's record keeping on file close.
99 private static final String ALREADY_OPENED =
100 "Output stream or writer has already been opened.";
101 private static final String NOT_FOR_READING =
102 "FileObject was not opened for reading.";
103 private static final String NOT_FOR_WRITING =
104 "FileObject was not opened for writing.";
106 /**
107 * Wrap a JavaFileObject to manage writing by the Filer.
108 */
109 private class FilerOutputFileObject extends ForwardingFileObject<FileObject> {
110 private boolean opened = false;
111 private String name;
113 FilerOutputFileObject(String name, FileObject fileObject) {
114 super(fileObject);
115 this.name = name;
116 }
118 @Override
119 public synchronized OutputStream openOutputStream() throws IOException {
120 if (opened)
121 throw new IOException(ALREADY_OPENED);
122 opened = true;
123 return new FilerOutputStream(name, fileObject);
124 }
126 @Override
127 public synchronized Writer openWriter() throws IOException {
128 if (opened)
129 throw new IOException(ALREADY_OPENED);
130 opened = true;
131 return new FilerWriter(name, fileObject);
132 }
134 // Three anti-literacy methods
135 @Override
136 public InputStream openInputStream() throws IOException {
137 throw new IllegalStateException(NOT_FOR_READING);
138 }
140 @Override
141 public Reader openReader(boolean ignoreEncodingErrors) throws IOException {
142 throw new IllegalStateException(NOT_FOR_READING);
143 }
145 @Override
146 public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
147 throw new IllegalStateException(NOT_FOR_READING);
148 }
150 @Override
151 public boolean delete() {
152 return false;
153 }
154 }
156 private class FilerOutputJavaFileObject extends FilerOutputFileObject implements JavaFileObject {
157 private final JavaFileObject javaFileObject;
158 FilerOutputJavaFileObject(String name, JavaFileObject javaFileObject) {
159 super(name, javaFileObject);
160 this.javaFileObject = javaFileObject;
161 }
163 public JavaFileObject.Kind getKind() {
164 return javaFileObject.getKind();
165 }
167 public boolean isNameCompatible(String simpleName,
168 JavaFileObject.Kind kind) {
169 return javaFileObject.isNameCompatible(simpleName, kind);
170 }
172 public NestingKind getNestingKind() {
173 return javaFileObject.getNestingKind();
174 }
176 public Modifier getAccessLevel() {
177 return javaFileObject.getAccessLevel();
178 }
179 }
181 /**
182 * Wrap a JavaFileObject to manage reading by the Filer.
183 */
184 private class FilerInputFileObject extends ForwardingFileObject<FileObject> {
185 FilerInputFileObject(FileObject fileObject) {
186 super(fileObject);
187 }
189 @Override
190 public OutputStream openOutputStream() throws IOException {
191 throw new IllegalStateException(NOT_FOR_WRITING);
192 }
194 @Override
195 public Writer openWriter() throws IOException {
196 throw new IllegalStateException(NOT_FOR_WRITING);
197 }
199 @Override
200 public boolean delete() {
201 return false;
202 }
203 }
205 private class FilerInputJavaFileObject extends FilerInputFileObject implements JavaFileObject {
206 private final JavaFileObject javaFileObject;
207 FilerInputJavaFileObject(JavaFileObject javaFileObject) {
208 super(javaFileObject);
209 this.javaFileObject = javaFileObject;
210 }
212 public JavaFileObject.Kind getKind() {
213 return javaFileObject.getKind();
214 }
216 public boolean isNameCompatible(String simpleName,
217 JavaFileObject.Kind kind) {
218 return javaFileObject.isNameCompatible(simpleName, kind);
219 }
221 public NestingKind getNestingKind() {
222 return javaFileObject.getNestingKind();
223 }
225 public Modifier getAccessLevel() {
226 return javaFileObject.getAccessLevel();
227 }
228 }
231 /**
232 * Wrap a {@code OutputStream} returned from the {@code
233 * JavaFileManager} to properly register source or class files
234 * when they are closed.
235 */
236 private class FilerOutputStream extends FilterOutputStream {
237 String typeName;
238 FileObject fileObject;
239 boolean closed = false;
241 /**
242 * @param typeName name of class or {@code null} if just a
243 * binary file
244 */
245 FilerOutputStream(String typeName, FileObject fileObject) throws IOException {
246 super(fileObject.openOutputStream());
247 this.typeName = typeName;
248 this.fileObject = fileObject;
249 }
251 public synchronized void close() throws IOException {
252 if (!closed) {
253 closed = true;
254 /*
255 * If an IOException occurs when closing the underlying
256 * stream, still try to process the file.
257 */
259 closeFileObject(typeName, fileObject);
260 out.close();
261 }
262 }
263 }
265 /**
266 * Wrap a {@code Writer} returned from the {@code JavaFileManager}
267 * to properly register source or class files when they are
268 * closed.
269 */
270 private class FilerWriter extends FilterWriter {
271 String typeName;
272 FileObject fileObject;
273 boolean closed = false;
275 /**
276 * @param fileObject the fileObject to be written to
277 * @param typeName name of source file or {@code null} if just a
278 * text file
279 */
280 FilerWriter(String typeName, FileObject fileObject) throws IOException {
281 super(fileObject.openWriter());
282 this.typeName = typeName;
283 this.fileObject = fileObject;
284 }
286 public synchronized void close() throws IOException {
287 if (!closed) {
288 closed = true;
289 /*
290 * If an IOException occurs when closing the underlying
291 * Writer, still try to process the file.
292 */
294 closeFileObject(typeName, fileObject);
295 out.close();
296 }
297 }
298 }
300 JavaFileManager fileManager;
301 Log log;
302 Context context;
303 boolean lastRound;
305 private final boolean lint;
307 /**
308 * Logical names of all created files. This set must be
309 * synchronized.
310 */
311 private final Set<FileObject> fileObjectHistory;
313 /**
314 * Names of types that have had files created but not closed.
315 */
316 private final Set<String> openTypeNames;
318 /**
319 * Names of source files closed in this round. This set must be
320 * synchronized. Its iterators should preserve insertion order.
321 */
322 private Set<String> generatedSourceNames;
324 /**
325 * Names and class files of the class files closed in this round.
326 * This set must be synchronized. Its iterators should preserve
327 * insertion order.
328 */
329 private final Map<String, JavaFileObject> generatedClasses;
331 /**
332 * JavaFileObjects for source files closed in this round. This
333 * set must be synchronized. Its iterators should preserve
334 * insertion order.
335 */
336 private Set<JavaFileObject> generatedSourceFileObjects;
338 /**
339 * Names of all created source files. Its iterators should
340 * preserve insertion order.
341 */
342 private final Set<String> aggregateGeneratedSourceNames;
344 /**
345 * Names of all created class files. Its iterators should
346 * preserve insertion order.
347 */
348 private final Set<String> aggregateGeneratedClassNames;
351 JavacFiler(Context context) {
352 this.context = context;
353 fileManager = context.get(JavaFileManager.class);
355 log = Log.instance(context);
357 fileObjectHistory = synchronizedSet(new LinkedHashSet<FileObject>());
358 generatedSourceNames = synchronizedSet(new LinkedHashSet<String>());
359 generatedSourceFileObjects = synchronizedSet(new LinkedHashSet<JavaFileObject>());
361 generatedClasses = synchronizedMap(new LinkedHashMap<String, JavaFileObject>());
363 openTypeNames = synchronizedSet(new LinkedHashSet<String>());
365 aggregateGeneratedSourceNames = new LinkedHashSet<String>();
366 aggregateGeneratedClassNames = new LinkedHashSet<String>();
368 lint = (Options.instance(context)).lint("processing");
369 }
371 public JavaFileObject createSourceFile(CharSequence name,
372 Element... originatingElements) throws IOException {
373 return createSourceOrClassFile(true, name.toString());
374 }
376 public JavaFileObject createClassFile(CharSequence name,
377 Element... originatingElements) throws IOException {
378 return createSourceOrClassFile(false, name.toString());
379 }
381 private JavaFileObject createSourceOrClassFile(boolean isSourceFile, String name) throws IOException {
382 if (lint) {
383 int periodIndex = name.lastIndexOf(".");
384 if (periodIndex != -1) {
385 String base = name.substring(periodIndex);
386 String extn = (isSourceFile ? ".java" : ".class");
387 if (base.equals(extn))
388 log.warning("proc.suspicious.class.name", name, extn);
389 }
390 }
391 checkNameAndExistence(name, isSourceFile);
392 Location loc = (isSourceFile ? SOURCE_OUTPUT : CLASS_OUTPUT);
393 JavaFileObject.Kind kind = (isSourceFile ?
394 JavaFileObject.Kind.SOURCE :
395 JavaFileObject.Kind.CLASS);
397 JavaFileObject fileObject =
398 fileManager.getJavaFileForOutput(loc, name, kind, null);
399 checkFileReopening(fileObject, true);
401 if (lastRound)
402 log.warning("proc.file.create.last.round", name);
404 if (isSourceFile)
405 aggregateGeneratedSourceNames.add(name);
406 else
407 aggregateGeneratedClassNames.add(name);
408 openTypeNames.add(name);
410 return new FilerOutputJavaFileObject(name, fileObject);
411 }
413 public FileObject createResource(JavaFileManager.Location location,
414 CharSequence pkg,
415 CharSequence relativeName,
416 Element... originatingElements) throws IOException {
417 locationCheck(location);
419 String strPkg = pkg.toString();
420 if (strPkg.length() > 0)
421 checkName(strPkg);
423 FileObject fileObject =
424 fileManager.getFileForOutput(location, strPkg,
425 relativeName.toString(), null);
426 checkFileReopening(fileObject, true);
428 if (fileObject instanceof JavaFileObject)
429 return new FilerOutputJavaFileObject(null, (JavaFileObject)fileObject);
430 else
431 return new FilerOutputFileObject(null, fileObject);
432 }
434 private void locationCheck(JavaFileManager.Location location) {
435 if (location instanceof StandardLocation) {
436 StandardLocation stdLoc = (StandardLocation) location;
437 if (!stdLoc.isOutputLocation())
438 throw new IllegalArgumentException("Resource creation not supported in location " +
439 stdLoc);
440 }
441 }
443 public FileObject getResource(JavaFileManager.Location location,
444 CharSequence pkg,
445 CharSequence relativeName) throws IOException {
446 String strPkg = pkg.toString();
447 if (strPkg.length() > 0)
448 checkName(strPkg);
450 // TODO: Only support reading resources in selected output
451 // locations? Only allow reading of non-source, non-class
452 // files from the supported input locations?
453 FileObject fileObject = fileManager.getFileForOutput(location,
454 pkg.toString(),
455 relativeName.toString(),
456 null);
457 // If the path was already opened for writing, throw an exception.
458 checkFileReopening(fileObject, false);
459 return new FilerInputFileObject(fileObject);
460 }
462 private void checkName(String name) throws FilerException {
463 checkName(name, false);
464 }
466 private void checkName(String name, boolean allowUnnamedPackageInfo) throws FilerException {
467 if (!SourceVersion.isName(name) && !isPackageInfo(name, allowUnnamedPackageInfo)) {
468 if (lint)
469 log.warning("proc.illegal.file.name", name);
470 throw new FilerException("Illegal name " + name);
471 }
472 }
474 private boolean isPackageInfo(String name, boolean allowUnnamedPackageInfo) {
475 // Is the name of the form "package-info" or
476 // "foo.bar.package-info"?
477 final String PKG_INFO = "package-info";
478 int periodIndex = name.lastIndexOf(".");
479 if (periodIndex == -1) {
480 return allowUnnamedPackageInfo ? name.equals(PKG_INFO) : false;
481 } else {
482 // "foo.bar.package-info." illegal
483 String prefix = name.substring(0, periodIndex);
484 String simple = name.substring(periodIndex+1);
485 return SourceVersion.isName(prefix) && simple.equals(PKG_INFO);
486 }
487 }
489 private void checkNameAndExistence(String typename, boolean allowUnnamedPackageInfo) throws FilerException {
490 // TODO: Check if type already exists on source or class path?
491 // If so, use warning message key proc.type.already.exists
492 checkName(typename, allowUnnamedPackageInfo);
493 if (aggregateGeneratedSourceNames.contains(typename) ||
494 aggregateGeneratedClassNames.contains(typename)) {
495 if (lint)
496 log.warning("proc.type.recreate", typename);
497 throw new FilerException("Attempt to recreate a file for type " + typename);
498 }
499 }
501 /**
502 * Check to see if the file has already been opened; if so, throw
503 * an exception, otherwise add it to the set of files.
504 */
505 private void checkFileReopening(FileObject fileObject, boolean addToHistory) throws FilerException {
506 for(FileObject veteran : fileObjectHistory) {
507 if (fileManager.isSameFile(veteran, fileObject)) {
508 if (lint)
509 log.warning("proc.file.reopening", fileObject.getName());
510 throw new FilerException("Attempt to reopen a file for path " + fileObject.getName());
511 }
512 }
513 if (addToHistory)
514 fileObjectHistory.add(fileObject);
515 }
517 public boolean newFiles() {
518 return (!generatedSourceNames.isEmpty())
519 || (!generatedClasses.isEmpty());
520 }
522 public Set<String> getGeneratedSourceNames() {
523 return generatedSourceNames;
524 }
526 public Set<JavaFileObject> getGeneratedSourceFileObjects() {
527 return generatedSourceFileObjects;
528 }
530 public Map<String, JavaFileObject> getGeneratedClasses() {
531 return generatedClasses;
532 }
534 public void warnIfUnclosedFiles() {
535 if (!openTypeNames.isEmpty())
536 log.warning("proc.unclosed.type.files", openTypeNames.toString());
537 }
539 /**
540 * Update internal state for a new round.
541 */
542 public void newRound(Context context) {
543 this.context = context;
544 this.log = Log.instance(context);
545 clearRoundState();
546 }
548 void setLastRound(boolean lastRound) {
549 this.lastRound = lastRound;
550 }
552 public void close() {
553 clearRoundState();
554 // Cross-round state
555 fileObjectHistory.clear();
556 openTypeNames.clear();
557 aggregateGeneratedSourceNames.clear();
558 aggregateGeneratedClassNames.clear();
559 }
561 private void clearRoundState() {
562 generatedSourceNames.clear();
563 generatedSourceFileObjects.clear();
564 generatedClasses.clear();
565 }
567 /**
568 * Debugging function to display internal state.
569 */
570 public void displayState() {
571 PrintWriter xout = context.get(Log.outKey);
572 xout.println("File Object History : " + fileObjectHistory);
573 xout.println("Open Type Names : " + openTypeNames);
574 xout.println("Gen. Src Names : " + generatedSourceNames);
575 xout.println("Gen. Cls Names : " + generatedClasses.keySet());
576 xout.println("Agg. Gen. Src Names : " + aggregateGeneratedSourceNames);
577 xout.println("Agg. Gen. Cls Names : " + aggregateGeneratedClassNames);
578 }
580 public String toString() {
581 return "javac Filer";
582 }
584 /**
585 * Upon close, register files opened by create{Source, Class}File
586 * for annotation processing.
587 */
588 private void closeFileObject(String typeName, FileObject fileObject) {
589 /*
590 * If typeName is non-null, the file object was opened as a
591 * source or class file by the user. If a file was opened as
592 * a resource, typeName will be null and the file is *not*
593 * subject to annotation processing.
594 */
595 if ((typeName != null)) {
596 if (!(fileObject instanceof JavaFileObject))
597 throw new AssertionError("JavaFileOject not found for " + fileObject);
598 JavaFileObject javaFileObject = (JavaFileObject)fileObject;
599 switch(javaFileObject.getKind()) {
600 case SOURCE:
601 generatedSourceNames.add(typeName);
602 generatedSourceFileObjects.add(javaFileObject);
603 openTypeNames.remove(typeName);
604 break;
606 case CLASS:
607 generatedClasses.put(typeName, javaFileObject);
608 openTypeNames.remove(typeName);
609 break;
611 default:
612 break;
613 }
614 }
615 }
617 }