private String getToolName(byte[] data) {
   String text = new String(data);
   String name = null;
   Tokenizer tok = new Tokenizer();
   Program pgm = tok.tokenize(text);
   int[] code = pgm.getCode();
   Symbol[] symbolTable = pgm.getSymbolTable();
   for (int i = 0; i < code.length; i++) {
     int token = code[i] & MacroConstants.TOK_MASK;
     if (token == MacroConstants.MACRO) {
       int nextToken = code[i + 1] & MacroConstants.TOK_MASK;
       if (nextToken == MacroConstants.STRING_CONSTANT) {
         int address = code[i + 1] >> MacroConstants.TOK_SHIFT;
         Symbol symbol = symbolTable[address];
         name = symbol.str;
         break;
       }
     }
   }
   if (name == null) return null;
   int index = name.indexOf("Tool");
   if (index == -1) return null;
   name = name.substring(0, index + 4);
   name = name.replaceAll(" ", "_");
   name = name + ".ijm";
   return name;
 }
Example #2
0
 protected void initOptions() {
   Options options = program.options();
   options.initOptions();
   options.addKeyOption("-version");
   options.addKeyOption("-print");
   options.addKeyOption("-g");
   options.addKeyOption("-g:none");
   options.addKeyOption("-g:lines,vars,source");
   options.addKeyOption("-nowarn");
   options.addKeyOption("-verbose");
   options.addKeyOption("-deprecation");
   options.addKeyValueOption("-classpath");
   options.addKeyValueOption("-cp");
   options.addKeyValueOption("-sourcepath");
   options.addKeyValueOption("-bootclasspath");
   options.addKeyValueOption("-extdirs");
   options.addKeyValueOption("-d");
   options.addKeyValueOption("-encoding");
   options.addKeyValueOption("-source");
   options.addKeyValueOption("-target");
   options.addKeyOption("-help");
   options.addKeyOption("-O");
   options.addKeyOption("-J-Xmx128M");
   options.addKeyOption("-recover");
 }
Example #3
0
  public static void main(String[] args) {

    try {
      // File file = new File("C:\\tiger2\\testcases\\BinarySearch.java");
      // File file = new File("C:\\tiger2\\testcases\\BinaryTree.java");
      // File file = new File("C:\\tiger2\\testcases\\BubbleSort.java");
      File file = new File("C:\\tiger2\\testcases\\Factorial.java");
      // File file = new File("C:\\tiger2\\testcases\\LinearSearch.java");
      // File file = new File("C:\\tiger2\\testcases\\LinkedList.java");
      // File file = new File("C:\\tiger2\\testcases\\QuickSort.java");
      // File file = new File("C:\\tiger2\\testcases\\Test1.java");
      // File file = new File("C:\\tiger2\\testcases\\TreeVisitor.java");
      FileInputStream stream = new FileInputStream(file);
      Program root = new MiniJavaParser(stream).Goal();

      // Print the original source code from the abstract syntax tree:
      root.accept(new PrettyPrintVisitor());
      // root.accept(new ASTPrintVisitor());

      // Print the abstract syntax tree:
      // root.accept(new ASTPrintVisitor());	// Should this have been called "UglyPrintVisitor"? :)

    } catch (ParseException e) {
      System.out.println(e.toString());
    } catch (FileNotFoundException fnfe) {
      System.out.println("File not found!");
    }

    /*try {
      //File file = new File("C:\\tiger2\\testcases\\Factorial.java");
      File file = new File("C:\\tiger2\\testcases\\BubbleSort.java");
      //File file = new File("C:\\tiger2\\testcases\\Test1.java");
      FileInputStream stream = new FileInputStream(file);
      MiniJavaParser parser = new MiniJavaParser(stream);
      parser.Goal();
      System.out.println("Parse succeeded.");
    }
    catch (FileNotFoundException fnfe)
    {
      System.out.println("File not found!");
    }
    catch (ParseException e) {
      System.out.println("Parser Error : \n"+ e.toString());
    }*/
  }
Example #4
0
  public boolean process(String[] args, BytecodeReader reader, JavaParser parser) {
    program.initBytecodeReader(reader);
    program.initJavaParser(parser);

    initOptions();
    processArgs(args);

    Collection files = program.options().files();

    if (program.options().hasOption("-version")) {
      printVersion();
      return false;
    }
    if (program.options().hasOption("-help") || files.isEmpty()) {
      printUsage();
      return false;
    }

    try {
      for (Iterator iter = files.iterator(); iter.hasNext(); ) {
        String name = (String) iter.next();
        if (!new File(name).exists())
          System.err.println("WARNING: file \"" + name + "\" does not exist");
        program.addSourceFile(name);
      }

      for (Iterator iter = program.compilationUnitIterator(); iter.hasNext(); ) {
        CompilationUnit unit = (CompilationUnit) iter.next();
        if (unit.fromSource()) {
          Collection errors = unit.parseErrors();
          Collection warnings = new LinkedList();
          // compute static semantic errors when there are no parse errors or
          // the recover from parse errors option is specified
          if (errors.isEmpty() || program.options().hasOption("-recover"))
            unit.errorCheck(errors, warnings);
          if (!errors.isEmpty()) {
            processErrors(errors, unit);
            return false;
          } else {
            if (!warnings.isEmpty()) processWarnings(warnings, unit);
            processNoErrors(unit);
          }
        }
      }
    } catch (Exception e) {
      System.err.println(e.getMessage());
      e.printStackTrace();
    }
    return true;
  }
 void installPopupMenu(String name, Program pgm) {
   Hashtable h = pgm.getMenus();
   if (h == null) return;
   String[] commands = (String[]) h.get(name);
   if (commands == null) return;
   PopupMenu popup = Menus.getPopupMenu();
   if (popup == null) return;
   popup.removeAll();
   for (int i = 0; i < commands.length; i++) {
     if (commands[i].equals("-")) popup.addSeparator();
     else {
       MenuItem mi = new MenuItem(commands[i]);
       mi.addActionListener(this);
       popup.add(mi);
     }
   }
 }
Example #6
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 + "'");
  }
Example #7
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();
    }
  }
Example #8
0
 protected Frontend() {
   program = new Program();
   program.state().reset();
 }
Example #9
0
 protected void processArgs(String[] args) {
   program.options().addOptions(args);
 }
 void install() {
   subMenus.clear();
   if (text != null) {
     Tokenizer tok = new Tokenizer();
     pgm = tok.tokenize(text);
   }
   if (macrosMenu != null) IJ.showStatus("");
   int[] code = pgm.getCode();
   Symbol[] symbolTable = pgm.getSymbolTable();
   int count = 0, token, nextToken, address;
   String name;
   Symbol symbol;
   shortcutsInUse = null;
   inUseCount = 0;
   nShortcuts = 0;
   toolCount = 0;
   macroStarts = new int[MAX_MACROS];
   macroNames = new String[MAX_MACROS];
   boolean isPluginsMacrosMenu = false;
   if (macrosMenu != null) {
     int itemCount = macrosMenu.getItemCount();
     isPluginsMacrosMenu = macrosMenu == Menus.getMacrosMenu();
     int baseCount = isPluginsMacrosMenu ? MACROS_MENU_COMMANDS : Editor.MACROS_MENU_ITEMS;
     if (itemCount > baseCount) {
       for (int i = itemCount - 1; i >= baseCount; i--) macrosMenu.remove(i);
     }
   }
   if (pgm.hasVars() && pgm.macroCount() > 0 && pgm.getGlobals() == null)
     new Interpreter().saveGlobals(pgm);
   ArrayList tools = new ArrayList();
   for (int i = 0; i < code.length; i++) {
     token = code[i] & TOK_MASK;
     if (token == MACRO) {
       nextToken = code[i + 1] & TOK_MASK;
       if (nextToken == STRING_CONSTANT) {
         if (count == MAX_MACROS) {
           if (isPluginsMacrosMenu)
             IJ.error("Macro Installer", "Macro sets are limited to " + MAX_MACROS + " macros.");
           break;
         }
         address = code[i + 1] >> TOK_SHIFT;
         symbol = symbolTable[address];
         name = symbol.str;
         macroStarts[count] = i + 2;
         macroNames[count] = name;
         if (name.indexOf('-') != -1
             && (name.indexOf("Tool") != -1 || name.indexOf("tool") != -1)) {
           tools.add(name);
           toolCount++;
         } else if (name.startsWith("AutoRun")) {
           if (autoRunCount == 0 && !openingStartupMacrosInEditor) {
             new MacroRunner(pgm, macroStarts[count], name, (String) null);
             if (name.equals("AutoRunAndHide")) autoRunAndHideCount++;
           }
           autoRunCount++;
           count--;
         } else if (name.equals("Popup Menu")) installPopupMenu(name, pgm);
         else if (!name.endsWith("Tool Selected")) {
           if (macrosMenu != null) {
             addShortcut(name);
             int pos = name.indexOf(">");
             boolean inSubMenu = name.startsWith("<") && (pos > 1);
             if (inSubMenu) {
               Menu parent = macrosMenu;
               Menu subMenu = null;
               String parentStr = name.substring(1, pos).trim();
               String childStr = name.substring(pos + 1).trim();
               MenuItem mnuItem = new MenuItem();
               mnuItem.setActionCommand(name);
               mnuItem.setLabel(childStr);
               for (int jj = 0; jj < subMenus.size(); jj++) {
                 String aName = subMenus.get(jj).getName();
                 if (aName.equals(parentStr)) subMenu = subMenus.get(jj);
               }
               if (subMenu == null) {
                 subMenu = new Menu(parentStr);
                 subMenu.setName(parentStr);
                 subMenu.addActionListener(this);
                 subMenus.add(subMenu);
                 parent.add(subMenu);
               }
               subMenu.add(mnuItem);
             } else macrosMenu.add(new MenuItem(name));
           }
         }
         // IJ.log(count+" "+name+" "+macroStarts[count]);
         count++;
       }
     } else if (token == EOF) break;
   }
   nMacros = count;
   if (toolCount > 0 && (isPluginsMacrosMenu || macrosMenu == null) && installTools) {
     Toolbar tb = Toolbar.getInstance();
     if (toolCount == 1) tb.addMacroTool((String) tools.get(0), this);
     else {
       for (int i = 0; i < tools.size(); i++) {
         String toolName = (String) tools.get(i);
         if (toolName.startsWith("Abort Macro or Plugin") && toolCount > 6)
           toolName = "Unused " + toolName;
         tb.addMacroTool(toolName, this, i);
       }
     }
     if (toolCount > 1 && Toolbar.getToolId() >= Toolbar.CUSTOM1) tb.setTool(Toolbar.RECTANGLE);
     tb.repaint();
   }
   if (macrosMenu != null) this.instance = this;
   if (shortcutsInUse != null && text != null)
     IJ.showMessage(
         "Install Macros",
         (inUseCount == 1 ? "This keyboard shortcut is" : "These keyboard shortcuts are")
             + " already in use:"
             + shortcutsInUse);
   if (nMacros == 0 && fileName != null) {
     if (text == null || text.length() == 0) return;
     int dotIndex = fileName.lastIndexOf('.');
     if (dotIndex > 0) anonymousName = fileName.substring(0, dotIndex);
     else anonymousName = fileName;
     if (macrosMenu != null) macrosMenu.add(new MenuItem(anonymousName));
     macroNames[0] = anonymousName;
     nMacros = 1;
   }
   String word = nMacros == 1 ? " macro" : " macros";
   if (isPluginsMacrosMenu) IJ.showStatus(nMacros + word + " installed");
 }