/**
  * Initializes a program.
  *
  * @return program
  */
 private static Program initProgram() {
   Program program = new Program();
   program.state().reset();
   program.initBytecodeReader(new BytecodeParser());
   initParser(program);
   return program;
 }
 @Override
 public void visitar(Program program) {
   // obtengo el identificador dl primer nodo.
   String ident = program.toGrapher(this.cantNodosVisitados);
   // agrego el identificador al codigo.
   this.codigoGraph += ident;
   // sepero el nombre del identificador del nombre asignadodentro del nodo, posicion 0.
   String[] delimitador = ident.split("\\[");
   // obtengo la id del nodo 'sin el ;'.
   this.auxPadres.push(delimitador[0]);
   // cuento como nodo visitado.
   this.cantNodosVisitados++;
   // obtengo la lista de declaraciones dentro del nodo Program.
   ArrayList<Nodo> lista = program.getDeclaraciones();
   // visito los siguientes nodos (hijos).
   for (Nodo nodo : lista) {
     nodo.aceptar(this);
   }
   // elimino el padre actual.
   this.auxPadres.pop();
   try {
     this.generarGraph();
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
Ejemplo n.º 3
0
 /** Returns the weakest precondition of a given program. */
 @Override
 public Term visit(Program root) {
   visitMethod = false;
   int lines = root.getNumberOfChildren();
   for (int i = 0; i < lines; i++) {
     root.getChild(lines - i - 1).accept(this);
   }
   return wp;
 }
  /**
   * @param artifact artifact to create program from
   * @return ASTNodeArtifact
   */
  public static ASTNodeArtifact createProgram(final ASTNodeArtifact artifact) {
    assert (artifact.astnode != null);
    assert (artifact.astnode instanceof Program);

    Program old = (Program) artifact.astnode;
    Program program;
    try {
      program = old.clone();
    } catch (CloneNotSupportedException e) {
      program = new Program();
    }

    ASTNodeArtifact p = new ASTNodeArtifact(program);
    p.deleteChildren();

    return p;
  }
  /**
   * Constructs an ASTNodeArtifact from a FileArtifact.
   *
   * @param artifact file artifact
   */
  public ASTNodeArtifact(final FileArtifact artifact) {
    assert (artifact != null);

    setRevision(artifact.getRevision());

    ASTNode<?> astnode;
    if (artifact.isEmptyDummy()) {
      astnode = new ASTNode<>();
      setEmptyDummy(true);
    } else {
      Program p = initProgram();
      p.addSourceFile(artifact.getPath());
      astnode = p;
    }

    this.astnode = astnode;
    renumber(1, this);
  }
 /**
  * Initializes parser.
  *
  * @param p program
  */
 private static void initParser(final Program p) {
   p.initJavaParser(
       new JavaParser() {
         @Override
         public CompilationUnit parse(final java.io.InputStream is, final String fileName)
             throws java.io.IOException, beaver.Parser.Exception {
           return new parser.JavaParser().parse(is, fileName);
         }
       });
 }
Ejemplo n.º 7
0
  /**
   * This is the primary method in this file. It returns a map from Strings to Integers. The string
   * keys are in the form: "ClassName.MethodName" The values of the map are simply how many local
   * variables the method uses, excluding local parameter variables.
   *
   * @param ast - The program's abstract syntax tree
   * @return the map described above.
   */
  public Map<String, Integer> getNumLocalVars(Program ast) {

    // clears the map
    this.numLocalVars.clear();

    // Populates the map appropriately
    ast.accept(this);

    // Return the map
    return this.numLocalVars;
  }
Ejemplo n.º 8
0
  public void run() {
    try {

      Scanner s = new Scanner(this.reader);
      Parser p = new Parser(s);
      Symbol root = p.parse();

      Program prog = (Program) root.value;
      prog.accept(new PrettyPrintVisitor());

      System.out.print("Parser rodou com sucesso!");

    } catch (CompilerException e) {
      // erro de compilação do arquivo de entrada
      System.err.println(e.getMessage());
    } catch (Exception e) {
      // erro do compilador
      System.err.println("Erro inesperado no parser: " + e.toString());
      e.printStackTrace();
    }
  }
Ejemplo n.º 9
0
  @Override
  public void visit(Program prog) {
    if (prog == null) return;

    if (prog.getMainClass() != null) prog.getMainClass().accept(this);

    if (prog.getClassDeclList() == null) return;
    for (int i = 0; i < prog.getClassDeclList().size(); i++) {
      if (prog.getClassDeclList().elementAt(i) == null) continue;

      System.out.println();
      prog.getClassDeclList().elementAt(i).accept(this);
    }
  }
Ejemplo n.º 10
0
  public void callMetaobjects(String filename, Program program, PrintWriter outError) {

    boolean foundCE = false;
    boolean foundNCE = false;
    for (MetaobjectCall moCall : program.getMetaobjectCallList()) {
      if (moCall.getName().equals("ce")) {
        this.numSourceFilesWithErros++;

        String message = (String) moCall.getParamList().get(2);
        int lineNumber = (Integer) moCall.getParamList().get(0);
        if (!program.hasCompilationErrors()) {
          // there was no compilation error. There should be no call
          // @ce(...)
          // the source code, through calls to "@ce(...)", informs
          // that
          // there are errors
          String whatToCorrect = "";
          if (moCall.getParamList().size() >= 4) {
            whatToCorrect = (String) moCall.getParamList().get(3);
            whatToCorrect = " (" + whatToCorrect + ")";
          }
          this.shouldButWereNotList.add(
              filename + ", " + lineNumber + ", " + message + whatToCorrect);
          if (foundCE)
            outError.println(
                "More than one 'ce' metaobject calls in the same source file '" + filename + "'");
          foundCE = true;
        } else {
          // there was a compilation error. Check it.
          int lineOfError = program.getCompilationErrorList().get(0).getLineNumber();
          String ceMessage = (String) moCall.getParamList().get(2);
          String compilerMessage = program.getCompilationErrorList().get(0).getMessage();
          if (lineNumber != lineOfError) {

            String whatToCorrect = "";
            if (moCall.getParamList().size() >= 4) {
              whatToCorrect = (String) moCall.getParamList().get(3);
              whatToCorrect = "(" + whatToCorrect + ")";
            }

            this.wereButWrongLineList.add(
                filename
                    + "\n"
                    + "    correto:    "
                    + lineNumber
                    + ", "
                    + ceMessage
                    + " "
                    + whatToCorrect
                    + "\n"
                    + "    sinalizado: "
                    + lineOfError
                    + ", "
                    + compilerMessage);
          } else {
            // the compiler is correct. Add to correctList the
            // message
            // that the compiler signalled and the message of the
            // test, given in @ce
            correctList.add(
                filename
                    + "\r\n"
                    + "The compiler message was: \""
                    + compilerMessage
                    + "\"\r\n"
                    + "The 'ce' message is:      \""
                    + ceMessage
                    + "\"\r\n");
          }
        }
      } else if (moCall.getName().equals("nce")) {
        if (foundNCE)
          outError.println(
              "More than one 'nce' metaobject calls in the same source file '" + filename + "'");
        foundNCE = true;
        if (program.hasCompilationErrors()) {
          int lineOfError = program.getCompilationErrorList().get(0).getLineNumber();
          String message = program.getCompilationErrorList().get(0).getMessage();
          this.wereButShouldNotList.add(filename + ", " + lineOfError + ", " + message);
        }
      }
    }
    if (foundCE && foundNCE)
      outError.println(
          "Calls to metaobjects 'ce' and 'nce' in the same source code '" + filename + "'");
  }
Ejemplo n.º 11
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();
    }
  }
Ejemplo n.º 12
0
  public static void main(String[] args) {
    try {
      if (args.length == 2) {
        FileReader reader = new FileReader(args[1]);
        scanner s = new scanner(reader);
        parser p = new parser(s);
        Symbol root;
        root = p.parse();

        if (args[0].equalsIgnoreCase("-ts")) {
          System.out.println("\n\n--------------------" + args[1] + "-------------------");
          System.out.println("Gerando tabela de simbolos...");
          Program program = (Program) root.value;
          VisitorTableSymbol vi = new VisitorTableSymbol();
          program.accept(vi);
          if (vi.getError().size() > 0) {
            vi.showErrors();
          } else vi.showAllTable();
          System.out.println("Concluido!");
        } else {
          if (args[0].equalsIgnoreCase("-sa")) {
            System.out.println("\n\n--------------------" + args[1] + "-------------------");
            System.out.println("Gerando tabela de simbolos...");
            Program program = (Program) root.value;
            VisitorTableSymbol vi = new VisitorTableSymbol();
            program.accept(vi);
            vi.showErrors();
            // vi.showAllTable();
            if (vi.getError().size() == 0) {
              System.out.println("Efetuando a analise semantica...");
              VisitorSemanticAnalysis vis = new VisitorSemanticAnalysis(vi);
              program.accept(vis);
              vis.showErrors();
              if (vis.getError().size() == 0)
                System.out.println("Analise semantica efetuada com sucesso!");
            }
          } else {
            if (args[0].equalsIgnoreCase("-gc")) {
              System.out.println("\n\n--------------------" + args[1] + "-------------------");
              System.out.println("Gerando tabela de simbolos...");
              Program program = (Program) root.value;
              VisitorTableSymbol vi = new VisitorTableSymbol();
              program.accept(vi);
              vi.showErrors();
              if (vi.getError().size() == 0) {
                System.out.println("Efetuando a analise semantica...");
                VisitorSemanticAnalysis vis = new VisitorSemanticAnalysis(vi);
                program.accept(vis);
                vis.showErrors();
                if (vis.getError().size() == 0) {
                  VisitorGenCod vigc = new VisitorGenCod(args[1], vi);
                  program.accept(vigc);
                  System.out.println("Compilacao efetuada com sucesso!");
                }
              }
            }
          }
        }
      } else {
        if (args.length == 1) {
          if (args[0].equalsIgnoreCase("-all")) {
            String[] files = {
              "BinarySearch",
              "BinaryTree",
              "BubbleSort",
              "Factorial",
              "LinearSearch",
              "LinkedList",
              "QuickSort",
              "TreeVisitor"
            };
            for (int i = 0; i < files.length; i++) {
              FileReader reader1 =
                  new FileReader("SamplePrograms\\SampleMiniJavaPrograms\\" + files[i] + ".java");
              System.out.println(
                  "\n\n--------------------" + files[i] + ".java" + "-------------------");
              scanner s = new scanner(reader1);

              parser p = new parser(s);

              Symbol root;
              // replace p.parse() with p.debug_parse() in next line to see trace of
              // parser shift/reduce actions during parse
              root = p.parse();

              Program program = (Program) root.value;
              VisitorTableSymbol vi = new VisitorTableSymbol();
              program.accept(vi);
              vi.showAllTable();
              if (vi.getError().size() == 0) {
                VisitorSemanticAnalysis vis = new VisitorSemanticAnalysis(vi);
                program.accept(vis);
                vis.showErrors();
                if (vis.getError().size() == 0) {
                  VisitorGenCod vigc = new VisitorGenCod(files[i], vi);
                  program.accept(vigc);
                  System.out.println("Compilacao efetuada com sucesso!");
                }
              }
            }
            System.out.println("Todas as tentativas ou sucessos de compilacao foram concluidos!");
          }
        } else System.out.println("Por favor informe um argumento valido!");
      }
    } catch (Exception e) {
      // yuck: some kind of error in the compiler implementation
      // that we're not expecting (a bug!)
      System.err.println("Unexpected internal compiler error: " + e.toString());
      // print out a stack dump
      e.printStackTrace();
    }
  }
Ejemplo n.º 13
0
 public Object visit(Program node) {
   return layoutNary("Program", node.getClassList());
 }