Search in sources :

Example 6 with JavacFileManager

use of com.sun.tools.javac.file.JavacFileManager in project ceylon-compiler by ceylon.

the class T6725036 method run.

void run() throws Exception {
    RelativeFile TEST_ENTRY_NAME = new RelativeFile("java/lang/String.class");
    File f = new File(System.getProperty("java.home"));
    if (!f.getName().equals("jre"))
        f = new File(f, "jre");
    File rt_jar = new File(new File(f, "lib"), "rt.jar");
    JarFile j = new JarFile(rt_jar);
    JarEntry je = j.getJarEntry(TEST_ENTRY_NAME.getPath());
    long jarEntryTime = je.getTime();
    ZipFileIndexCache zfic = ZipFileIndexCache.getSharedInstance();
    ZipFileIndex zfi = zfic.getZipFileIndex(rt_jar, null, false, null, false);
    long zfiTime = zfi.getLastModified(TEST_ENTRY_NAME);
    check(je, jarEntryTime, zfi + ":" + TEST_ENTRY_NAME.getPath(), zfiTime);
    Context context = new Context();
    JavacFileManager fm = new JavacFileManager(context, false, null);
    ZipFileIndexArchive zfia = new ZipFileIndexArchive(fm, zfi);
    JavaFileObject jfo = zfia.getFileObject(TEST_ENTRY_NAME.dirname(), TEST_ENTRY_NAME.basename());
    long jfoTime = jfo.getLastModified();
    check(je, jarEntryTime, jfo, jfoTime);
    if (errors > 0)
        throw new Exception(errors + " occurred");
}
Also used : Context(com.sun.tools.javac.util.Context) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) ZipFileIndexArchive(com.sun.tools.javac.file.ZipFileIndexArchive) JavaFileObject(javax.tools.JavaFileObject) ZipFileIndex(com.sun.tools.javac.file.ZipFileIndex) RelativeFile(com.sun.tools.javac.file.RelativePath.RelativeFile) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) RelativeFile(com.sun.tools.javac.file.RelativePath.RelativeFile) JarFile(java.util.jar.JarFile) File(java.io.File) ZipFileIndexCache(com.sun.tools.javac.file.ZipFileIndexCache)

Example 7 with JavacFileManager

use of com.sun.tools.javac.file.JavacFileManager in project ceylon-compiler by ceylon.

the class JavacTool method getStandardFileManager.

public JavacFileManager getStandardFileManager(DiagnosticListener<? super JavaFileObject> diagnosticListener, Locale locale, Charset charset) {
    Context context = new Context();
    context.put(Locale.class, locale);
    if (diagnosticListener != null)
        context.put(DiagnosticListener.class, diagnosticListener);
    PrintWriter pw = (charset == null) ? new PrintWriter(System.err, true) : new PrintWriter(new OutputStreamWriter(System.err, charset), true);
    context.put(Log.outKey, pw);
    return new JavacFileManager(context, true, charset);
}
Also used : Context(com.sun.tools.javac.util.Context) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter)

Example 8 with JavacFileManager

use of com.sun.tools.javac.file.JavacFileManager in project ceylon-compiler by ceylon.

the class Main method compile.

/** Programmatic interface for main function.
     * @param args    The command line parameters.
     */
public int compile(String[] args, AnnotationProcessorFactory factory) {
    int returnCode = 0;
    providedFactory = factory;
    Context context = new Context();
    JavacFileManager.preRegister(context);
    options = Options.instance(context);
    Bark bark;
    /*
         * Process the command line options to create the intial
         * options data.  This processing is at least partially reused
         * by any recursive apt calls.
         */
    // For testing: assume all arguments in forcedOpts are
    // prefixed to command line arguments.
    processArgs(forcedOpts);
    /*
         * A run of apt only gets passed the most recently generated
         * files; the initial run of apt gets passed the files from
         * the command line.
         */
    java.util.List<String> origFilenames;
    try {
        // assign args the result of parse to capture results of
        // '@file' expansion
        origFilenames = processArgs((args = CommandLine.parse(args)));
        if (options.get("suppress-tool-api-removal-message") == null) {
            Bark.printLines(out, getLocalizedString("misc.Deprecation"));
        }
        if (origFilenames == null) {
            return EXIT_CMDERR;
        } else if (origFilenames.size() == 0) {
            // it is allowed to compile nothing if just asking for help
            if (options.get("-help") != null || options.get("-X") != null)
                return EXIT_OK;
        }
    } catch (java.io.FileNotFoundException e) {
        Bark.printLines(out, ownName + ": " + getLocalizedString("err.file.not.found", e.getMessage()));
        return EXIT_SYSERR;
    } catch (IOException ex) {
        ioMessage(ex);
        return EXIT_SYSERR;
    } catch (OutOfMemoryError ex) {
        resourceMessage(ex);
        return EXIT_SYSERR;
    } catch (StackOverflowError ex) {
        resourceMessage(ex);
        return EXIT_SYSERR;
    } catch (FatalError ex) {
        feMessage(ex);
        return EXIT_SYSERR;
    } catch (sun.misc.ServiceConfigurationError sce) {
        sceMessage(sce);
        return EXIT_ABNORMAL;
    } catch (Throwable ex) {
        bugMessage(ex);
        return EXIT_ABNORMAL;
    }
    boolean firstRound = true;
    boolean needSourcePath = false;
    boolean needClassPath = false;
    boolean classesAsDecls = options.get("-XclassesAsDecls") != null;
    /*
         * Create augumented classpath and sourcepath values.
         *
         * If any of the prior apt rounds generated any new source
         * files, the n'th apt round (and any javac invocation) has the
         * source destination path ("-s path") as the last element of
         * the "-sourcepath" to the n'th call.
         *
         * If any of the prior apt rounds generated any new class files,
         * the n'th apt round (and any javac invocation) has the class
         * destination path ("-d path") as the last element of the
         * "-classpath" to the n'th call.
         */
    String augmentedSourcePath = "";
    String augmentedClassPath = "";
    String baseClassPath = "";
    try {
        /*
             * Record original options for future annotation processor
             * invocations.
             */
        origOptions = new HashMap<String, String>(options.size());
        for (String s : options.keySet()) {
            String value;
            if (s.equals(value = options.get(s)))
                origOptions.put(s, (String) null);
            else
                origOptions.put(s, value);
        }
        origOptions = Collections.unmodifiableMap(origOptions);
        JavacFileManager fm = (JavacFileManager) context.get(JavaFileManager.class);
        {
            // Note: it might be necessary to check for an empty
            // component ("") of the source path or class path
            String sourceDest = options.get("-s");
            if (fm.hasLocation(StandardLocation.SOURCE_PATH)) {
                for (File f : fm.getLocation(StandardLocation.SOURCE_PATH)) augmentedSourcePath += (f + File.pathSeparator);
                augmentedSourcePath += (sourceDest == null) ? "." : sourceDest;
            } else {
                augmentedSourcePath = ".";
                if (sourceDest != null)
                    augmentedSourcePath += (File.pathSeparator + sourceDest);
            }
            String classDest = options.get("-d");
            if (fm.hasLocation(StandardLocation.CLASS_PATH)) {
                for (File f : fm.getLocation(StandardLocation.CLASS_PATH)) baseClassPath += (f + File.pathSeparator);
                // put baseClassPath into map to handle any
                // value needed for the classloader
                options.put("-classpath", baseClassPath);
                augmentedClassPath = baseClassPath + ((classDest == null) ? "." : classDest);
            } else {
                baseClassPath = ".";
                if (classDest != null)
                    augmentedClassPath = baseClassPath + (File.pathSeparator + classDest);
            }
            assert options.get("-classpath") != null;
        }
        /*
             * Create base and augmented class loaders
             */
        ClassLoader augmentedAptCL = null;
        {
            /*
             * Use a url class loader to look for classes on the
             * user-specified class path. Prepend computed bootclass
             * path, which includes extdirs, to the URLClassLoader apt
             * uses.
             */
            String aptclasspath = "";
            String bcp = "";
            Iterable<? extends File> bootclasspath = fm.getLocation(StandardLocation.PLATFORM_CLASS_PATH);
            if (bootclasspath != null) {
                for (File f : bootclasspath) bcp += (f + File.pathSeparator);
            }
            // If the factory path is set, use that path
            if (providedFactory == null)
                aptclasspath = options.get("-factorypath");
            if (aptclasspath == null)
                aptclasspath = options.get("-classpath");
            assert aptclasspath != null;
            aptclasspath = (bcp + aptclasspath);
            aptCL = new URLClassLoader(pathToURLs(aptclasspath));
            if (providedFactory == null && // same CL even if new class files written
            options.get("-factorypath") != null)
                augmentedAptCL = aptCL;
            else {
                // Create class loader in case new class files are
                // written
                augmentedAptCL = new URLClassLoader(pathToURLs(augmentedClassPath.substring(baseClassPath.length())), aptCL);
            }
        }
        // For -XPrintAptRounds
        int round = 0;
        do {
            round++;
            Context newContext = new Context();
            // creates a new context
            Options newOptions = Options.instance(newContext);
            newOptions.putAll(options);
            // if genSource files, must add destination to source path
            if (genSourceFileNames.size() > 0 && !firstRound) {
                newOptions.put("-sourcepath", augmentedSourcePath);
                needSourcePath = true;
            }
            aggregateGenSourceFileNames.addAll(genSourceFileNames);
            sourceFileNames.addAll(genSourceFileNames);
            genSourceFileNames.clear();
            // "foo" to class path if any class files are generated
            if (genClassFileNames.size() > 0) {
                newOptions.put("-classpath", augmentedClassPath);
                aptCL = augmentedAptCL;
                needClassPath = true;
            }
            aggregateGenClassFileNames.addAll(genClassFileNames);
            classFileNames.addAll(genClassFileNames);
            genClassFileNames.clear();
            options = newOptions;
            if (options.get("-XPrintAptRounds") != null) {
                out.println("apt Round : " + round);
                out.println("filenames: " + sourceFileNames);
                if (classesAsDecls)
                    out.println("classnames: " + classFileNames);
                out.println("options: " + options);
            }
            returnCode = compile(args, newContext);
            firstRound = false;
            // Check for reported errors before continuing
            bark = Bark.instance(newContext);
        } while (((genSourceFileNames.size() != 0) || (classesAsDecls && genClassFileNames.size() != 0)) && bark.nerrors == 0);
    } catch (UsageMessageNeededException umne) {
        help();
        // will cause usage message to be printed
        return EXIT_CMDERR;
    }
    /*
         * Do not compile if a processor has reported an error or if
         * there are no source files to process.  A more sophisticated
         * test would also fail for syntax errors caught by javac.
         */
    if (options.get("-nocompile") == null && options.get("-print") == null && bark.nerrors == 0 && (origFilenames.size() > 0 || aggregateGenSourceFileNames.size() > 0)) {
        /*
             * Need to create new argument string for calling javac:
             * 1. apt specific arguments (e.g. -factory) must be stripped out
             * 2. proper settings for sourcepath and classpath must be used
             * 3. generated class names must be added
             * 4. class file names as declarations must be removed
             */
        int newArgsLength = args.length + (needSourcePath ? 1 : 0) + (needClassPath ? 1 : 0) + aggregateGenSourceFileNames.size();
        // class names from the javac argument list
        argLoop: for (int i = 0; i < args.length; i++) {
            int matchPosition = -1;
            // "-A" by itself is recognized by apt but not javac
            if (args[i] != null && args[i].equals("-A")) {
                newArgsLength--;
                args[i] = null;
                continue argLoop;
            } else {
                optionLoop: for (int j = 0; j < recognizedOptions.length; j++) {
                    if (args[i] != null && recognizedOptions[j].matches(args[i])) {
                        matchPosition = j;
                        break optionLoop;
                    }
                }
                if (matchPosition != -1) {
                    Option op = recognizedOptions[matchPosition];
                    if (op.aptOnly) {
                        newArgsLength--;
                        args[i] = null;
                        if (op.hasArg()) {
                            newArgsLength--;
                            args[i + 1] = null;
                        }
                    } else {
                        if (op.hasArg()) {
                            // skip over next string
                            i++;
                            continue argLoop;
                        }
                        if ((options.get("-XclassesAsDecls") != null) && (matchPosition == (recognizedOptions.length - 1))) {
                            // consideration by javac.
                            if (!args[i].endsWith(".java")) {
                                newArgsLength--;
                                args[i] = null;
                            }
                        }
                    }
                }
            }
        }
        String[] newArgs = new String[newArgsLength];
        int j = 0;
        for (int i = 0; i < args.length; i++) {
            if (args[i] != null)
                newArgs[j++] = args[i];
        }
        if (needClassPath)
            newArgs[j++] = "-XD-classpath=" + augmentedClassPath;
        if (needSourcePath) {
            newArgs[j++] = "-XD-sourcepath=" + augmentedSourcePath;
            for (String s : aggregateGenSourceFileNames) newArgs[j++] = s;
        }
        returnCode = com.sun.tools.javac.Main.compile(newArgs);
    }
    return returnCode;
}
Also used : Bark(com.sun.tools.apt.util.Bark) UsageMessageNeededException(com.sun.tools.apt.comp.UsageMessageNeededException) URLClassLoader(java.net.URLClassLoader) JavaFileManager(javax.tools.JavaFileManager) IOException(java.io.IOException) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) com.sun.tools.javac.util(com.sun.tools.javac.util) URLClassLoader(java.net.URLClassLoader) File(java.io.File)

Example 9 with JavacFileManager

use of com.sun.tools.javac.file.JavacFileManager in project ceylon-compiler by ceylon.

the class Main method compile.

/** Programmatic interface for main function.
     * @param args    The command line parameters.
     */
public int compile(String[] args, Context context, List<JavaFileObject> fileObjects, Iterable<? extends Processor> processors) {
    if (options == null)
        // creates a new one
        options = Options.instance(context);
    filenames = new ListBuffer<File>();
    classnames = new ListBuffer<String>();
    JavaCompiler comp = null;
    /*
         * TODO: Logic below about what is an acceptable command line
         * should be updated to take annotation processing semantics
         * into account.
         */
    try {
        if (args.length == 0 && fileObjects.isEmpty()) {
            help();
            return EXIT_CMDERR;
        }
        List<File> files;
        try {
            files = processArgs(CommandLine.parse(args));
            if (files == null) {
                // null signals an error in options, abort
                return EXIT_CMDERR;
            } else if (files.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) {
                // it is allowed to compile nothing if just asking for help or version info
                if (options.isSet(HELP) || options.isSet(X) || options.isSet(VERSION) || options.isSet(FULLVERSION))
                    return EXIT_OK;
                if (JavaCompiler.explicitAnnotationProcessingRequested(options)) {
                    error("err.no.source.files.classes");
                } else {
                    error("err.no.source.files");
                }
                return EXIT_CMDERR;
            }
        } catch (java.io.FileNotFoundException e) {
            Log.printLines(out, ownName + ": " + getLocalizedString("err.file.not.found", e.getMessage()));
            return EXIT_SYSERR;
        }
        boolean forceStdOut = options.isSet("stdout");
        if (forceStdOut) {
            out.flush();
            out = new PrintWriter(System.out, true);
        }
        context.put(Log.outKey, out);
        // allow System property in following line as a Mustang legacy
        boolean batchMode = (options.isUnset("nonBatchMode") && System.getProperty("nonBatchMode") == null);
        if (batchMode)
            CacheFSInfo.preRegister(context);
        fileManager = context.get(JavaFileManager.class);
        comp = JavaCompiler.instance(context);
        if (comp == null)
            return EXIT_SYSERR;
        Log log = Log.instance(context);
        if (!files.isEmpty()) {
            // add filenames to fileObjects
            comp = JavaCompiler.instance(context);
            List<JavaFileObject> otherFiles = List.nil();
            JavacFileManager dfm = (JavacFileManager) fileManager;
            for (JavaFileObject fo : dfm.getJavaFileObjectsFromFiles(files)) otherFiles = otherFiles.prepend(fo);
            for (JavaFileObject fo : otherFiles) fileObjects = fileObjects.prepend(fo);
        }
        comp.compile(fileObjects, classnames.toList(), processors);
        if (log.expectDiagKeys != null) {
            if (log.expectDiagKeys.isEmpty()) {
                Log.printLines(log.noticeWriter, "all expected diagnostics found");
                return EXIT_OK;
            } else {
                Log.printLines(log.noticeWriter, "expected diagnostic keys not found: " + log.expectDiagKeys);
                return EXIT_ERROR;
            }
        }
        if (comp.errorCount() != 0)
            return EXIT_ERROR;
    } catch (IOException ex) {
        ioMessage(ex);
        return EXIT_SYSERR;
    } catch (OutOfMemoryError ex) {
        resourceMessage(ex);
        return EXIT_SYSERR;
    } catch (StackOverflowError ex) {
        resourceMessage(ex);
        return EXIT_SYSERR;
    } catch (FatalError ex) {
        feMessage(ex);
        return EXIT_SYSERR;
    } catch (AnnotationProcessingError ex) {
        if (apiMode)
            throw new RuntimeException(ex.getCause());
        apMessage(ex);
        return EXIT_SYSERR;
    } catch (ClientCodeException ex) {
        // and javax.tools.JavaCompiler.CompilationTask#call
        throw new RuntimeException(ex.getCause());
    } catch (PropagatedException ex) {
        throw ex.getCause();
    } catch (Throwable ex) {
        // exceptions.
        if (comp == null || comp.errorCount() == 0 || options == null || options.isSet("dev"))
            bugMessage(ex);
        return EXIT_ABNORMAL;
    } finally {
        if (comp != null) {
            try {
                comp.close();
            } catch (ClientCodeException ex) {
                throw new RuntimeException(ex.getCause());
            }
        }
        filenames = null;
        options = null;
    }
    return EXIT_OK;
}
Also used : JavaFileManager(javax.tools.JavaFileManager) IOException(java.io.IOException) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) AnnotationProcessingError(com.sun.tools.javac.processing.AnnotationProcessingError) JavaFileObject(javax.tools.JavaFileObject) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 10 with JavacFileManager

use of com.sun.tools.javac.file.JavacFileManager in project ceylon-compiler by ceylon.

the class T6589361 method main.

public static void main(String[] args) throws Exception {
    JavacFileManager fm = null;
    try {
        fm = new JavacFileManager(new Context(), false, null);
        Set<JavaFileObject.Kind> set = new HashSet<JavaFileObject.Kind>();
        set.add(JavaFileObject.Kind.CLASS);
        Iterable<JavaFileObject> files = fm.list(StandardLocation.PLATFORM_CLASS_PATH, "java.lang", set, false);
        for (JavaFileObject file : files) {
            // we normalize the filename as well.
            if (file.getName().replace(File.separatorChar, '/').contains("java/lang/Object.class")) {
                String str = fm.inferBinaryName(StandardLocation.CLASS_PATH, file);
                if (!str.equals("java.lang.Object")) {
                    throw new AssertionError("Error in JavacFileManager.inferBinaryName method!");
                } else {
                    return;
                }
            }
        }
    } finally {
        if (fm != null) {
            fm.close();
        }
    }
    throw new AssertionError("Could not find java/lang/Object.class while compiling");
}
Also used : JavacFileManager(com.sun.tools.javac.file.JavacFileManager) Context(com.sun.tools.javac.util.Context) JavaFileObject(javax.tools.JavaFileObject) Kind(javax.tools.JavaFileObject.Kind) HashSet(java.util.HashSet)

Aggregations

JavacFileManager (com.sun.tools.javac.file.JavacFileManager)35 Context (com.sun.tools.javac.util.Context)19 JavaFileObject (javax.tools.JavaFileObject)10 File (java.io.File)9 IOException (java.io.IOException)7 PrintWriter (java.io.PrintWriter)7 JavaFileManager (javax.tools.JavaFileManager)7 VirtualFile (com.redhat.ceylon.compiler.typechecker.io.VirtualFile)5 Path (java.nio.file.Path)5 JavacTask (com.sun.source.util.JavacTask)4 Options (com.sun.tools.javac.util.Options)4 OutputStreamWriter (java.io.OutputStreamWriter)4 BufferedWriter (java.io.BufferedWriter)3 Deps (com.google.devtools.build.lib.view.proto.Deps)2 JavacTool (com.sun.tools.javac.api.JavacTool)2 JavaCompiler (com.sun.tools.javac.main.JavaCompiler)2 AnnotationProcessingError (com.sun.tools.javac.processing.AnnotationProcessingError)2 PropagatedException (com.sun.tools.javac.util.PropagatedException)2 DiagnosticCollector (javax.tools.DiagnosticCollector)2 Test (org.junit.Test)2