Search in sources :

Example 41 with JavaFileObject

use of org.eclipse.ceylon.javax.tools.JavaFileObject in project ceylon by eclipse.

the class Main method compile.

public Result compile(String[] args, String[] classNames, Context context, List<JavaFileObject> fileObjects, Iterable<? extends Processor> processors) {
    context.put(Log.outKey, out);
    log = Log.instance(context);
    if (options == null)
        // creates a new one
        options = Options.instance(context);
    filenames = new LinkedHashSet<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 && (classNames == null || classNames.length == 0) && fileObjects.isEmpty()) {
            Option.HELP.process(optionHelper, "-help");
            return Result.CMDERR;
        }
        Collection<File> files;
        try {
            files = processArgs(CommandLine.parse(args), classNames);
            if (files == null) {
                // null signals an error in options, abort
                return Result.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 Result.OK;
                if (JavaCompiler.explicitAnnotationProcessingRequested(options)) {
                    error("err.no.source.files.classes");
                } else {
                    error("err.no.source.files");
                }
                return Result.CMDERR;
            }
        } catch (java.io.FileNotFoundException e) {
            warning("err.file.not.found", e.getMessage());
            return Result.SYSERR;
        }
        boolean forceStdOut = options.isSet("stdout");
        if (forceStdOut) {
            log.flush();
            log.setWriters(new PrintWriter(System.out, true));
        }
        // allow System property in following line as a Mustang legacy
        boolean batchMode = (options.isUnset("nonBatchMode") && System.getProperty("nonBatchMode") == null);
        if (batchMode)
            CacheFSInfo.preRegister(context);
        // FIXME: this code will not be invoked if using JavacTask.parse/analyze/generate
        // invoke any available plugins
        String plugins = options.get(PLUGIN);
        if (plugins != null) {
            JavacProcessingEnvironment pEnv = JavacProcessingEnvironment.instance(context);
            ClassLoader cl = pEnv.getProcessorClassLoader();
            ServiceLoader<Plugin> sl = ServiceLoader.load(Plugin.class, cl);
            Set<List<String>> pluginsToCall = new LinkedHashSet<List<String>>();
            for (String plugin : plugins.split("\\x00")) {
                pluginsToCall.add(List.from(plugin.split("\\s+")));
            }
            JavacTask task = null;
            Iterator<Plugin> iter = sl.iterator();
            while (iter.hasNext()) {
                Plugin plugin = iter.next();
                for (List<String> p : pluginsToCall) {
                    if (plugin.getName().equals(p.head)) {
                        pluginsToCall.remove(p);
                        try {
                            if (task == null)
                                task = JavacTask.instance(pEnv);
                            plugin.init(task, p.tail.toArray(new String[p.tail.size()]));
                        } catch (Throwable ex) {
                            if (apiMode)
                                throw new RuntimeException(ex);
                            pluginMessage(ex);
                            return Result.SYSERR;
                        }
                    }
                }
            }
            for (List<String> p : pluginsToCall) {
                log.printLines(PrefixKind.JAVAC, "msg.plugin.not.found", p.head);
            }
        }
        comp = JavaCompiler.instance(context);
        fileManager = context.get(JavaFileManager.class);
        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.printRawLines("all expected diagnostics found");
                return Result.OK;
            } else {
                log.printRawLines("expected diagnostic keys not found: " + log.expectDiagKeys);
                return Result.ERROR;
            }
        }
        if (comp.errorCount() != 0)
            return Result.ERROR;
    } catch (IOException ex) {
        ioMessage(ex);
        return Result.SYSERR;
    } catch (OutOfMemoryError ex) {
        resourceMessage(ex);
        return Result.SYSERR;
    } catch (StackOverflowError ex) {
        resourceMessage(ex);
        return Result.SYSERR;
    } catch (FatalError ex) {
        feMessage(ex);
        return Result.SYSERR;
    } catch (AnnotationProcessingError ex) {
        if (apiMode)
            throw new RuntimeException(ex.getCause());
        apMessage(ex);
        return Result.SYSERR;
    } catch (ClientCodeException ex) {
        // and org.eclipse.ceylon.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 Result.ABNORMAL;
    } finally {
        if (comp != null) {
            try {
                comp.close();
            } catch (ClientCodeException ex) {
                throw new RuntimeException(ex.getCause());
            }
        }
        filenames = null;
        options = null;
    }
    return Result.OK;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) JavaFileObject(org.eclipse.ceylon.javax.tools.JavaFileObject) JavacTask(org.eclipse.ceylon.langtools.source.util.JavacTask) BasicJavacTask(org.eclipse.ceylon.langtools.tools.javac.api.BasicJavacTask) PrintWriter(java.io.PrintWriter) JavaFileManager(org.eclipse.ceylon.javax.tools.JavaFileManager) IOException(java.io.IOException) JavacFileManager(org.eclipse.ceylon.langtools.tools.javac.file.JavacFileManager) AnnotationProcessingError(org.eclipse.ceylon.langtools.tools.javac.processing.AnnotationProcessingError) JavacProcessingEnvironment(org.eclipse.ceylon.langtools.tools.javac.processing.JavacProcessingEnvironment) File(java.io.File) Plugin(org.eclipse.ceylon.langtools.source.util.Plugin)

Example 42 with JavaFileObject

use of org.eclipse.ceylon.javax.tools.JavaFileObject in project ceylon by eclipse.

the class ClassWriter method writeClass.

/**
 * Emit a class file for a given class.
 *  @param c      The class from which a class file is generated.
 */
public JavaFileObject writeClass(ClassSymbol c) throws IOException, PoolOverflow, StringOverflow {
    JavaFileObject outFile = fileManager.getJavaFileForOutput(CLASS_OUTPUT, c.flatname.toString(), JavaFileObject.Kind.CLASS, c.sourcefile);
    OutputStream out = outFile.openOutputStream();
    try {
        writeClassFile(out, c);
        if (verbose)
            log.printVerbose("wrote.file", outFile);
        out.close();
        out = null;
    } finally {
        if (out != null) {
            // if we are propagating an exception, delete the file
            out.close();
            outFile.delete();
            outFile = null;
        }
    }
    // may be null if write failed
    return outFile;
}
Also used : JavaFileObject(org.eclipse.ceylon.javax.tools.JavaFileObject)

Example 43 with JavaFileObject

use of org.eclipse.ceylon.javax.tools.JavaFileObject in project ceylon by eclipse.

the class JavacElements method getSourcePosition.

public JavacSourcePosition getSourcePosition(Element e) {
    Pair<JCTree, JCCompilationUnit> treeTop = getTreeAndTopLevel(e);
    if (treeTop == null)
        return null;
    JCTree tree = treeTop.fst;
    JCCompilationUnit toplevel = treeTop.snd;
    JavaFileObject sourcefile = toplevel.sourcefile;
    if (sourcefile == null)
        return null;
    return new JavacSourcePosition(sourcefile, tree.pos, toplevel.lineMap);
}
Also used : JavaFileObject(org.eclipse.ceylon.javax.tools.JavaFileObject) JCTree(org.eclipse.ceylon.langtools.tools.javac.tree.JCTree)

Example 44 with JavaFileObject

use of org.eclipse.ceylon.javax.tools.JavaFileObject in project ceylon by eclipse.

the class JavacPathFileManager method list.

private void list(Path path, String packageName, final Set<Kind> kinds, boolean recurse, final ListBuffer<JavaFileObject> results) throws IOException {
    if (!Files.exists(path))
        return;
    final Path pathDir;
    if (isDirectory(path))
        pathDir = path;
    else {
        FileSystem fs = getFileSystem(path);
        if (fs == null)
            return;
        pathDir = fs.getRootDirectories().iterator().next();
    }
    String sep = path.getFileSystem().getSeparator();
    Path packageDir = packageName.isEmpty() ? pathDir : pathDir.resolve(packageName.replace(".", sep));
    if (!Files.exists(packageDir))
        return;
    /* Alternate impl of list, superceded by use of Files.walkFileTree */
    // Deque<Path> queue = new LinkedList<Path>();
    // queue.add(packageDir);
    // 
    // Path dir;
    // while ((dir = queue.poll()) != null) {
    // DirectoryStream<Path> ds = dir.newDirectoryStream();
    // try {
    // for (Path p: ds) {
    // String name = p.getFileName().toString();
    // if (isDirectory(p)) {
    // if (recurse && SourceVersion.isIdentifier(name)) {
    // queue.add(p);
    // }
    // } else {
    // if (kinds.contains(getKind(name))) {
    // JavaFileObject fe =
    // PathFileObject.createDirectoryPathFileObject(this, p, pathDir);
    // results.append(fe);
    // }
    // }
    // }
    // } finally {
    // ds.close();
    // }
    // }
    int maxDepth = (recurse ? Integer.MAX_VALUE : 1);
    Set<FileVisitOption> opts = EnumSet.of(FOLLOW_LINKS);
    Files.walkFileTree(packageDir, opts, maxDepth, new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            Path name = dir.getFileName();
            if (// JSR 292?
            name == null || SourceVersion.isIdentifier(name.toString()))
                return FileVisitResult.CONTINUE;
            else
                return FileVisitResult.SKIP_SUBTREE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            if (attrs.isRegularFile() && kinds.contains(getKind(file.getFileName().toString()))) {
                JavaFileObject fe = PathFileObject.createDirectoryPathFileObject(JavacPathFileManager.this, file, pathDir);
                results.append(fe);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}
Also used : Path(java.nio.file.Path) JavaFileObject(org.eclipse.ceylon.javax.tools.JavaFileObject) FileVisitOption(java.nio.file.FileVisitOption) FileSystem(java.nio.file.FileSystem) FileVisitResult(java.nio.file.FileVisitResult) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 45 with JavaFileObject

use of org.eclipse.ceylon.javax.tools.JavaFileObject in project ceylon by eclipse.

the class JavacPathFileManager method list.

@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse) throws IOException {
    // validatePackageName(packageName);
    nullCheck(packageName);
    nullCheck(kinds);
    Iterable<? extends Path> paths = getLocation(location);
    if (paths == null)
        return List.nil();
    ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
    for (Path path : paths) list(path, packageName, kinds, recurse, results);
    return results.toList();
}
Also used : Path(java.nio.file.Path) JavaFileObject(org.eclipse.ceylon.javax.tools.JavaFileObject) ListBuffer(org.eclipse.ceylon.langtools.tools.javac.util.ListBuffer)

Aggregations

JavaFileObject (org.eclipse.ceylon.javax.tools.JavaFileObject)53 JCTree (org.eclipse.ceylon.langtools.tools.javac.tree.JCTree)9 File (java.io.File)8 IOException (java.io.IOException)8 HashSet (java.util.HashSet)8 CeylonFileObject (org.eclipse.ceylon.compiler.java.codegen.CeylonFileObject)5 TaskEvent (org.eclipse.ceylon.langtools.source.util.TaskEvent)5 Symbol (org.eclipse.ceylon.langtools.tools.javac.code.Symbol)5 Type (org.eclipse.ceylon.langtools.tools.javac.code.Type)5 InputStream (java.io.InputStream)4 ListBuffer (org.eclipse.ceylon.langtools.tools.javac.util.ListBuffer)4 LinkedHashSet (java.util.LinkedHashSet)3 VirtualFile (org.eclipse.ceylon.compiler.typechecker.io.VirtualFile)3 JavacFileManager (org.eclipse.ceylon.langtools.tools.javac.file.JavacFileManager)3 JCCompilationUnit (org.eclipse.ceylon.langtools.tools.javac.tree.JCTree.JCCompilationUnit)3 FileInputStream (java.io.FileInputStream)2 OutputStream (java.io.OutputStream)2 PrintWriter (java.io.PrintWriter)2 ByteBuffer (java.nio.ByteBuffer)2 CharBuffer (java.nio.CharBuffer)2