0N/A/*
1062N/A * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
553N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
553N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
553N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
553N/A * or visit www.oracle.com if you need additional information or have any
553N/A * questions.
0N/A */
0N/A
0N/Apackage com.sun.tools.javac.processing;
0N/A
0N/Aimport java.io.Closeable;
654N/Aimport java.io.FileNotFoundException;
0N/Aimport java.io.InputStream;
0N/Aimport java.io.OutputStream;
0N/Aimport java.io.FilterOutputStream;
0N/Aimport java.io.Reader;
0N/Aimport java.io.Writer;
0N/Aimport java.io.FilterWriter;
0N/Aimport java.io.PrintWriter;
0N/Aimport java.io.IOException;
699N/Aimport java.util.*;
0N/A
0N/Aimport static java.util.Collections.*;
0N/A
699N/Aimport javax.annotation.processing.*;
699N/Aimport javax.lang.model.SourceVersion;
699N/Aimport javax.lang.model.element.NestingKind;
699N/Aimport javax.lang.model.element.Modifier;
699N/Aimport javax.lang.model.element.Element;
699N/Aimport javax.tools.*;
0N/Aimport javax.tools.JavaFileManager.Location;
699N/A
0N/Aimport static javax.tools.StandardLocation.SOURCE_OUTPUT;
0N/Aimport static javax.tools.StandardLocation.CLASS_OUTPUT;
0N/A
699N/Aimport com.sun.tools.javac.code.Lint;
699N/Aimport com.sun.tools.javac.util.*;
699N/A
699N/Aimport static com.sun.tools.javac.code.Lint.LintCategory.PROCESSING;
699N/A
0N/A/**
0N/A * The FilerImplementation class must maintain a number of
0N/A * constraints. First, multiple attempts to open the same path within
0N/A * the same invocation of the tool results in an IOException being
0N/A * thrown. For example, trying to open the same source file twice:
0N/A *
0N/A * <pre>
0N/A * createSourceFile("foo.Bar")
0N/A * ...
0N/A * createSourceFile("foo.Bar")
0N/A * </pre>
0N/A *
0N/A * is disallowed as is opening a text file that happens to have
0N/A * the same name as a source file:
0N/A *
0N/A * <pre>
0N/A * createSourceFile("foo.Bar")
0N/A * ...
0N/A * createTextFile(SOURCE_TREE, "foo", new File("Bar"), null)
0N/A * </pre>
0N/A *
0N/A * <p>Additionally, creating a source file that corresponds to an
0N/A * already created class file (or vice versa) also results in an
0N/A * IOException since each type can only be created once. However, if
0N/A * the Filer is used to create a text file named *.java that happens
0N/A * to correspond to an existing class file, a warning is *not*
0N/A * generated. Similarly, a warning is not generated for a binary file
0N/A * named *.class and an existing source file.
0N/A *
0N/A * <p>The reason for this difference is that source files and class
0N/A * files are registered with the tool and can get passed on as
0N/A * declarations to the next round of processing. Files that are just
0N/A * named *.java and *.class are not processed in that manner; although
0N/A * having extra source files and class files on the source path and
0N/A * class path can alter the behavior of the tool and any final
0N/A * compile.
0N/A *
580N/A * <p><b>This is NOT part of any supported API.
0N/A * If you write code that depends on this, you do so at your own risk.
0N/A * This code and its internal interfaces are subject to change or
0N/A * deletion without notice.</b>
0N/A */
0N/Apublic class JavacFiler implements Filer, Closeable {
0N/A // TODO: Implement different transaction model for updating the
0N/A // Filer's record keeping on file close.
0N/A
0N/A private static final String ALREADY_OPENED =
0N/A "Output stream or writer has already been opened.";
0N/A private static final String NOT_FOR_READING =
0N/A "FileObject was not opened for reading.";
0N/A private static final String NOT_FOR_WRITING =
0N/A "FileObject was not opened for writing.";
0N/A
0N/A /**
0N/A * Wrap a JavaFileObject to manage writing by the Filer.
0N/A */
0N/A private class FilerOutputFileObject extends ForwardingFileObject<FileObject> {
0N/A private boolean opened = false;
0N/A private String name;
0N/A
0N/A FilerOutputFileObject(String name, FileObject fileObject) {
0N/A super(fileObject);
0N/A this.name = name;
0N/A }
0N/A
0N/A @Override
0N/A public synchronized OutputStream openOutputStream() throws IOException {
0N/A if (opened)
0N/A throw new IOException(ALREADY_OPENED);
0N/A opened = true;
0N/A return new FilerOutputStream(name, fileObject);
0N/A }
0N/A
0N/A @Override
0N/A public synchronized Writer openWriter() throws IOException {
0N/A if (opened)
0N/A throw new IOException(ALREADY_OPENED);
0N/A opened = true;
0N/A return new FilerWriter(name, fileObject);
0N/A }
0N/A
0N/A // Three anti-literacy methods
0N/A @Override
0N/A public InputStream openInputStream() throws IOException {
0N/A throw new IllegalStateException(NOT_FOR_READING);
0N/A }
0N/A
0N/A @Override
0N/A public Reader openReader(boolean ignoreEncodingErrors) throws IOException {
0N/A throw new IllegalStateException(NOT_FOR_READING);
0N/A }
0N/A
0N/A @Override
0N/A public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
0N/A throw new IllegalStateException(NOT_FOR_READING);
0N/A }
0N/A
0N/A @Override
0N/A public boolean delete() {
0N/A return false;
0N/A }
0N/A }
0N/A
0N/A private class FilerOutputJavaFileObject extends FilerOutputFileObject implements JavaFileObject {
0N/A private final JavaFileObject javaFileObject;
0N/A FilerOutputJavaFileObject(String name, JavaFileObject javaFileObject) {
0N/A super(name, javaFileObject);
0N/A this.javaFileObject = javaFileObject;
0N/A }
0N/A
0N/A public JavaFileObject.Kind getKind() {
0N/A return javaFileObject.getKind();
0N/A }
0N/A
0N/A public boolean isNameCompatible(String simpleName,
0N/A JavaFileObject.Kind kind) {
0N/A return javaFileObject.isNameCompatible(simpleName, kind);
0N/A }
0N/A
0N/A public NestingKind getNestingKind() {
0N/A return javaFileObject.getNestingKind();
0N/A }
0N/A
0N/A public Modifier getAccessLevel() {
0N/A return javaFileObject.getAccessLevel();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Wrap a JavaFileObject to manage reading by the Filer.
0N/A */
0N/A private class FilerInputFileObject extends ForwardingFileObject<FileObject> {
0N/A FilerInputFileObject(FileObject fileObject) {
0N/A super(fileObject);
0N/A }
0N/A
0N/A @Override
0N/A public OutputStream openOutputStream() throws IOException {
0N/A throw new IllegalStateException(NOT_FOR_WRITING);
0N/A }
0N/A
0N/A @Override
0N/A public Writer openWriter() throws IOException {
0N/A throw new IllegalStateException(NOT_FOR_WRITING);
0N/A }
0N/A
0N/A @Override
0N/A public boolean delete() {
0N/A return false;
0N/A }
0N/A }
0N/A
0N/A private class FilerInputJavaFileObject extends FilerInputFileObject implements JavaFileObject {
0N/A private final JavaFileObject javaFileObject;
0N/A FilerInputJavaFileObject(JavaFileObject javaFileObject) {
0N/A super(javaFileObject);
0N/A this.javaFileObject = javaFileObject;
0N/A }
0N/A
0N/A public JavaFileObject.Kind getKind() {
0N/A return javaFileObject.getKind();
0N/A }
0N/A
0N/A public boolean isNameCompatible(String simpleName,
0N/A JavaFileObject.Kind kind) {
0N/A return javaFileObject.isNameCompatible(simpleName, kind);
0N/A }
0N/A
0N/A public NestingKind getNestingKind() {
0N/A return javaFileObject.getNestingKind();
0N/A }
0N/A
0N/A public Modifier getAccessLevel() {
0N/A return javaFileObject.getAccessLevel();
0N/A }
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Wrap a {@code OutputStream} returned from the {@code
0N/A * JavaFileManager} to properly register source or class files
0N/A * when they are closed.
0N/A */
0N/A private class FilerOutputStream extends FilterOutputStream {
0N/A String typeName;
0N/A FileObject fileObject;
0N/A boolean closed = false;
0N/A
0N/A /**
0N/A * @param typeName name of class or {@code null} if just a
0N/A * binary file
0N/A */
0N/A FilerOutputStream(String typeName, FileObject fileObject) throws IOException {
0N/A super(fileObject.openOutputStream());
0N/A this.typeName = typeName;
0N/A this.fileObject = fileObject;
0N/A }
0N/A
0N/A public synchronized void close() throws IOException {
0N/A if (!closed) {
0N/A closed = true;
0N/A /*
0N/A * If an IOException occurs when closing the underlying
0N/A * stream, still try to process the file.
0N/A */
0N/A
0N/A closeFileObject(typeName, fileObject);
0N/A out.close();
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Wrap a {@code Writer} returned from the {@code JavaFileManager}
0N/A * to properly register source or class files when they are
0N/A * closed.
0N/A */
0N/A private class FilerWriter extends FilterWriter {
0N/A String typeName;
0N/A FileObject fileObject;
0N/A boolean closed = false;
0N/A
0N/A /**
0N/A * @param fileObject the fileObject to be written to
0N/A * @param typeName name of source file or {@code null} if just a
0N/A * text file
0N/A */
0N/A FilerWriter(String typeName, FileObject fileObject) throws IOException {
0N/A super(fileObject.openWriter());
0N/A this.typeName = typeName;
0N/A this.fileObject = fileObject;
0N/A }
0N/A
0N/A public synchronized void close() throws IOException {
0N/A if (!closed) {
0N/A closed = true;
0N/A /*
0N/A * If an IOException occurs when closing the underlying
0N/A * Writer, still try to process the file.
0N/A */
0N/A
0N/A closeFileObject(typeName, fileObject);
0N/A out.close();
0N/A }
0N/A }
0N/A }
0N/A
0N/A JavaFileManager fileManager;
0N/A Log log;
0N/A Context context;
0N/A boolean lastRound;
0N/A
0N/A private final boolean lint;
0N/A
0N/A /**
0N/A * Logical names of all created files. This set must be
0N/A * synchronized.
0N/A */
0N/A private final Set<FileObject> fileObjectHistory;
0N/A
0N/A /**
0N/A * Names of types that have had files created but not closed.
0N/A */
0N/A private final Set<String> openTypeNames;
0N/A
0N/A /**
0N/A * Names of source files closed in this round. This set must be
0N/A * synchronized. Its iterators should preserve insertion order.
0N/A */
0N/A private Set<String> generatedSourceNames;
0N/A
0N/A /**
0N/A * Names and class files of the class files closed in this round.
0N/A * This set must be synchronized. Its iterators should preserve
0N/A * insertion order.
0N/A */
0N/A private final Map<String, JavaFileObject> generatedClasses;
0N/A
0N/A /**
0N/A * JavaFileObjects for source files closed in this round. This
0N/A * set must be synchronized. Its iterators should preserve
0N/A * insertion order.
0N/A */
0N/A private Set<JavaFileObject> generatedSourceFileObjects;
0N/A
0N/A /**
0N/A * Names of all created source files. Its iterators should
0N/A * preserve insertion order.
0N/A */
0N/A private final Set<String> aggregateGeneratedSourceNames;
0N/A
0N/A /**
0N/A * Names of all created class files. Its iterators should
0N/A * preserve insertion order.
0N/A */
0N/A private final Set<String> aggregateGeneratedClassNames;
0N/A
0N/A
0N/A JavacFiler(Context context) {
0N/A this.context = context;
0N/A fileManager = context.get(JavaFileManager.class);
0N/A
0N/A log = Log.instance(context);
0N/A
0N/A fileObjectHistory = synchronizedSet(new LinkedHashSet<FileObject>());
0N/A generatedSourceNames = synchronizedSet(new LinkedHashSet<String>());
0N/A generatedSourceFileObjects = synchronizedSet(new LinkedHashSet<JavaFileObject>());
0N/A
0N/A generatedClasses = synchronizedMap(new LinkedHashMap<String, JavaFileObject>());
0N/A
0N/A openTypeNames = synchronizedSet(new LinkedHashSet<String>());
0N/A
0N/A aggregateGeneratedSourceNames = new LinkedHashSet<String>();
0N/A aggregateGeneratedClassNames = new LinkedHashSet<String>();
0N/A
699N/A lint = (Lint.instance(context)).isEnabled(PROCESSING);
0N/A }
0N/A
0N/A public JavaFileObject createSourceFile(CharSequence name,
0N/A Element... originatingElements) throws IOException {
0N/A return createSourceOrClassFile(true, name.toString());
0N/A }
0N/A
0N/A public JavaFileObject createClassFile(CharSequence name,
0N/A Element... originatingElements) throws IOException {
0N/A return createSourceOrClassFile(false, name.toString());
0N/A }
0N/A
0N/A private JavaFileObject createSourceOrClassFile(boolean isSourceFile, String name) throws IOException {
617N/A if (lint) {
617N/A int periodIndex = name.lastIndexOf(".");
617N/A if (periodIndex != -1) {
617N/A String base = name.substring(periodIndex);
617N/A String extn = (isSourceFile ? ".java" : ".class");
617N/A if (base.equals(extn))
617N/A log.warning("proc.suspicious.class.name", name, extn);
617N/A }
617N/A }
0N/A checkNameAndExistence(name, isSourceFile);
0N/A Location loc = (isSourceFile ? SOURCE_OUTPUT : CLASS_OUTPUT);
0N/A JavaFileObject.Kind kind = (isSourceFile ?
0N/A JavaFileObject.Kind.SOURCE :
0N/A JavaFileObject.Kind.CLASS);
0N/A
0N/A JavaFileObject fileObject =
0N/A fileManager.getJavaFileForOutput(loc, name, kind, null);
0N/A checkFileReopening(fileObject, true);
0N/A
0N/A if (lastRound)
0N/A log.warning("proc.file.create.last.round", name);
0N/A
0N/A if (isSourceFile)
0N/A aggregateGeneratedSourceNames.add(name);
0N/A else
0N/A aggregateGeneratedClassNames.add(name);
0N/A openTypeNames.add(name);
0N/A
0N/A return new FilerOutputJavaFileObject(name, fileObject);
0N/A }
0N/A
0N/A public FileObject createResource(JavaFileManager.Location location,
0N/A CharSequence pkg,
0N/A CharSequence relativeName,
0N/A Element... originatingElements) throws IOException {
0N/A locationCheck(location);
0N/A
0N/A String strPkg = pkg.toString();
0N/A if (strPkg.length() > 0)
0N/A checkName(strPkg);
0N/A
0N/A FileObject fileObject =
0N/A fileManager.getFileForOutput(location, strPkg,
0N/A relativeName.toString(), null);
0N/A checkFileReopening(fileObject, true);
0N/A
0N/A if (fileObject instanceof JavaFileObject)
0N/A return new FilerOutputJavaFileObject(null, (JavaFileObject)fileObject);
0N/A else
0N/A return new FilerOutputFileObject(null, fileObject);
0N/A }
0N/A
0N/A private void locationCheck(JavaFileManager.Location location) {
0N/A if (location instanceof StandardLocation) {
0N/A StandardLocation stdLoc = (StandardLocation) location;
0N/A if (!stdLoc.isOutputLocation())
0N/A throw new IllegalArgumentException("Resource creation not supported in location " +
0N/A stdLoc);
0N/A }
0N/A }
0N/A
0N/A public FileObject getResource(JavaFileManager.Location location,
0N/A CharSequence pkg,
0N/A CharSequence relativeName) throws IOException {
0N/A String strPkg = pkg.toString();
0N/A if (strPkg.length() > 0)
0N/A checkName(strPkg);
0N/A
0N/A // TODO: Only support reading resources in selected output
0N/A // locations? Only allow reading of non-source, non-class
0N/A // files from the supported input locations?
1062N/A
1062N/A // In the following, getFileForInput is the "obvious" method
1062N/A // to use, but it does not have the "obvious" semantics for
1062N/A // SOURCE_OUTPUT and CLASS_OUTPUT. Conversely, getFileForOutput
1062N/A // does not have the correct semantics for any "path" location
1062N/A // with more than one component. So, for now, we use a hybrid
1062N/A // invocation.
1062N/A FileObject fileObject;
1062N/A if (location.isOutputLocation()) {
1062N/A fileObject = fileManager.getFileForOutput(location,
1062N/A pkg.toString(),
1062N/A relativeName.toString(),
1062N/A null);
1062N/A } else {
1062N/A fileObject = fileManager.getFileForInput(location,
654N/A pkg.toString(),
654N/A relativeName.toString());
1062N/A }
654N/A if (fileObject == null) {
654N/A String name = (pkg.length() == 0)
654N/A ? relativeName.toString() : (pkg + "/" + relativeName);
654N/A throw new FileNotFoundException(name);
654N/A }
654N/A
0N/A // If the path was already opened for writing, throw an exception.
0N/A checkFileReopening(fileObject, false);
0N/A return new FilerInputFileObject(fileObject);
0N/A }
0N/A
0N/A private void checkName(String name) throws FilerException {
0N/A checkName(name, false);
0N/A }
0N/A
0N/A private void checkName(String name, boolean allowUnnamedPackageInfo) throws FilerException {
0N/A if (!SourceVersion.isName(name) && !isPackageInfo(name, allowUnnamedPackageInfo)) {
0N/A if (lint)
0N/A log.warning("proc.illegal.file.name", name);
0N/A throw new FilerException("Illegal name " + name);
0N/A }
0N/A }
0N/A
0N/A private boolean isPackageInfo(String name, boolean allowUnnamedPackageInfo) {
0N/A // Is the name of the form "package-info" or
0N/A // "foo.bar.package-info"?
0N/A final String PKG_INFO = "package-info";
0N/A int periodIndex = name.lastIndexOf(".");
0N/A if (periodIndex == -1) {
0N/A return allowUnnamedPackageInfo ? name.equals(PKG_INFO) : false;
0N/A } else {
0N/A // "foo.bar.package-info." illegal
0N/A String prefix = name.substring(0, periodIndex);
0N/A String simple = name.substring(periodIndex+1);
0N/A return SourceVersion.isName(prefix) && simple.equals(PKG_INFO);
0N/A }
0N/A }
0N/A
0N/A private void checkNameAndExistence(String typename, boolean allowUnnamedPackageInfo) throws FilerException {
0N/A // TODO: Check if type already exists on source or class path?
0N/A // If so, use warning message key proc.type.already.exists
0N/A checkName(typename, allowUnnamedPackageInfo);
0N/A if (aggregateGeneratedSourceNames.contains(typename) ||
0N/A aggregateGeneratedClassNames.contains(typename)) {
0N/A if (lint)
0N/A log.warning("proc.type.recreate", typename);
0N/A throw new FilerException("Attempt to recreate a file for type " + typename);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Check to see if the file has already been opened; if so, throw
0N/A * an exception, otherwise add it to the set of files.
0N/A */
0N/A private void checkFileReopening(FileObject fileObject, boolean addToHistory) throws FilerException {
0N/A for(FileObject veteran : fileObjectHistory) {
0N/A if (fileManager.isSameFile(veteran, fileObject)) {
0N/A if (lint)
0N/A log.warning("proc.file.reopening", fileObject.getName());
0N/A throw new FilerException("Attempt to reopen a file for path " + fileObject.getName());
0N/A }
0N/A }
0N/A if (addToHistory)
0N/A fileObjectHistory.add(fileObject);
0N/A }
0N/A
0N/A public boolean newFiles() {
0N/A return (!generatedSourceNames.isEmpty())
0N/A || (!generatedClasses.isEmpty());
0N/A }
0N/A
0N/A public Set<String> getGeneratedSourceNames() {
0N/A return generatedSourceNames;
0N/A }
0N/A
0N/A public Set<JavaFileObject> getGeneratedSourceFileObjects() {
0N/A return generatedSourceFileObjects;
0N/A }
0N/A
0N/A public Map<String, JavaFileObject> getGeneratedClasses() {
0N/A return generatedClasses;
0N/A }
0N/A
0N/A public void warnIfUnclosedFiles() {
0N/A if (!openTypeNames.isEmpty())
0N/A log.warning("proc.unclosed.type.files", openTypeNames.toString());
0N/A }
0N/A
0N/A /**
0N/A * Update internal state for a new round.
0N/A */
619N/A public void newRound(Context context) {
0N/A this.context = context;
0N/A this.log = Log.instance(context);
619N/A clearRoundState();
619N/A }
619N/A
619N/A void setLastRound(boolean lastRound) {
0N/A this.lastRound = lastRound;
0N/A }
0N/A
0N/A public void close() {
0N/A clearRoundState();
0N/A // Cross-round state
0N/A fileObjectHistory.clear();
0N/A openTypeNames.clear();
0N/A aggregateGeneratedSourceNames.clear();
0N/A aggregateGeneratedClassNames.clear();
0N/A }
0N/A
0N/A private void clearRoundState() {
0N/A generatedSourceNames.clear();
0N/A generatedSourceFileObjects.clear();
0N/A generatedClasses.clear();
0N/A }
0N/A
0N/A /**
0N/A * Debugging function to display internal state.
0N/A */
0N/A public void displayState() {
0N/A PrintWriter xout = context.get(Log.outKey);
0N/A xout.println("File Object History : " + fileObjectHistory);
0N/A xout.println("Open Type Names : " + openTypeNames);
0N/A xout.println("Gen. Src Names : " + generatedSourceNames);
0N/A xout.println("Gen. Cls Names : " + generatedClasses.keySet());
0N/A xout.println("Agg. Gen. Src Names : " + aggregateGeneratedSourceNames);
0N/A xout.println("Agg. Gen. Cls Names : " + aggregateGeneratedClassNames);
0N/A }
0N/A
0N/A public String toString() {
0N/A return "javac Filer";
0N/A }
0N/A
0N/A /**
0N/A * Upon close, register files opened by create{Source, Class}File
0N/A * for annotation processing.
0N/A */
0N/A private void closeFileObject(String typeName, FileObject fileObject) {
0N/A /*
0N/A * If typeName is non-null, the file object was opened as a
0N/A * source or class file by the user. If a file was opened as
0N/A * a resource, typeName will be null and the file is *not*
0N/A * subject to annotation processing.
0N/A */
0N/A if ((typeName != null)) {
0N/A if (!(fileObject instanceof JavaFileObject))
0N/A throw new AssertionError("JavaFileOject not found for " + fileObject);
0N/A JavaFileObject javaFileObject = (JavaFileObject)fileObject;
0N/A switch(javaFileObject.getKind()) {
0N/A case SOURCE:
0N/A generatedSourceNames.add(typeName);
0N/A generatedSourceFileObjects.add(javaFileObject);
0N/A openTypeNames.remove(typeName);
0N/A break;
0N/A
0N/A case CLASS:
0N/A generatedClasses.put(typeName, javaFileObject);
0N/A openTypeNames.remove(typeName);
0N/A break;
0N/A
0N/A default:
0N/A break;
0N/A }
0N/A }
0N/A }
0N/A
0N/A}