duke@1: /* ohair@158: * Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved. duke@1: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. duke@1: * duke@1: * This code is free software; you can redistribute it and/or modify it duke@1: * under the terms of the GNU General Public License version 2 only, as ohair@158: * published by the Free Software Foundation. Oracle designates this duke@1: * particular file as subject to the "Classpath" exception as provided ohair@158: * by Oracle in the LICENSE file that accompanied this code. duke@1: * duke@1: * This code is distributed in the hope that it will be useful, but WITHOUT duke@1: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or duke@1: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License duke@1: * version 2 for more details (a copy is included in the LICENSE file that duke@1: * accompanied this code). duke@1: * duke@1: * You should have received a copy of the GNU General Public License version duke@1: * 2 along with this work; if not, write to the Free Software Foundation, duke@1: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. duke@1: * ohair@158: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA ohair@158: * or visit www.oracle.com if you need additional information or have any ohair@158: * questions. duke@1: */ duke@1: duke@1: /* duke@1: * Licensed Materials - Property of IBM duke@1: * RMI-IIOP v1.0 duke@1: * Copyright IBM Corp. 1998 1999 All Rights Reserved duke@1: * duke@1: */ duke@1: duke@1: duke@1: package sun.rmi.rmic.iiop; duke@1: duke@1: import java.io.File; duke@1: import java.io.FileOutputStream; duke@1: import java.io.OutputStreamWriter; duke@1: import java.io.IOException; duke@1: import sun.tools.java.Identifier; duke@1: import sun.tools.java.ClassPath; duke@1: import sun.tools.java.ClassFile; duke@1: import sun.tools.java.ClassNotFound; duke@1: import sun.tools.java.ClassDefinition; duke@1: import sun.tools.java.ClassDeclaration; duke@1: import sun.rmi.rmic.IndentingWriter; duke@1: import sun.rmi.rmic.Main; duke@1: import sun.rmi.rmic.iiop.Util; duke@1: import java.util.HashSet; duke@1: duke@1: /** duke@1: * Generator provides a small framework from which IIOP-specific duke@1: * generators can inherit. Common logic is implemented here which uses duke@1: * both abstract methods as well as concrete methods which subclasses may duke@1: * want to override. The following methods must be present in any subclass: duke@1: *
duke@1:  *      Default constructor
duke@1:  *              CompoundType getTopType(BatchEnvironment env, ClassDefinition cdef);
duke@1:  *      int parseArgs(String argv[], int currentIndex);
duke@1:  *      boolean requireNewInstance();
duke@1:  *              OutputType[] getOutputTypesFor(CompoundType topType,
duke@1:  *                                     HashSet alreadyChecked);
duke@1:  *              String getFileNameExtensionFor(OutputType outputType);
duke@1:  *              void writeOutputFor (   OutputType outputType,
duke@1:  *                              HashSet alreadyChecked,
duke@1:  *                                                              IndentingWriter writer) throws IOException;
duke@1:  * 
duke@1: * @author Bryan Atsatt duke@1: */ duke@1: public abstract class Generator implements sun.rmi.rmic.Generator, duke@1: sun.rmi.rmic.iiop.Constants { duke@1: duke@1: protected boolean alwaysGenerate = false; duke@1: protected BatchEnvironment env = null; duke@1: protected ContextStack contextStack = null; duke@1: private boolean trace = false; duke@1: protected boolean idl = false; duke@1: duke@1: /** duke@1: * Examine and consume command line arguments. duke@1: * @param argv The command line arguments. Ignore null duke@1: * and unknown arguments. Set each consumed argument to null. duke@1: * @param error Report any errors using the main.error() methods. duke@1: * @return true if no errors, false otherwise. duke@1: */ duke@1: public boolean parseArgs(String argv[], Main main) { duke@1: for (int i = 0; i < argv.length; i++) { duke@1: if (argv[i] != null) { duke@1: if (argv[i].equalsIgnoreCase("-always") || duke@1: argv[i].equalsIgnoreCase("-alwaysGenerate")) { duke@1: alwaysGenerate = true; duke@1: argv[i] = null; duke@1: } else if (argv[i].equalsIgnoreCase("-xtrace")) { duke@1: trace = true; duke@1: argv[i] = null; duke@1: } duke@1: } duke@1: } duke@1: return true; duke@1: } duke@1: duke@1: /** duke@1: * Return true if non-conforming types should be parsed. duke@1: * @param stack The context stack. duke@1: */ duke@1: protected abstract boolean parseNonConforming(ContextStack stack); duke@1: duke@1: /** duke@1: * Create and return a top-level type. duke@1: * @param cdef The top-level class definition. duke@1: * @param stack The context stack. duke@1: * @return The compound type or null if is non-conforming. duke@1: */ duke@1: protected abstract CompoundType getTopType(ClassDefinition cdef, ContextStack stack); duke@1: duke@1: /** duke@1: * Return an array containing all the file names and types that need to be duke@1: * generated for the given top-level type. The file names must NOT have an duke@1: * extension (e.g. ".java"). duke@1: * @param topType The type returned by getTopType(). duke@1: * @param alreadyChecked A set of Types which have already been checked. duke@1: * Intended to be passed to Type.collectMatching(filter,alreadyChecked). duke@1: */ duke@1: protected abstract OutputType[] getOutputTypesFor(CompoundType topType, duke@1: HashSet alreadyChecked); duke@1: duke@1: /** duke@1: * Return the file name extension for the given file name (e.g. ".java"). duke@1: * All files generated with the ".java" extension will be compiled. To duke@1: * change this behavior for ".java" files, override the compileJavaSourceFile duke@1: * method to return false. duke@1: * @param outputType One of the items returned by getOutputTypesFor(...) duke@1: */ duke@1: protected abstract String getFileNameExtensionFor(OutputType outputType); duke@1: duke@1: /** duke@1: * Write the output for the given OutputFileName into the output stream. duke@1: * @param name One of the items returned by getOutputTypesFor(...) duke@1: * @param alreadyChecked A set of Types which have already been checked. duke@1: * Intended to be passed to Type.collectMatching(filter,alreadyChecked). duke@1: * @param writer The output stream. duke@1: */ duke@1: protected abstract void writeOutputFor(OutputType outputType, duke@1: HashSet alreadyChecked, duke@1: IndentingWriter writer) throws IOException; duke@1: duke@1: /** duke@1: * Return true if a new instance should be created for each duke@1: * class on the command line. Subclasses which return true duke@1: * should override newInstance() to return an appropriately duke@1: * constructed instance. duke@1: */ duke@1: protected abstract boolean requireNewInstance(); duke@1: duke@1: /** duke@1: * Return true if the specified file needs generation. duke@1: */ duke@1: public boolean requiresGeneration (File target, Type theType) { duke@1: duke@1: boolean result = alwaysGenerate; duke@1: duke@1: if (!result) { duke@1: duke@1: // Get a ClassFile instance for base source or class duke@1: // file. We use ClassFile so that if the base is in duke@1: // a zip file, we can still get at it's mod time... duke@1: duke@1: ClassFile baseFile; duke@1: ClassPath path = env.getClassPath(); duke@1: String className = theType.getQualifiedName().replace('.',File.separatorChar); duke@1: duke@1: // First try the source file... duke@1: duke@1: baseFile = path.getFile(className + ".source"); duke@1: duke@1: if (baseFile == null) { duke@1: duke@1: // Then try class file... duke@1: duke@1: baseFile = path.getFile(className + ".class"); duke@1: } duke@1: duke@1: // Do we have a baseFile? duke@1: duke@1: if (baseFile != null) { duke@1: duke@1: // Yes, grab baseFile's mod time... duke@1: duke@1: long baseFileMod = baseFile.lastModified(); duke@1: duke@1: // Get a File instance for the target. If it is a source duke@1: // file, create a class file instead since the source file duke@1: // will frequently be deleted... duke@1: duke@1: String targetName = IDLNames.replace(target.getName(),".java",".class"); duke@1: String parentPath = target.getParent(); duke@1: File targetFile = new File(parentPath,targetName); duke@1: duke@1: // Does the target file exist? duke@1: duke@1: if (targetFile.exists()) { duke@1: duke@1: // Yes, so grab it's mod time... duke@1: duke@1: long targetFileMod = targetFile.lastModified(); duke@1: duke@1: // Set result... duke@1: duke@1: result = targetFileMod < baseFileMod; duke@1: duke@1: } else { duke@1: duke@1: // No, so we must generate... duke@1: duke@1: result = true; duke@1: } duke@1: } else { duke@1: duke@1: // No, so we must generate... duke@1: duke@1: result = true; duke@1: } duke@1: } duke@1: duke@1: return result; duke@1: } duke@1: duke@1: /** duke@1: * Create and return a new instance of self. Subclasses duke@1: * which need to do something other than default construction duke@1: * must override this method. duke@1: */ duke@1: protected Generator newInstance() { duke@1: Generator result = null; duke@1: try { duke@1: result = (Generator) getClass().newInstance(); duke@1: } duke@1: catch (Exception e){} // Should ALWAYS work! duke@1: duke@1: return result; duke@1: } duke@1: duke@1: /** duke@1: * Default constructor for subclasses to use. duke@1: */ duke@1: protected Generator() { duke@1: } duke@1: duke@1: /** duke@1: * Generate output. Any source files created which need compilation should duke@1: * be added to the compiler environment using the addGeneratedFile(File) duke@1: * method. duke@1: * duke@1: * @param env The compiler environment duke@1: * @param cdef The definition for the implementation class or interface from duke@1: * which to generate output duke@1: * @param destDir The directory for the root of the package hierarchy duke@1: * for generated files. May be null. duke@1: */ duke@1: public void generate(sun.rmi.rmic.BatchEnvironment env, ClassDefinition cdef, File destDir) { duke@1: duke@1: this.env = (BatchEnvironment) env; duke@1: contextStack = new ContextStack(this.env); duke@1: contextStack.setTrace(trace); duke@1: duke@1: // Make sure the environment knows whether or not to parse duke@1: // non-conforming types. This will clear out any previously duke@1: // parsed types if necessary... duke@1: duke@1: this.env.setParseNonConforming(parseNonConforming(contextStack)); duke@1: duke@1: // Get our top level type... duke@1: duke@1: CompoundType topType = getTopType(cdef,contextStack); duke@1: if (topType != null) { duke@1: duke@1: Generator generator = this; duke@1: duke@1: // Do we need to make a new instance? duke@1: duke@1: if (requireNewInstance()) { duke@1: duke@1: // Yes, so make one. 'this' instance is the one instantiated by Main duke@1: // and which knows any needed command line args... duke@1: duke@1: generator = newInstance(); duke@1: } duke@1: duke@1: // Now generate all output files... duke@1: duke@1: generator.generateOutputFiles(topType, this.env, destDir); duke@1: } duke@1: } duke@1: duke@1: /** duke@1: * Create and return a new instance of self. Subclasses duke@1: * which need to do something other than default construction duke@1: * must override this method. duke@1: */ duke@1: protected void generateOutputFiles (CompoundType topType, duke@1: BatchEnvironment env, duke@1: File destDir) { duke@1: duke@1: // Grab the 'alreadyChecked' HashSet from the environment... duke@1: duke@1: HashSet alreadyChecked = env.alreadyChecked; duke@1: duke@1: // Ask subclass for a list of output types... duke@1: duke@1: OutputType[] types = getOutputTypesFor(topType,alreadyChecked); duke@1: duke@1: // Process each file... duke@1: duke@1: for (int i = 0; i < types.length; i++) { duke@1: OutputType current = types[i]; duke@1: String className = current.getName(); duke@1: File file = getFileFor(current,destDir); duke@1: boolean sourceFile = false; duke@1: duke@1: // Do we need to generate this file? duke@1: duke@1: if (requiresGeneration(file,current.getType())) { duke@1: duke@1: // Yes. If java source file, add to environment so will be compiled... duke@1: duke@1: if (file.getName().endsWith(".java")) { duke@1: sourceFile = compileJavaSourceFile(current); duke@1: duke@1: // Are we supposeded to compile this one? duke@1: duke@1: if (sourceFile) { duke@1: env.addGeneratedFile(file); duke@1: } duke@1: } duke@1: duke@1: // Now create an output stream and ask subclass to fill it up... duke@1: duke@1: try { duke@1: IndentingWriter out = new IndentingWriter( duke@1: new OutputStreamWriter(new FileOutputStream(file)),INDENT_STEP,TAB_SIZE); duke@1: duke@1: long startTime = 0; duke@1: if (env.verbose()) { duke@1: startTime = System.currentTimeMillis(); duke@1: } duke@1: duke@1: writeOutputFor(types[i],alreadyChecked,out); duke@1: out.close(); duke@1: duke@1: if (env.verbose()) { duke@1: long duration = System.currentTimeMillis() - startTime; duke@1: env.output(Main.getText("rmic.generated", file.getPath(), Long.toString(duration))); duke@1: } duke@1: if (sourceFile) { duke@1: env.parseFile(new ClassFile(file)); duke@1: } duke@1: } catch (IOException e) { duke@1: env.error(0, "cant.write", file.toString()); duke@1: return; duke@1: } duke@1: } else { duke@1: duke@1: // No, say so if we need to... duke@1: duke@1: if (env.verbose()) { duke@1: env.output(Main.getText("rmic.previously.generated", file.getPath())); duke@1: } duke@1: } duke@1: } duke@1: } duke@1: duke@1: /** duke@1: * Return the File object that should be used as the output file duke@1: * for the given OutputType. duke@1: * @param outputType The type to create a file for. duke@1: * @param destinationDir The directory to use as the root of the duke@1: * package heirarchy. May be null, in which case the current duke@1: * classpath is searched to find the directory in which to create duke@1: * the output file. If that search fails (most likely because the duke@1: * package directory lives in a zip or jar file rather than the duke@1: * file system), the current user directory is used. duke@1: */ duke@1: protected File getFileFor(OutputType outputType, File destinationDir) { duke@1: // Calling this method does some crucial initialization duke@1: // in a subclass implementation. Don't skip it. duke@1: Identifier id = getOutputId(outputType); duke@1: File packageDir = null; duke@1: if(idl){ duke@1: packageDir = Util.getOutputDirectoryForIDL(id,destinationDir,env); duke@1: } else { duke@1: packageDir = Util.getOutputDirectoryForStub(id,destinationDir,env); duke@1: } duke@1: String classFileName = outputType.getName() + getFileNameExtensionFor(outputType); duke@1: return new File(packageDir, classFileName); duke@1: } duke@1: duke@1: /** duke@1: * Return an identifier to use for output. duke@1: * @param outputType the type for which output is to be generated. duke@1: * @return the new identifier. This implementation returns the input parameter. duke@1: */ duke@1: protected Identifier getOutputId (OutputType outputType) { duke@1: return outputType.getType().getIdentifier(); duke@1: } duke@1: duke@1: /** duke@1: * Return true if the given file should be compiled. duke@1: * @param outputType One of the items returned by getOutputTypesFor(...) for duke@1: * which getFileNameExtensionFor(OutputType) returned ".java". duke@1: */ duke@1: protected boolean compileJavaSourceFile (OutputType outputType) { duke@1: return true; duke@1: } duke@1: duke@1: //_____________________________________________________________________ duke@1: // OutputType is a simple wrapper for a name and a Type duke@1: //_____________________________________________________________________ duke@1: duke@1: public class OutputType { duke@1: private String name; duke@1: private Type type; duke@1: duke@1: public OutputType (String name, Type type) { duke@1: this.name = name; duke@1: this.type = type; duke@1: } duke@1: duke@1: public String getName() { duke@1: return name; duke@1: } duke@1: duke@1: public Type getType() { duke@1: return type; duke@1: } duke@1: } duke@1: }