コード例 #1
0
  void test(String[] opts, String className) throws Exception {
    count++;
    System.err.println("Test " + count + " " + Arrays.asList(opts) + " " + className);
    Path testSrcDir = Paths.get(System.getProperty("test.src"));
    Path testClassesDir = Paths.get(System.getProperty("test.classes"));
    Path classes = Paths.get("classes." + count);
    classes.createDirectory();

    Context ctx = new Context();
    PathFileManager fm = new JavacPathFileManager(ctx, true, null);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    List<String> options = new ArrayList<String>();
    options.addAll(Arrays.asList(opts));
    options.addAll(Arrays.asList("-verbose", "-XDverboseCompilePolicy", "-d", classes.toString()));
    Iterable<? extends JavaFileObject> compilationUnits =
        fm.getJavaFileObjects(testSrcDir.resolve(className + ".java"));
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    JavaCompiler.CompilationTask t =
        compiler.getTask(out, fm, null, options, null, compilationUnits);
    boolean ok = t.call();
    System.err.println(sw.toString());
    if (!ok) {
      throw new Exception("compilation failed");
    }

    File expect = new File("classes." + count + "/" + className + ".class");
    if (!expect.exists()) throw new Exception("expected file not found: " + expect);
    long expectedSize = new File(testClassesDir.toString(), className + ".class").length();
    long actualSize = expect.length();
    if (expectedSize != actualSize)
      throw new Exception("wrong size found: " + actualSize + "; expected: " + expectedSize);
  }
コード例 #2
0
ファイル: Compiler.java プロジェクト: FauxFaux/jdk9-jdk
 public Compiler(Flags... flags) {
   setFlags(flags);
   this.tempDirs = new ArrayList<>();
   this.postprocessors = new ArrayList<>();
   this.systemJavaCompiler = ToolProvider.getSystemJavaCompiler();
   this.fm = systemJavaCompiler.getStandardFileManager(null, null, null);
 }
コード例 #3
0
ファイル: TestInput.java プロジェクト: jsinglet/checklt
  public TestInput(
      Iterable<? extends JavaFileObject> files, Iterable<String> processors, String[] options) {

    this.compiler = ToolProvider.getSystemJavaCompiler();
    this.fileManager = compiler.getStandardFileManager(null, null, null);

    this.files = files;
    this.processors = processors;
    this.options = new LinkedList<String>();

    String classpath = System.getProperty("tests.classpath", "tests" + File.separator + "build");
    String globalclasspath = System.getProperty("java.class.path", "");

    this.options.add("-Xmaxerrs");
    this.options.add("9999");
    this.options.add("-g");
    this.options.add("-d");
    this.options.add(OUTDIR);
    this.options.add("-classpath");
    this.options.add(
        "build"
            + File.pathSeparator
            + "junit.jar"
            + File.pathSeparator
            + classpath
            + File.pathSeparator
            + globalclasspath);
    this.options.addAll(Arrays.asList(options));
  }
コード例 #4
0
 public static void main(String... args) {
   try {
     JavaCompiler javac = javax.tools.ToolProvider.getSystemJavaCompiler();
     DiagnosticListener<JavaFileObject> dl =
         new DiagnosticListener<JavaFileObject>() {
           public void report(Diagnostic<? extends JavaFileObject> message) {
             throw new NullPointerException(SILLY_BILLY);
           }
         };
     StandardJavaFileManager fm = javac.getStandardFileManager(dl, null, null);
     Iterable<? extends JavaFileObject> files =
         fm.getJavaFileObjectsFromStrings(Arrays.asList("badfile.java"));
     javac.getTask(null, fm, dl, null, null, files).call();
   } catch (RuntimeException e) {
     Throwable cause = e.getCause();
     if (cause instanceof NullPointerException && cause.getMessage().equals(SILLY_BILLY)) return;
     throw new Error("unexpected exception caught: " + e);
   } catch (Throwable t) {
     throw new Error("unexpected exception caught: " + t);
   }
   throw new Error("no exception caught");
 }
コード例 #5
0
    // Writes the program to a source file, compiles it, and runs it.
    private void compileAndRun(String fileName, String code) {
      // Exceptions here can pick and choose what font to use, as needed.
      // Exceptions thrown by the program, that cause the Playground to be unstable, should be in
      // blue.

      println("Deleting old temp files...", progErr);
      new File(fileName + ".java").delete();
      new File(fileName + ".class").delete();

      println("Creating source file...", progErr);
      file = new File(fileName + ".java");

      println("Writing code to source file...", progErr);
      try {
        new FileWriter(file).append(code).close();
      } catch (IOException i) {
        println("Had an IO Exception when trying to write the code. Stack trace:", error);
        i.printStackTrace();
        return; // Exit on error
      }

      println("Compiling code...", progErr);
      // This should only ever be called if the JDK isn't installed. How you'd get here, I don't
      // know.
      if (compiler == null) {
        println("Fatal Error: JDK not installed. Go to java.sun.com and install.", error);
        return;
      }

      // Tries to compile. Success code is 0, so if something goes wrong, do stuff.
      int result =
          compiler.run(
              null,
              null,
              null,
              file
                  .getAbsolutePath()); // Possibly add a new outputstream to parse through the
                                       // compiler errors
      if (result != 0) {
        displayLog();
        println("Failed to compile.", error);
        return; // Return on error
      }

      println("Code compiled with 0 errors.", progErr);

      println("Attempting to run code...", progErr);
      run(fileName);
    }
コード例 #6
0
ファイル: TestInput.java プロジェクト: jsinglet/checklt
  public TestRun run() {
    StringWriter output = new StringWriter();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    if (debug) {
      System.out.printf(
          "TestInput.run:%n  options: %s%n  processors: %s%n  files: %s%n",
          this.options, this.processors, this.files);
    }

    JavaCompiler.CompilationTask task =
        compiler.getTask(
            output, fileManager, diagnostics, this.options, this.processors, this.files);

    /*
     * In Eclipse, std out and std err for multiple tests appear as one
     * long stream. When selecting a specific failed test, one sees the
     * expected/unexpected messages, but not the std out/err messages from
     * that particular test. Can we improve this somehow?
     */
    Boolean result = task.call();

    return new TestRun(result, output.toString(), diagnostics.getDiagnostics());
  }
コード例 #7
0
ファイル: BaseTest.java プロジェクト: chrreisinger/antlr4
  /**
   * Wow! much faster than compiling outside of VM. Finicky though. Had rules called r and modulo.
   * Wouldn't compile til I changed to 'a'.
   */
  protected boolean compile(String fileName) {
    String classpathOption = "-classpath";

    String[] args =
        new String[] {
          "javac",
          "-d",
          tmpdir,
          classpathOption,
          tmpdir + pathSep + CLASSPATH,
          tmpdir + "/" + fileName
        };
    String cmdLine =
        "javac"
            + " -d "
            + tmpdir
            + " "
            + classpathOption
            + " "
            + tmpdir
            + pathSep
            + CLASSPATH
            + " "
            + fileName;
    // System.out.println("compile: "+cmdLine);

    File f = new File(tmpdir, fileName);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    //		DiagnosticCollector<JavaFileObject> diagnostics =
    //			new DiagnosticCollector<JavaFileObject>();

    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    Iterable<? extends JavaFileObject> compilationUnits =
        fileManager.getJavaFileObjectsFromFiles(Arrays.asList(f));

    Iterable<String> compileOptions =
        Arrays.asList(new String[] {"-d", tmpdir, "-cp", tmpdir + pathSep + CLASSPATH});

    JavaCompiler.CompilationTask task =
        compiler.getTask(null, fileManager, null, compileOptions, null, compilationUnits);
    boolean ok = task.call();

    try {
      fileManager.close();
    } catch (IOException ioe) {
      ioe.printStackTrace(System.err);
    }

    //		List<String> errors = new ArrayList<String>();
    //		for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
    //			errors.add(
    //				String.valueOf(diagnostic.getLineNumber())+
    //				": " + diagnostic.getMessage(null));
    //		}
    //		if ( errors.size()>0 ) {
    //			System.err.println("compile stderr from: "+cmdLine);
    //			System.err.println(errors);
    //			return false;
    //		}
    return ok;

    /*
    File outputDir = new File(tmpdir);
    try {
    	Process process =
    		Runtime.getRuntime().exec(args, null, outputDir);
    	StreamVacuum stdout = new StreamVacuum(process.getInputStream());
    	StreamVacuum stderr = new StreamVacuum(process.getErrorStream());
    	stdout.start();
    	stderr.start();
    	process.waitFor();
              stdout.join();
              stderr.join();
    	if ( stdout.toString().length()>0 ) {
    		System.err.println("compile stdout from: "+cmdLine);
    		System.err.println(stdout);
    	}
    	if ( stderr.toString().length()>0 ) {
    		System.err.println("compile stderr from: "+cmdLine);
    		System.err.println(stderr);
    	}
    	int ret = process.exitValue();
    	return ret==0;
    }
    catch (Exception e) {
    	System.err.println("can't exec compilation");
    	e.printStackTrace(System.err);
    	return false;
    }
    */
  }