Package Hack.Controller

Examples of Hack.Controller.ProgramException


     */
    public void executeInstruction() throws ProgramException {
        currentInstruction = program.getNextInstruction();

        if (currentInstruction == null)
            throw new ProgramException("No more instructions to execute");

        switch (currentInstruction.getOpCode()) {
            case HVMInstructionSet.ADD_CODE:
                add();
                break;
            case HVMInstructionSet.SUBSTRACT_CODE:
                substract();
                break;
            case HVMInstructionSet.NEGATE_CODE:
                negate();
                break;
            case HVMInstructionSet.EQUAL_CODE:
                equal();
                break;
            case HVMInstructionSet.GREATER_THAN_CODE:
                greaterThan();
                break;
            case HVMInstructionSet.LESS_THAN_CODE:
                lessThan();
                break;
            case HVMInstructionSet.AND_CODE:
                and();
                break;
            case HVMInstructionSet.OR_CODE:
                or();
                break;
            case HVMInstructionSet.NOT_CODE:
                not();
                break;

            case HVMInstructionSet.PUSH_CODE:
                push(currentInstruction.getArg0(), currentInstruction.getArg1());
                break;
            case HVMInstructionSet.POP_CODE:
                pop(currentInstruction.getArg0(), currentInstruction.getArg1());
                break;

            case HVMInstructionSet.GOTO_CODE:
                goTo(currentInstruction.getArg0());
                break;
            case HVMInstructionSet.IF_GOTO_CODE:
                ifGoTo(currentInstruction.getArg0());
                break;

            case HVMInstructionSet.FUNCTION_CODE:
                if (program.getCurrentPC() == program.getPreviousPC() + 1)
                    throw new ProgramException("Missing return in " + callStack.getTopFunction());

                function(currentInstruction.getArg0());
                break;
            case HVMInstructionSet.RETURN_CODE:
                returnFromFunction();
View Full Code Here


     */
    public void returnFromFunction() throws ProgramException {

        // make sure that there's somewhere to return to (old local <> 0)
        if (stackSegment.getValueAt(Definitions.LOCAL_POINTER_ADDRESS) == 0)
            throw new ProgramException("Nowhere to return to in " +
                                       getCallStack().getTopFunction() + "." +
                                       getCurrentInstruction().getIndexInFunction());

        // done in order to clear the method stack's contents
        workingStackSegment.setStartAddress(getSP());
View Full Code Here

     * Sets the static segment range according to the the given function (file) name.
     */
    protected void setStaticRange(String functionName) throws ProgramException {
        int dotLocation = functionName.indexOf(".");
        if (dotLocation == -1)
            throw new ProgramException("Illegal function name: " + functionName);

        String className = functionName.substring(0, dotLocation);
        int[] range = program.getStaticRange(className);
        if (range == null)
            throw new ProgramException("Function name doesn't match class name: " + functionName);

        staticSegment.setStartAddress(range[0]);
        staticSegment.setEnabledRange(range[0], range[1], true);
    }
View Full Code Here

        }
    }

    // Throws a program exception with the given message.
    private void error(String message) throws ProgramException {
        throw new ProgramException(message + " in " + callStack.getTopFunction() + "." +
                                   currentInstruction.getIndexInFunction());
    }
View Full Code Here

   * Throws a ProgramException if no built-in implementation was found.
   */
  public void callBuiltInFunction(String functionName, short[] params) throws ProgramException {
        int dotLocation = functionName.indexOf(".");
        if (dotLocation == -1) {
            throw new ProgramException("Illegal function name: " + functionName);
    }
        String className = functionName.substring(0, dotLocation);
    String methodName = functionName.substring(dotLocation+1, functionName.length());
    if (methodName.equals("new")) {
      // new is a reserved Java word - therefore Jack functions named
      // new are implemented by Java functions named NEW.
      methodName = "NEW";
    }
   
    // Find the implementing class
    Class implementingClass;
    try {
      implementingClass = Class.forName(builtInDir+"."+className);
    } catch (ClassNotFoundException cnfe) {
      throw new ProgramException("Can't find "+className+".vm or a built-in implementation for class "+className);
    }

    // Check that the class is a subclass of BuiltInVMClass
    // (right now not that important if the class doesn't want to access
    // the computer - like math - but good practice anyway).
    Class currentClass = implementingClass;
    boolean found;
    do {
      currentClass = currentClass.getSuperclass();
      found = currentClass.getName().equals("Hack.VMEmulator.BuiltInVMClass");
    } while (!found && !currentClass.getName().equals("java.lang.Object"));
    if (!found) {
      throw new ProgramException("Built-in implementation for "+className+" is not a subclass of BuiltInVMClass");
    }

    // Find the implementing method & fill in the request
    Class[] paramsClasses = new Class[params.length];
    Object[] requestParams = new Object[params.length];
    for (int i=0; i<params.length; ++i) {
      requestParams[i] = new Short(params[i]);
      paramsClasses[i] = short.class;
    }

    Method functionObject;
    try {
      functionObject =
        implementingClass.getDeclaredMethod(methodName, paramsClasses);
    } catch (NoSuchMethodException nsme) {
      throw new ProgramException("Can't find "+className+".vm or a built-in implementation for function "+methodName+" in class "+className+" taking "+params.length+" argument"+(params.length==1?"":"s")+".");
    }
    Class returnType = functionObject.getReturnType();
    if (returnType != short.class && returnType != void.class &&
      returnType != char.class && returnType != boolean.class) {
      throw new ProgramException("Can't find "+className+".vm and the built-in implementation for "+functionName+" taking "+params.length+" arguments doesn't return short/char/void/boolean.");
    }
    programToBuiltIn.request = CALL_REQUEST;
    programToBuiltIn.params = requestParams;
    programToBuiltIn.functionObject = functionObject;
     
View Full Code Here

      break;
    case INFINITE_LOOP_REQUEST:
      cpu.infiniteLoopFromBuiltIn(builtInToProgram.details);
      break;
    case THROW_PROGRAM_EXCEPTION_REQUEST:
      throw new ProgramException(builtInToProgram.details);
      //break - unreachable
    }
  }
View Full Code Here

     * Throws ProgramException if an error occurs while loading the program.
     */
    public void loadProgram(String fileName) throws ProgramException {
        File file = new File(fileName);
        if (!file.exists())
            throw new ProgramException("cannot find " + fileName);

        File[] files;

        if (file.isDirectory()) {
            files = file.listFiles(new HackFileFilter(".vm"));
            if (files == null || files.length == 0)
                throw new ProgramException("No vm files found in " + fileName);
        }
        else
            files = new File[]{file};

        if (displayChanges)
            gui.showMessage("Loading...");

        // First scan
    staticRange.clear();
    functions.clear();
    builtInAccessStatus = BUILTIN_ACCESS_UNDECIDED;
        Hashtable symbols = new Hashtable();
    nextPC = 0;
        for (int i = 0; i < files.length; i++) {
            String name = files[i].getName();
            String className = name.substring(0, name.indexOf("."));
      // put some dummy into static range - just to tell the function
      // getAddress in the second pass which classes exist
      staticRange.put(className, new Boolean(true));
            try {
                updateSymbolTable(files[i], symbols, functions);
            } catch (ProgramException pe) {
                if (displayChanges)
                    gui.hideMessage();
                throw new ProgramException(name + ": " + pe.getMessage());
            }
        }
    boolean addCallBuiltInSysInit = false;
    if ((file.isDirectory() || symbols.get("Main.main") != null) &&
      symbols.get("Sys.init") == null) {
      // If the program is in multiple files or there's a Main.main
      // function it is assumed that it should be run by calling Sys.init.
      // If no Sys.init is found, add an invisible line with a call
      // to Sys.init to start on - the builtin version will be called.
      addCallBuiltInSysInit = true;
      getAddress("Sys.init"); // confirm calling the built-in Sys.init
      ++nextPC; // A "call Sys.init 0" line will be added
    }

        instructions = new VMEmulatorInstruction[nextPC+4];

        // Second scan
        nextPC = 0;
        currentStaticIndex = Definitions.VAR_START_ADDRESS;
        for (int i = 0; i < files.length; i++) {
            String name = files[i].getName();
            String className = name.substring(0, name.indexOf("."));

            largestStaticIndex = -1;
            int[] range = new int[2];
            range[0] = currentStaticIndex;

            try {
        // functions is not passed as an argument since it is accessed
        // through getAddress()
                buildProgram(files[i], symbols);
            } catch (ProgramException pe) {
                if (displayChanges)
                    gui.hideMessage();
                throw new ProgramException(name + ": " + pe.getMessage());
            }

            currentStaticIndex += largestStaticIndex + 1;
            range[1] = currentStaticIndex - 1;
            staticRange.put(className, range);
View Full Code Here

        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(file.getAbsolutePath()));
        } catch (FileNotFoundException fnfe) {
            throw new ProgramException("file " + file.getName() + " does not exist");
        }

        String line;
        String currentFunction = null;
        String label;
        int lineNumber = 0;

    isSlashStar = false;
        try {
            while ((line = unCommentLine(reader.readLine())) != null) {
                lineNumber++;
                if (!line.trim().equals("")) {
                    if (line.startsWith("function ")) {
                        StringTokenizer tokenizer = new StringTokenizer(line);
                        tokenizer.nextToken();
                        currentFunction = tokenizer.nextToken();
                        if (symbols.containsKey(currentFunction))
                            throw new ProgramException("subroutine " + currentFunction +
                                                       " already exists");
                        functions.put(currentFunction, new Short(nextPC));
                        symbols.put(currentFunction, new Short(nextPC));
                    }
                    else if (line.startsWith("label ")) {
                        StringTokenizer tokenizer = new StringTokenizer(line);
                        tokenizer.nextToken();
                        label = currentFunction + "$" + tokenizer.nextToken();
                        symbols.put(label, new Short((short)(nextPC + 1)));
                    }

                    nextPC++;
                }
            }
            reader.close();
        } catch (IOException ioe) {
            throw new ProgramException("Error while reading from file");
        } catch (NoSuchElementException nsee) {
            throw new ProgramException("In line " + lineNumber + ": unexpected end of command");
        }
    if (isSlashStar) {
      throw new ProgramException("Unterminated /* comment at end of file");
    }
    }
View Full Code Here

        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(file.getAbsolutePath()));
        } catch (FileNotFoundException fnfe) {
            throw new ProgramException("file does not exist");
        }

        int lineNumber = 0;
        String line;
        String label;
        String instructionName;
        String currentFunction = null;
        short indexInFunction = 0;
        byte opCode;
        short arg0, arg1;
        short pc = nextPC;
        HVMInstructionSet instructionSet = HVMInstructionSet.getInstance();

    isSlashStar = false;
        try {
            while ((line = unCommentLine(reader.readLine())) != null) {
                lineNumber++;

                if (!line.trim().equals("")) {
                    StringTokenizer tokenizer = new StringTokenizer(line);
                    instructionName = tokenizer.nextToken();

                    opCode = instructionSet.instructionStringToCode(instructionName);
                    if (opCode == HVMInstructionSet.UNKNOWN_INSTRUCTION)
                        throw new ProgramException("in line " + lineNumber +
                                                   ": unknown instruction - " + instructionName);

                    switch (opCode) {
                        case HVMInstructionSet.PUSH_CODE:
                            String segment = tokenizer.nextToken();
                            try {
                                arg0 = translateSegment(segment, instructionSet, file.getName());
                            } catch (ProgramException pe) {
                                throw new ProgramException("in line " + lineNumber + pe.getMessage());
                            }
                            arg1 = Short.parseShort(tokenizer.nextToken());
                            if (arg1 < 0)
                                throw new ProgramException("in line " + lineNumber +
                                                           ": Illegal argument - " + line);

                            if (arg0 == HVMInstructionSet.STATIC_SEGMENT_CODE && arg1 > largestStaticIndex)
                                largestStaticIndex = arg1;

                            instructions[pc] = new VMEmulatorInstruction(opCode, arg0, arg1,
                                                                         indexInFunction);
                            break;

                        case HVMInstructionSet.POP_CODE:
                            int n = tokenizer.countTokens();
                            segment = tokenizer.nextToken();
                            try {
                                arg0 = translateSegment(segment, instructionSet, file.getName());
                            } catch (ProgramException pe) {
                                throw new ProgramException("in line " + lineNumber + pe.getMessage());
                            }
                            arg1 = Short.parseShort(tokenizer.nextToken());

                            if (arg1 < 0)
                                throw new ProgramException("in line " + lineNumber +
                                                           ": Illegal argument - " + line);

                            if (arg0 == HVMInstructionSet.STATIC_SEGMENT_CODE && arg1 > largestStaticIndex)
                                largestStaticIndex = arg1;

                            instructions[pc] = new VMEmulatorInstruction(opCode, arg0, arg1,
                                                                         indexInFunction);
                            break;

                        case HVMInstructionSet.FUNCTION_CODE:
                            currentFunction = tokenizer.nextToken();
                            indexInFunction = 0;
                            arg0 = Short.parseShort(tokenizer.nextToken());

                            if (arg0 < 0)
                                throw new ProgramException("in line " + lineNumber +
                                                           ": Illegal argument - " + line);

                            instructions[pc] = new VMEmulatorInstruction(opCode, arg0, indexInFunction);
                            instructions[pc].setStringArg(currentFunction);
                            break;

                        case HVMInstructionSet.CALL_CODE:
                            String functionName = tokenizer.nextToken();
              try {
                arg0 = getAddress(functionName);
              } catch (ProgramException pe) {
                throw new ProgramException("in line " +
                               lineNumber + ": " +
                               pe.getMessage());
              }
                            arg1 = Short.parseShort(tokenizer.nextToken());

                            if (arg1 < 0 || ((arg0 < 0 || arg0 > Definitions.ROM_SIZE) && arg0 != BUILTIN_FUNCTION_ADDRESS))
                                throw new ProgramException("in line " + lineNumber +
                                                           ": Illegal argument - " + line);

                            instructions[pc] = new VMEmulatorInstruction(opCode, arg0, arg1,
                                                                         indexInFunction);
                            instructions[pc].setStringArg(functionName);
                            break;

                        case HVMInstructionSet.LABEL_CODE:
                            label = currentFunction + "$" + tokenizer.nextToken();
                            instructions[pc] = new VMEmulatorInstruction(opCode, (short)(-1));
                            instructions[pc].setStringArg(label);
                            indexInFunction--; // since Label is not a "physical" instruction
                            break;

                        case HVMInstructionSet.GOTO_CODE:
                            label = currentFunction + "$" + tokenizer.nextToken();
                            Short labelAddress = (Short)symbols.get(label);
                            if (labelAddress == null)
                                throw new ProgramException("in line " + lineNumber +
                                                           ": Unknown label - " + label);
                            arg0 = labelAddress.shortValue();

                            if (arg0 < 0 || arg0 > Definitions.ROM_SIZE)
                                throw new ProgramException("in line " + lineNumber +
                                                           ": Illegal argument - " + line);

                            instructions[pc] = new VMEmulatorInstruction(opCode, arg0, indexInFunction);
                            instructions[pc].setStringArg(label);
                            break;

                        case HVMInstructionSet.IF_GOTO_CODE:
                            label = currentFunction + "$" + tokenizer.nextToken();
                            labelAddress = (Short)symbols.get(label);
                            if (labelAddress == null)
                                throw new ProgramException("in line " + lineNumber +
                                                           ": Unknown label - " + label);

                            arg0 = labelAddress.shortValue();

                            if (arg0 < 0 || arg0 > Definitions.ROM_SIZE)
                                throw new ProgramException("in line " + lineNumber +
                                                           ": Illegal argument - "  + line);

                            instructions[pc] = new VMEmulatorInstruction(opCode, arg0, indexInFunction);
                            instructions[pc].setStringArg(label);
                            break;

                        // All other instructions have either 1 or 0 arguments and require no
                        // special treatment
                        default:
                            if (tokenizer.countTokens() == 0) {
                                instructions[pc] = new VMEmulatorInstruction(opCode, indexInFunction);
                            }
                            else {
                                arg0 = Short.parseShort(tokenizer.nextToken());

                                if (arg0 < 0)
                                    throw new ProgramException("in line " + lineNumber +
                                                               ": Illegal argument - " + line);

                                instructions[pc] = new VMEmulatorInstruction(opCode, arg0,
                                                                             indexInFunction);
                            }
                            break;
                    }

                    // check end of command
                    if (tokenizer.hasMoreTokens())
                        throw new ProgramException("in line " + lineNumber +
                                                   ": Too many arguments - " + line);

                    pc++;
                    indexInFunction++;
                }

                nextPC = pc;
            }
            reader.close();
        } catch (IOException ioe) {
            throw new ProgramException("Error while reading from file");
        } catch (NumberFormatException nfe) {
            throw new ProgramException("Illegal 16-bit value");
        } catch (NoSuchElementException nsee) {
            throw new ProgramException("In line " + lineNumber + ": unexpected end of command");
        }
    if (isSlashStar) {
      throw new ProgramException("Unterminated /* comment at end of file");
    }
    }
View Full Code Here

      // Either:
      // 1.The class is implemented by a VM file and no implementation
      //     for the function is found - don't override with built-in
      // - or -
      // 2.The user did not authorize using built-in implementations.
      throw new ProgramException(className + ".vm not found " +
                     "or function " + functionName +
                     " not found in " + className + ".vm");
    }
  }
View Full Code Here

TOP

Related Classes of Hack.Controller.ProgramException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.