src/share/classes/com/sun/tools/javac/processing/JavacFiler.java

Tue, 28 Dec 2010 15:54:52 -0800

author
ohair
date
Tue, 28 Dec 2010 15:54:52 -0800
changeset 798
4868a36f6fd8
parent 700
7b413ac1a720
child 1092
826ae6a2f27d
permissions
-rw-r--r--

6962318: Update copyright year
Reviewed-by: xdono

     1 /*
     2  * Copyright (c) 2005, 2010, 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 java.io.Closeable;
    29 import java.io.FileNotFoundException;
    30 import java.io.InputStream;
    31 import java.io.OutputStream;
    32 import java.io.FilterOutputStream;
    33 import java.io.Reader;
    34 import java.io.Writer;
    35 import java.io.FilterWriter;
    36 import java.io.PrintWriter;
    37 import java.io.IOException;
    38 import java.util.*;
    40 import static java.util.Collections.*;
    42 import javax.annotation.processing.*;
    43 import javax.lang.model.SourceVersion;
    44 import javax.lang.model.element.NestingKind;
    45 import javax.lang.model.element.Modifier;
    46 import javax.lang.model.element.Element;
    47 import javax.tools.*;
    48 import javax.tools.JavaFileManager.Location;
    50 import static javax.tools.StandardLocation.SOURCE_OUTPUT;
    51 import static javax.tools.StandardLocation.CLASS_OUTPUT;
    53 import com.sun.tools.javac.code.Lint;
    54 import com.sun.tools.javac.util.*;
    56 import static com.sun.tools.javac.code.Lint.LintCategory.PROCESSING;
    58 /**
    59  * The FilerImplementation class must maintain a number of
    60  * constraints.  First, multiple attempts to open the same path within
    61  * the same invocation of the tool results in an IOException being
    62  * thrown.  For example, trying to open the same source file twice:
    63  *
    64  * <pre>
    65  * createSourceFile("foo.Bar")
    66  * ...
    67  * createSourceFile("foo.Bar")
    68  * </pre>
    69  *
    70  * is disallowed as is opening a text file that happens to have
    71  * the same name as a source file:
    72  *
    73  * <pre>
    74  * createSourceFile("foo.Bar")
    75  * ...
    76  * createTextFile(SOURCE_TREE, "foo", new File("Bar"), null)
    77  * </pre>
    78  *
    79  * <p>Additionally, creating a source file that corresponds to an
    80  * already created class file (or vice versa) also results in an
    81  * IOException since each type can only be created once.  However, if
    82  * the Filer is used to create a text file named *.java that happens
    83  * to correspond to an existing class file, a warning is *not*
    84  * generated.  Similarly, a warning is not generated for a binary file
    85  * named *.class and an existing source file.
    86  *
    87  * <p>The reason for this difference is that source files and class
    88  * files are registered with the tool and can get passed on as
    89  * declarations to the next round of processing.  Files that are just
    90  * named *.java and *.class are not processed in that manner; although
    91  * having extra source files and class files on the source path and
    92  * class path can alter the behavior of the tool and any final
    93  * compile.
    94  *
    95  * <p><b>This is NOT part of any supported API.
    96  * If you write code that depends on this, you do so at your own risk.
    97  * This code and its internal interfaces are subject to change or
    98  * deletion without notice.</b>
    99  */
   100 public class JavacFiler implements Filer, Closeable {
   101     // TODO: Implement different transaction model for updating the
   102     // Filer's record keeping on file close.
   104     private static final String ALREADY_OPENED =
   105         "Output stream or writer has already been opened.";
   106     private static final String NOT_FOR_READING =
   107         "FileObject was not opened for reading.";
   108     private static final String NOT_FOR_WRITING =
   109         "FileObject was not opened for writing.";
   111     /**
   112      * Wrap a JavaFileObject to manage writing by the Filer.
   113      */
   114     private class FilerOutputFileObject extends ForwardingFileObject<FileObject> {
   115         private boolean opened = false;
   116         private String name;
   118         FilerOutputFileObject(String name, FileObject fileObject) {
   119             super(fileObject);
   120             this.name = name;
   121         }
   123         @Override
   124         public synchronized OutputStream openOutputStream() throws IOException {
   125             if (opened)
   126                 throw new IOException(ALREADY_OPENED);
   127             opened = true;
   128             return new FilerOutputStream(name, fileObject);
   129         }
   131         @Override
   132         public synchronized Writer openWriter() throws IOException {
   133             if (opened)
   134                 throw new IOException(ALREADY_OPENED);
   135             opened = true;
   136             return new FilerWriter(name, fileObject);
   137         }
   139         // Three anti-literacy methods
   140         @Override
   141         public InputStream openInputStream() throws IOException {
   142             throw new IllegalStateException(NOT_FOR_READING);
   143         }
   145         @Override
   146         public Reader openReader(boolean ignoreEncodingErrors) throws IOException {
   147             throw new IllegalStateException(NOT_FOR_READING);
   148         }
   150         @Override
   151         public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
   152             throw new IllegalStateException(NOT_FOR_READING);
   153         }
   155         @Override
   156         public boolean delete() {
   157             return false;
   158         }
   159     }
   161     private class FilerOutputJavaFileObject extends FilerOutputFileObject implements JavaFileObject {
   162         private final JavaFileObject javaFileObject;
   163         FilerOutputJavaFileObject(String name, JavaFileObject javaFileObject) {
   164             super(name, javaFileObject);
   165             this.javaFileObject = javaFileObject;
   166         }
   168         public JavaFileObject.Kind getKind() {
   169             return javaFileObject.getKind();
   170         }
   172         public boolean isNameCompatible(String simpleName,
   173                                         JavaFileObject.Kind kind) {
   174             return javaFileObject.isNameCompatible(simpleName, kind);
   175         }
   177         public NestingKind getNestingKind() {
   178             return javaFileObject.getNestingKind();
   179         }
   181         public Modifier getAccessLevel() {
   182             return javaFileObject.getAccessLevel();
   183         }
   184     }
   186     /**
   187      * Wrap a JavaFileObject to manage reading by the Filer.
   188      */
   189     private class FilerInputFileObject extends ForwardingFileObject<FileObject> {
   190         FilerInputFileObject(FileObject fileObject) {
   191             super(fileObject);
   192         }
   194         @Override
   195         public OutputStream openOutputStream() throws IOException {
   196             throw new IllegalStateException(NOT_FOR_WRITING);
   197         }
   199         @Override
   200         public Writer openWriter() throws IOException {
   201             throw new IllegalStateException(NOT_FOR_WRITING);
   202         }
   204         @Override
   205         public boolean delete() {
   206             return false;
   207         }
   208     }
   210     private class FilerInputJavaFileObject extends FilerInputFileObject implements JavaFileObject {
   211         private final JavaFileObject javaFileObject;
   212         FilerInputJavaFileObject(JavaFileObject javaFileObject) {
   213             super(javaFileObject);
   214             this.javaFileObject = javaFileObject;
   215         }
   217         public JavaFileObject.Kind getKind() {
   218             return javaFileObject.getKind();
   219         }
   221         public boolean isNameCompatible(String simpleName,
   222                                         JavaFileObject.Kind kind) {
   223             return javaFileObject.isNameCompatible(simpleName, kind);
   224         }
   226         public NestingKind getNestingKind() {
   227             return javaFileObject.getNestingKind();
   228         }
   230         public Modifier getAccessLevel() {
   231             return javaFileObject.getAccessLevel();
   232         }
   233     }
   236     /**
   237      * Wrap a {@code OutputStream} returned from the {@code
   238      * JavaFileManager} to properly register source or class files
   239      * when they are closed.
   240      */
   241     private class FilerOutputStream extends FilterOutputStream {
   242         String typeName;
   243         FileObject fileObject;
   244         boolean closed = false;
   246         /**
   247          * @param typeName name of class or {@code null} if just a
   248          * binary file
   249          */
   250         FilerOutputStream(String typeName, FileObject fileObject) throws IOException {
   251             super(fileObject.openOutputStream());
   252             this.typeName = typeName;
   253             this.fileObject = fileObject;
   254         }
   256         public synchronized void close() throws IOException {
   257             if (!closed) {
   258                 closed = true;
   259                 /*
   260                  * If an IOException occurs when closing the underlying
   261                  * stream, still try to process the file.
   262                  */
   264                 closeFileObject(typeName, fileObject);
   265                 out.close();
   266             }
   267         }
   268     }
   270     /**
   271      * Wrap a {@code Writer} returned from the {@code JavaFileManager}
   272      * to properly register source or class files when they are
   273      * closed.
   274      */
   275     private class FilerWriter extends FilterWriter {
   276         String typeName;
   277         FileObject fileObject;
   278         boolean closed = false;
   280         /**
   281          * @param fileObject the fileObject to be written to
   282          * @param typeName name of source file or {@code null} if just a
   283          * text file
   284          */
   285         FilerWriter(String typeName, FileObject fileObject) throws IOException {
   286             super(fileObject.openWriter());
   287             this.typeName = typeName;
   288             this.fileObject = fileObject;
   289         }
   291         public synchronized void close() throws IOException {
   292             if (!closed) {
   293                 closed = true;
   294                 /*
   295                  * If an IOException occurs when closing the underlying
   296                  * Writer, still try to process the file.
   297                  */
   299                 closeFileObject(typeName, fileObject);
   300                 out.close();
   301             }
   302         }
   303     }
   305     JavaFileManager fileManager;
   306     Log log;
   307     Context context;
   308     boolean lastRound;
   310     private final boolean lint;
   312     /**
   313      * Logical names of all created files.  This set must be
   314      * synchronized.
   315      */
   316     private final Set<FileObject> fileObjectHistory;
   318     /**
   319      * Names of types that have had files created but not closed.
   320      */
   321     private final Set<String> openTypeNames;
   323     /**
   324      * Names of source files closed in this round.  This set must be
   325      * synchronized.  Its iterators should preserve insertion order.
   326      */
   327     private Set<String> generatedSourceNames;
   329     /**
   330      * Names and class files of the class files closed in this round.
   331      * This set must be synchronized.  Its iterators should preserve
   332      * insertion order.
   333      */
   334     private final Map<String, JavaFileObject> generatedClasses;
   336     /**
   337      * JavaFileObjects for source files closed in this round.  This
   338      * set must be synchronized.  Its iterators should preserve
   339      * insertion order.
   340      */
   341     private Set<JavaFileObject> generatedSourceFileObjects;
   343     /**
   344      * Names of all created source files.  Its iterators should
   345      * preserve insertion order.
   346      */
   347     private final Set<String> aggregateGeneratedSourceNames;
   349     /**
   350      * Names of all created class files.  Its iterators should
   351      * preserve insertion order.
   352      */
   353     private final Set<String> aggregateGeneratedClassNames;
   356     JavacFiler(Context context) {
   357         this.context = context;
   358         fileManager = context.get(JavaFileManager.class);
   360         log = Log.instance(context);
   362         fileObjectHistory = synchronizedSet(new LinkedHashSet<FileObject>());
   363         generatedSourceNames = synchronizedSet(new LinkedHashSet<String>());
   364         generatedSourceFileObjects = synchronizedSet(new LinkedHashSet<JavaFileObject>());
   366         generatedClasses = synchronizedMap(new LinkedHashMap<String, JavaFileObject>());
   368         openTypeNames  = synchronizedSet(new LinkedHashSet<String>());
   370         aggregateGeneratedSourceNames = new LinkedHashSet<String>();
   371         aggregateGeneratedClassNames  = new LinkedHashSet<String>();
   373         lint = (Lint.instance(context)).isEnabled(PROCESSING);
   374     }
   376     public JavaFileObject createSourceFile(CharSequence name,
   377                                            Element... originatingElements) throws IOException {
   378         return createSourceOrClassFile(true, name.toString());
   379     }
   381     public JavaFileObject createClassFile(CharSequence name,
   382                                            Element... originatingElements) throws IOException {
   383         return createSourceOrClassFile(false, name.toString());
   384     }
   386     private JavaFileObject createSourceOrClassFile(boolean isSourceFile, String name) throws IOException {
   387         if (lint) {
   388             int periodIndex = name.lastIndexOf(".");
   389             if (periodIndex != -1) {
   390                 String base = name.substring(periodIndex);
   391                 String extn = (isSourceFile ? ".java" : ".class");
   392                 if (base.equals(extn))
   393                     log.warning("proc.suspicious.class.name", name, extn);
   394             }
   395         }
   396         checkNameAndExistence(name, isSourceFile);
   397         Location loc = (isSourceFile ? SOURCE_OUTPUT : CLASS_OUTPUT);
   398         JavaFileObject.Kind kind = (isSourceFile ?
   399                                     JavaFileObject.Kind.SOURCE :
   400                                     JavaFileObject.Kind.CLASS);
   402         JavaFileObject fileObject =
   403             fileManager.getJavaFileForOutput(loc, name, kind, null);
   404         checkFileReopening(fileObject, true);
   406         if (lastRound)
   407             log.warning("proc.file.create.last.round", name);
   409         if (isSourceFile)
   410             aggregateGeneratedSourceNames.add(name);
   411         else
   412             aggregateGeneratedClassNames.add(name);
   413         openTypeNames.add(name);
   415         return new FilerOutputJavaFileObject(name, fileObject);
   416     }
   418     public FileObject createResource(JavaFileManager.Location location,
   419                                      CharSequence pkg,
   420                                      CharSequence relativeName,
   421                                      Element... originatingElements) throws IOException {
   422         locationCheck(location);
   424         String strPkg = pkg.toString();
   425         if (strPkg.length() > 0)
   426             checkName(strPkg);
   428         FileObject fileObject =
   429             fileManager.getFileForOutput(location, strPkg,
   430                                          relativeName.toString(), null);
   431         checkFileReopening(fileObject, true);
   433         if (fileObject instanceof JavaFileObject)
   434             return new FilerOutputJavaFileObject(null, (JavaFileObject)fileObject);
   435         else
   436             return new FilerOutputFileObject(null, fileObject);
   437     }
   439     private void locationCheck(JavaFileManager.Location location) {
   440         if (location instanceof StandardLocation) {
   441             StandardLocation stdLoc = (StandardLocation) location;
   442             if (!stdLoc.isOutputLocation())
   443                 throw new IllegalArgumentException("Resource creation not supported in location " +
   444                                                    stdLoc);
   445         }
   446     }
   448     public FileObject getResource(JavaFileManager.Location location,
   449                                   CharSequence pkg,
   450                                   CharSequence relativeName) throws IOException {
   451         String strPkg = pkg.toString();
   452         if (strPkg.length() > 0)
   453             checkName(strPkg);
   455         // TODO: Only support reading resources in selected output
   456         // locations?  Only allow reading of non-source, non-class
   457         // files from the supported input locations?
   458         FileObject fileObject = fileManager.getFileForInput(location,
   459                     pkg.toString(),
   460                     relativeName.toString());
   461         if (fileObject == null) {
   462             String name = (pkg.length() == 0)
   463                     ? relativeName.toString() : (pkg + "/" + relativeName);
   464             throw new FileNotFoundException(name);
   465         }
   467         // If the path was already opened for writing, throw an exception.
   468         checkFileReopening(fileObject, false);
   469         return new FilerInputFileObject(fileObject);
   470     }
   472     private void checkName(String name) throws FilerException {
   473         checkName(name, false);
   474     }
   476     private void checkName(String name, boolean allowUnnamedPackageInfo) throws FilerException {
   477         if (!SourceVersion.isName(name) && !isPackageInfo(name, allowUnnamedPackageInfo)) {
   478             if (lint)
   479                 log.warning("proc.illegal.file.name", name);
   480             throw new FilerException("Illegal name " + name);
   481         }
   482     }
   484     private boolean isPackageInfo(String name, boolean allowUnnamedPackageInfo) {
   485         // Is the name of the form "package-info" or
   486         // "foo.bar.package-info"?
   487         final String PKG_INFO = "package-info";
   488         int periodIndex = name.lastIndexOf(".");
   489         if (periodIndex == -1) {
   490             return allowUnnamedPackageInfo ? name.equals(PKG_INFO) : false;
   491         } else {
   492             // "foo.bar.package-info." illegal
   493             String prefix = name.substring(0, periodIndex);
   494             String simple = name.substring(periodIndex+1);
   495             return SourceVersion.isName(prefix) && simple.equals(PKG_INFO);
   496         }
   497     }
   499     private void checkNameAndExistence(String typename, boolean allowUnnamedPackageInfo) throws FilerException {
   500         // TODO: Check if type already exists on source or class path?
   501         // If so, use warning message key proc.type.already.exists
   502         checkName(typename, allowUnnamedPackageInfo);
   503         if (aggregateGeneratedSourceNames.contains(typename) ||
   504             aggregateGeneratedClassNames.contains(typename)) {
   505             if (lint)
   506                 log.warning("proc.type.recreate", typename);
   507             throw new FilerException("Attempt to recreate a file for type " + typename);
   508         }
   509     }
   511     /**
   512      * Check to see if the file has already been opened; if so, throw
   513      * an exception, otherwise add it to the set of files.
   514      */
   515     private void checkFileReopening(FileObject fileObject, boolean addToHistory) throws FilerException {
   516         for(FileObject veteran : fileObjectHistory) {
   517             if (fileManager.isSameFile(veteran, fileObject)) {
   518                 if (lint)
   519                     log.warning("proc.file.reopening", fileObject.getName());
   520                 throw new FilerException("Attempt to reopen a file for path " + fileObject.getName());
   521             }
   522         }
   523         if (addToHistory)
   524             fileObjectHistory.add(fileObject);
   525     }
   527     public boolean newFiles() {
   528         return (!generatedSourceNames.isEmpty())
   529             || (!generatedClasses.isEmpty());
   530     }
   532     public Set<String> getGeneratedSourceNames() {
   533         return generatedSourceNames;
   534     }
   536     public Set<JavaFileObject> getGeneratedSourceFileObjects() {
   537         return generatedSourceFileObjects;
   538     }
   540     public Map<String, JavaFileObject> getGeneratedClasses() {
   541         return generatedClasses;
   542     }
   544     public void warnIfUnclosedFiles() {
   545         if (!openTypeNames.isEmpty())
   546             log.warning("proc.unclosed.type.files", openTypeNames.toString());
   547     }
   549     /**
   550      * Update internal state for a new round.
   551      */
   552     public void newRound(Context context) {
   553         this.context = context;
   554         this.log = Log.instance(context);
   555         clearRoundState();
   556     }
   558     void setLastRound(boolean lastRound) {
   559         this.lastRound = lastRound;
   560     }
   562     public void close() {
   563         clearRoundState();
   564         // Cross-round state
   565         fileObjectHistory.clear();
   566         openTypeNames.clear();
   567         aggregateGeneratedSourceNames.clear();
   568         aggregateGeneratedClassNames.clear();
   569     }
   571     private void clearRoundState() {
   572         generatedSourceNames.clear();
   573         generatedSourceFileObjects.clear();
   574         generatedClasses.clear();
   575     }
   577     /**
   578      * Debugging function to display internal state.
   579      */
   580     public void displayState() {
   581         PrintWriter xout = context.get(Log.outKey);
   582         xout.println("File Object History : " +  fileObjectHistory);
   583         xout.println("Open Type Names     : " +  openTypeNames);
   584         xout.println("Gen. Src Names      : " +  generatedSourceNames);
   585         xout.println("Gen. Cls Names      : " +  generatedClasses.keySet());
   586         xout.println("Agg. Gen. Src Names : " +  aggregateGeneratedSourceNames);
   587         xout.println("Agg. Gen. Cls Names : " +  aggregateGeneratedClassNames);
   588     }
   590     public String toString() {
   591         return "javac Filer";
   592     }
   594     /**
   595      * Upon close, register files opened by create{Source, Class}File
   596      * for annotation processing.
   597      */
   598     private void closeFileObject(String typeName, FileObject fileObject) {
   599         /*
   600          * If typeName is non-null, the file object was opened as a
   601          * source or class file by the user.  If a file was opened as
   602          * a resource, typeName will be null and the file is *not*
   603          * subject to annotation processing.
   604          */
   605         if ((typeName != null)) {
   606             if (!(fileObject instanceof JavaFileObject))
   607                 throw new AssertionError("JavaFileOject not found for " + fileObject);
   608             JavaFileObject javaFileObject = (JavaFileObject)fileObject;
   609             switch(javaFileObject.getKind()) {
   610             case SOURCE:
   611                 generatedSourceNames.add(typeName);
   612                 generatedSourceFileObjects.add(javaFileObject);
   613                 openTypeNames.remove(typeName);
   614                 break;
   616             case CLASS:
   617                 generatedClasses.put(typeName, javaFileObject);
   618                 openTypeNames.remove(typeName);
   619                 break;
   621             default:
   622                 break;
   623             }
   624         }
   625     }
   627 }

mercurial