void test(List<String> opts, Main.Result expectResult, Set<Message> expectMessages) {
    System.err.println("test: " + opts);
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    List<JavaFileObject> files = Arrays.asList(file);
    try {
      JavacTask t = (JavacTask) javac.getTask(pw, fm, null, opts, null, files);
      boolean ok = t.call();
      pw.close();
      String out = sw.toString().replaceAll("[\r\n]+", "\n");
      if (!out.isEmpty()) System.err.println(out);
      if (ok && expectResult != Main.Result.OK) {
        error("Compilation succeeded unexpectedly");
      } else if (!ok && expectResult != Main.Result.ERROR) {
        error("Compilation failed unexpectedly");
      } else check(out, expectMessages);
    } catch (IllegalArgumentException e) {
      System.err.println(e);
      String expectOut = expectMessages.iterator().next().text;
      if (expectResult != Main.Result.CMDERR) error("unexpected exception caught");
      else if (!e.getMessage().equals(expectOut)) {
        error("unexpected exception message: " + e.getMessage() + " expected: " + expectOut);
      }
    }

    //        if (errors > 0)
    //            throw new Error("stop");
  }
Example #2
0
  public static void main(String... args) throws Throwable {
    String testSrcDir = System.getProperty("test.src");
    String testClassDir = System.getProperty("test.classes");
    String self = T6361619.class.getName();

    JavacTool tool = JavacTool.create();

    final PrintWriter out = new PrintWriter(System.err, true);

    Iterable<String> flags =
        Arrays.asList(
            "-processorpath", testClassDir,
            "-processor", self,
            "-d", ".");
    DiagnosticListener<JavaFileObject> dl =
        new DiagnosticListener<JavaFileObject>() {
          public void report(Diagnostic<? extends JavaFileObject> m) {
            out.println(m);
          }
        };

    StandardJavaFileManager fm = tool.getStandardFileManager(dl, null, null);
    Iterable<? extends JavaFileObject> f =
        fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrcDir, self + ".java")));

    JavacTask task = tool.getTask(out, fm, dl, flags, null, f);
    MyTaskListener tl = new MyTaskListener(task);
    task.setTaskListener(tl);

    // should complete, without exceptions
    task.call();
  }
Example #3
0
  /**
   * The worker method for each test case. Compile the files and verify that exactly the expected
   * set of header files is generated.
   */
  void test(RunKind rk, GenKind gk, List<File> files, Set<String> expect) throws Exception {
    List<String> args = new ArrayList<String>();
    if (gk == GenKind.FULL) args.add("-XDjavah:full");

    switch (rk) {
      case CMD:
        args.add("-d");
        args.add(classesDir.getPath());
        args.add("-h");
        args.add(headersDir.getPath());
        for (File f : files) args.add(f.getPath());
        int rc = com.sun.tools.javac.Main.compile(args.toArray(new String[args.size()]));
        if (rc != 0) throw new Exception("compilation failed, rc=" + rc);
        break;

      case API:
        fm.setLocation(StandardLocation.SOURCE_PATH, Arrays.asList(srcDir));
        fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(classesDir));
        fm.setLocation(StandardLocation.NATIVE_HEADER_OUTPUT, Arrays.asList(headersDir));
        JavacTask task =
            javac.getTask(null, fm, null, args, null, fm.getJavaFileObjectsFromFiles(files));
        if (!task.call()) throw new Exception("compilation failed");
        break;
    }

    Set<String> found = createSet(headersDir.list());
    checkEqual("header files", expect, found);
  }
Example #4
0
 @Override
 public void run() {
   int id = checkCount.incrementAndGet();
   final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
   JavaSource source = new JavaSource(id);
   JavacTask ct =
       (JavacTask) tool.getTask(null, fm.get(), null, null, null, Arrays.asList(source));
   ct.call();
   verifyBytecode(source, id);
 }
Example #5
0
 void compileAndCheck(
     VarargsMethod m1, VarargsMethod m2, TypeKind actual, ArgumentsArity argsArity)
     throws Exception {
   final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
   JavaSource source = new JavaSource(m1, m2, actual, argsArity);
   ErrorChecker ec = new ErrorChecker();
   JavacTask ct = (JavacTask) tool.getTask(null, fm, ec, null, null, Arrays.asList(source));
   ct.generate();
   check(source, ec, m1, m2, actual, argsArity);
 }
Example #6
0
  private File compileOne(Type type) {
    if (this.flags.contains(Flags.USECACHE)) {
      File dir = cache.get(type.getName());
      if (dir != null) {
        return dir;
      }
    }
    List<JavaFileObject> files = new ArrayList<>();
    SourceProcessor accum = (name, src) -> files.add(new SourceFile(name, src));

    for (Type dep : type.typeDependencies()) {
      dep.generateAsDependency(accum, type.methodDependencies());
    }

    type.generate(accum);

    JavacTask ct =
        (JavacTask) this.systemJavaCompiler.getTask(null, this.fm, null, null, null, files);
    File destDir = null;
    do {
      int value = counter.incrementAndGet();
      destDir = new File(root, Integer.toString(value));
    } while (destDir.exists());

    if (this.flags.contains(Flags.VERBOSE)) {
      System.out.println("Compilation unit for " + type.getName() + " : compiled into " + destDir);
      for (JavaFileObject jfo : files) {
        System.out.println(jfo.toString());
      }
    }

    try {
      destDir.mkdirs();
      this.fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
    } catch (IOException e) {
      throw new RuntimeException(
          "IOException encountered during compilation: " + e.getMessage(), e);
    }
    Boolean result = ct.call();
    if (result == Boolean.FALSE) {
      throw new RuntimeException("Compilation failure in " + type.getName() + " unit");
    }
    if (this.flags.contains(Flags.USECACHE)) {
      File existing = cache.putIfAbsent(type.getName(), destDir);
      if (existing != null) {
        deleteDir(destDir);
        return existing;
      }
    } else {
      this.tempDirs.add(destDir);
    }
    return destDir;
  }
  public static void main(String... args) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
      JavacTask task =
          (JavacTask)
              compiler.getTask(
                  null, fileManager, null, null, null, fileManager.getJavaFileObjects(args));

      task.parse().forEach(cu -> cu.accept(new SampleVisitor(), null));
    }
  }
 @Override
 public void run() {
   JavacTask ct =
       (JavacTask) comp.getTask(null, fm.get(), diagChecker, null, null, Arrays.asList(source));
   try {
     ct.parse();
   } catch (Throwable ex) {
     processException(ex);
     return;
   }
   check();
 }
Example #9
0
  void run() throws IOException {
    JavacTool tool = (JavacTool) ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);

    File classes = new File("classes");
    classes.mkdirs();
    File extraClasses = new File("extraClasses");
    extraClasses.mkdirs();

    System.out.println("compiling classes to extraClasses");
    { // setup class in extraClasses
      fm.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(extraClasses));
      List<? extends JavaFileObject> files =
          Arrays.asList(
              new MemFile("AnnoProc.java", annoProc), new MemFile("Callback.java", callback));
      JavacTask task = tool.getTask(null, fm, null, null, null, files);
      check(task.call());
    }

    System.out.println("compiling dummy to classes with anno processor");
    { // use that class in a TaskListener after processing has completed
      PrintStream prev = System.out;
      String out;
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      try (PrintStream ps = new PrintStream(baos)) {
        System.setOut(ps);
        File testClasses = new File(System.getProperty("test.classes"));
        fm.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(classes));
        fm.setLocation(
            StandardLocation.ANNOTATION_PROCESSOR_PATH, Arrays.asList(extraClasses, testClasses));
        List<? extends JavaFileObject> files =
            Arrays.asList(new MemFile("my://dummy", "class Dummy { }"));
        List<String> options = Arrays.asList("-processor", "AnnoProc");
        JavacTask task = tool.getTask(null, fm, null, options, null, files);
        task.setTaskListener(this);
        check(task.call());
      } finally {
        System.setOut(prev);
        out = baos.toString();
        if (!out.isEmpty()) System.out.println(out);
      }
      check(out.contains("AnnoProc$1: run()"));
      check(out.contains("Callback: run()"));
    }
  }
 @Override
 public final void init(ProcessingEnvironment env) {
   super.init(env);
   JavacTask.instance(env).addTaskListener(listener);
   Context ctx = ((JavacProcessingEnvironment) processingEnv).getContext();
   JavaCompiler compiler = JavaCompiler.instance(ctx);
   compiler.shouldStopPolicyIfNoError =
       CompileState.max(compiler.shouldStopPolicyIfNoError, CompileState.FLOW);
 }
Example #11
0
 public static void add(ProcessingEnvironment env, Runnable r) {
   try {
     JavacTask task = JavacTask.instance(env);
     TaskListener l = ((BasicJavacTask) task).getTaskListeners().iterator().next();
     // The TaskListener is an instanceof TestClose, but when using the
     // default class loaders. the taskListener uses a different
     // instance of Class<TestClose> than the anno processor.
     // If you try to evaluate
     //      TestClose tc = (TestClose) (l).
     // you get the following somewhat confusing error:
     //   java.lang.ClassCastException: TestClose cannot be cast to TestClose
     // The workaround is to access the fields of TestClose with reflection.
     Field f = l.getClass().getField("runnables");
     @SuppressWarnings("unchecked")
     List<Runnable> runnables = (List<Runnable>) f.get(l);
     runnables.add(r);
   } catch (Throwable t) {
     t.printStackTrace();
   }
 }
  public static void main(String... args) throws IOException, URISyntaxException {
    if (args.length != 1) throw new IllegalStateException("Must provide class name!");
    String testContent = null;
    List<File> sourcePath = new ArrayList<>();
    for (String sourcePaths : System.getProperty("test.src.path").split(":")) {
      sourcePath.add(new File(sourcePaths));
    }
    JavacFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);
    for (File sp : sourcePath) {
      File inp = new File(sp, args[0]);

      if (inp.canRead()) {
        testContent = fm.getRegularFile(inp.toPath()).getCharContent(true).toString();
      }
    }
    if (testContent == null) throw new IllegalStateException();
    final List<Diagnostic<?>> diagnostics = new ArrayList<>();
    DiagnosticListener<JavaFileObject> collectDiagnostics =
        new DiagnosticListener<JavaFileObject>() {
          @Override
          public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            diagnostics.add(diagnostic);
          }
        };
    JavaFileObject testFile = new TestFO(new URI("mem://" + args[0]), testContent);
    JavacTask task =
        JavacTool.create()
            .getTask(
                null,
                new TestFM(fm),
                collectDiagnostics,
                STANDARD_PARAMS,
                null,
                Arrays.asList(testFile));
    final Trees trees = Trees.instance(task);
    final CompilationUnitTree cut = task.parse().iterator().next();
    task.analyze();

    final List<int[]> declarationSpans = new ArrayList<>();

    new TreeScanner<Void, Void>() {
      @Override
      public Void visitClass(ClassTree node, Void p) {
        handleDeclaration(node);
        return super.visitClass(node, p);
      }

      @Override
      public Void visitMethod(MethodTree node, Void p) {
        handleDeclaration(node);
        return super.visitMethod(node, p);
      }

      @Override
      public Void visitVariable(VariableTree node, Void p) {
        handleDeclaration(node);
        return super.visitVariable(node, p);
      }

      @Override
      public Void visitNewClass(NewClassTree node, Void p) {
        if (node.getClassBody() != null) {
          scan(node.getClassBody().getMembers(), null);
        }
        return null;
      }

      private void handleDeclaration(Tree node) {
        int endPos = (int) trees.getSourcePositions().getEndPosition(cut, node);

        if (endPos == (-1)) {
          if (node.getKind() == Tree.Kind.METHOD
              && (((JCMethodDecl) node).getModifiers().flags & Flags.GENERATEDCONSTR) != 0) {
            return;
          }
          throw new IllegalStateException();
        }

        declarationSpans.add(
            new int[] {(int) trees.getSourcePositions().getStartPosition(cut, node), endPos});
      }
    }.scan(cut, null);

    for (final int[] declarationSpan : declarationSpans) {
      final String suppressWarnings =
          "@SuppressWarnings({\"deprecation\", \"unchecked\", \"serial\", \"divzero\"})";
      final String updatedContent =
          testContent.substring(0, declarationSpan[0])
              + suppressWarnings
              + testContent.substring(declarationSpan[0]);
      final List<Diagnostic<?>> foundErrors = new ArrayList<>(diagnostics);
      DiagnosticListener<JavaFileObject> verifyDiagnostics =
          new DiagnosticListener<JavaFileObject>() {
            @Override
            public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
              long adjustedPos = diagnostic.getPosition();

              if (adjustedPos >= declarationSpan[0]) adjustedPos -= suppressWarnings.length();

              if (declarationSpan[0] <= adjustedPos && adjustedPos <= declarationSpan[1]) {
                throw new IllegalStateException("unsuppressed: " + diagnostic.getMessage(null));
              }

              boolean found = false;

              for (Iterator<Diagnostic<?>> it = foundErrors.iterator(); it.hasNext(); ) {
                Diagnostic<?> d = it.next();
                if (d.getPosition() == adjustedPos && d.getCode().equals(diagnostic.getCode())) {
                  it.remove();
                  found = true;
                  break;
                }
              }

              if (!found) {
                throw new IllegalStateException(
                    "diagnostic not originally reported: " + diagnostic.getMessage(null));
              }
            }
          };

      JavaFileObject updatedFile = new TestFO(new URI("mem://" + args[0]), updatedContent);
      JavacTask testTask =
          JavacTool.create()
              .getTask(
                  null,
                  new TestFM(fm),
                  verifyDiagnostics,
                  STANDARD_PARAMS,
                  null,
                  Arrays.asList(updatedFile));

      testTask.analyze();

      for (Diagnostic<?> d : foundErrors) {
        if (d.getPosition() < declarationSpan[0] || declarationSpan[1] < d.getPosition()) {
          throw new IllegalStateException("missing: " + d.getMessage(null));
        }
      }
    }
  }
    void run(PrintWriter out, String... args) throws IOException {
      JavaCompiler c = ToolProvider.getSystemJavaCompiler();
      StandardJavaFileManager fm = c.getStandardFileManager(null, null, null);

      // DPrinter options
      final Set<TaskEvent.Kind> before = EnumSet.noneOf(TaskEvent.Kind.class);
      final Set<TaskEvent.Kind> after = EnumSet.noneOf(TaskEvent.Kind.class);
      boolean showPositions = false;
      boolean showSource = false;
      boolean showTreeSymbols = false;
      boolean showTreeTypes = false;
      boolean showEmptyItems = true;
      boolean showNulls = true;

      // javac options
      Collection<String> options = new ArrayList<String>();
      Collection<File> files = new ArrayList<File>();
      String classpath = null;
      String classoutdir = null;

      final Handler h = getHandlers().get(args[0]);
      if (h == null) throw new IllegalArgumentException(args[0]);

      for (int i = 1; i < args.length; i++) {
        String arg = args[i];
        if (arg.equals("-before") && i + 1 < args.length) {
          before.add(getKind(args[++i]));
        } else if (arg.equals("-after") && i + 1 < args.length) {
          after.add(getKind(args[++i]));
        } else if (arg.equals("-showPositions")) {
          showPositions = true;
        } else if (arg.equals("-showSource")) {
          showSource = true;
        } else if (arg.equals("-showTreeSymbols")) {
          showTreeSymbols = true;
        } else if (arg.equals("-showTreeTypes")) {
          showTreeTypes = true;
        } else if (arg.equals("-hideEmptyLists")) {
          showEmptyItems = false;
        } else if (arg.equals("-hideNulls")) {
          showNulls = false;
        } else if (arg.equals("-classpath") && i + 1 < args.length) {
          classpath = args[++i];
        } else if (arg.equals("-d") && i + 1 < args.length) {
          classoutdir = args[++i];
        } else if (arg.startsWith("-")) {
          int n = c.isSupportedOption(arg);
          if (n < 0) throw new IllegalArgumentException(arg);
          options.add(arg);
          while (n > 0) options.add(args[++i]);
        } else if (arg.endsWith(".java")) {
          files.add(new File(arg));
        }
      }

      if (classoutdir != null) {
        fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(classoutdir)));
      }

      if (classpath != null) {
        Collection<File> path = new ArrayList<File>();
        for (String p : classpath.split(File.pathSeparator)) {
          if (p.isEmpty()) continue;
          File f = new File(p);
          if (f.exists()) path.add(f);
        }
        fm.setLocation(StandardLocation.CLASS_PATH, path);
      }
      Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files);

      JavacTask task = (JavacTask) c.getTask(out, fm, null, options, null, fos);
      final Trees trees = Trees.instance(task);

      final DPrinter dprinter = new DPrinter(out, trees);
      dprinter
          .source(showSource)
          .emptyItems(showEmptyItems)
          .nulls(showNulls)
          .positions(showPositions)
          .treeSymbols(showTreeSymbols)
          .treeTypes(showTreeTypes);

      if (before.isEmpty() && after.isEmpty()) {
        if (h.name.equals("trees") && !showTreeSymbols && !showTreeTypes)
          after.add(TaskEvent.Kind.PARSE);
        else after.add(TaskEvent.Kind.ANALYZE);
      }

      task.addTaskListener(
          new TaskListener() {
            public void started(TaskEvent e) {
              if (before.contains(e.getKind())) handle(e);
            }

            public void finished(TaskEvent e) {
              if (after.contains(e.getKind())) handle(e);
            }

            private void handle(TaskEvent e) {
              JCCompilationUnit unit = (JCCompilationUnit) e.getCompilationUnit();
              switch (e.getKind()) {
                case PARSE:
                case ENTER:
                  h.handle(e.getSourceFile().getName(), unit, unit, dprinter);
                  break;

                default:
                  TypeElement elem = e.getTypeElement();
                  h.handle(elem.toString(), unit, (JCTree) trees.getTree(elem), dprinter);
                  break;
              }
            }
          });

      task.call();
    }