Beispiel #1
0
  /**
   * @param args
   * @param stream
   * @param numChRead
   * @param outError
   * @param printWriter
   * @throws IOException
   */
  private void compileProgram(File file, String filename, PrintWriter outError) {
    Program program;
    FileReader stream;
    int numChRead;

    try {
      stream = new FileReader(file);
    } catch (FileNotFoundException e) {
      String msg = "Something wrong: file does not exist anymore";
      outError.println(msg);
      return;
    }
    // one more character for '\0' at the end that will be added by the
    // compiler
    char[] input = new char[(int) file.length() + 1];

    try {
      numChRead = stream.read(input, 0, (int) file.length());
      if (numChRead != file.length()) {
        outError.println("Read error");
        stream.close();
        return;
      }
      stream.close();
    } catch (IOException e) {
      String msg = "Error reading file " + filename;
      outError.println(msg);
      try {
        stream.close();
      } catch (IOException e1) {
      }
      return;
    }

    Compiler compiler = new Compiler();

    program = null;
    // the generated code goes to a file and so are the errors
    program = compiler.compile(input, outError);
    callMetaobjects(filename, program, outError);

    if (!program.hasCompilationErrors()) {

      String outputFileName;

      int lastIndex;
      if ((lastIndex = filename.lastIndexOf('.')) == -1) lastIndex = filename.length();
      outputFileName = filename.substring(0, lastIndex);
      if ((lastIndex = filename.lastIndexOf('\\')) != -1)
        outputFileName = filename.substring(lastIndex + 1);

      FileOutputStream outputStream;
      try {
        outputStream = new FileOutputStream(outputFileName + ".c");
      } catch (IOException e) {
        String msg = "File " + outputFileName + " was not found";
        outError.println(msg);
        return;
      }
      PrintWriter printWriter = new PrintWriter(outputStream);

      PW pw = new PW();
      pw.set(printWriter);
      program.genC(pw);
      if (printWriter.checkError()) {
        outError.println("There was an error in the output");
      }
      printWriter.close();
    }
  }
 public void genC(PW pw) {
   pw.print("return ");
   expr.genC(pw, false);
   pw.println(";");
 }