⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 smallbasic.txt

📁 Small Basic解释器的完整java代码
💻 TXT
📖 第 1 页 / 共 2 页
字号:
import java.io.*;
import java.util.*;

// Exception class for interpreter errors.
class InterpreterException extends Exception {
  String errStr; // describes the error 
 
  public InterpreterException(String str) { 
    errStr = str; 
  }   
  
  public String toString() {  
    return errStr; 
  }  
}  
  
// The Small BASIC interpreter.
class SBasic {  
  final int PROG_SIZE = 10000; // maximum program size

  // These are the token types. 
  final int NONE = 0; 
  final int DELIMITER = 1; 
  final int VARIABLE = 2; 
  final int NUMBER = 3; 
  final int COMMAND = 4; 
  final int QUOTEDSTR = 5;
 
  // These are the types of errors. 
  final int SYNTAX = 0; 
  final int UNBALPARENS = 1; 
  final int NOEXP = 2; 
  final int DIVBYZERO = 3; 
  final int EQUALEXPECTED = 4; 
  final int NOTVAR = 5; 
  final int LABELTABLEFULL = 6; 
  final int DUPLABEL = 7; 
  final int UNDEFLABEL = 8; 
  final int THENEXPECTED = 9; 
  final int TOEXPECTED = 10; 
  final int NEXTWITHOUTFOR = 11; 
  final int RETURNWITHOUTGOSUB = 12; 
  final int MISSINGQUOTE = 13;
  final int FILENOTFOUND = 14; 
  final int FILEIOERROR = 15; 
  final int INPUTIOERROR = 16;

  // Internal representation of the Small BASIC keywords.
  final int UNKNCOM = 0;
  final int PRINT = 1;
  final int INPUT = 2;
  final int IF = 3;
  final int THEN = 4;
  final int FOR = 5;
  final int NEXT = 6;
  final int TO = 7;
  final int GOTO = 8;
  final int GOSUB = 9;
  final int RETURN = 10;
  final int END = 11;
  final int EOL = 12;

  // This token indicates end-of-program. 
  final String EOP = "\0"; 
 
  // Codes for double-operators, such as <=.
  final char LE = 1;
  final char GE = 2;
  final char NE = 3;

  // Array for variables.  
  private double vars[];
 
  // This class links keywords with their keyword tokens.
  class Keyword { 
    String keyword; // string form 
    int keywordTok; // internal representation 

    Keyword(String str, int t) {
      keyword = str;
      keywordTok = t;
    }
  }

  /* Table of keywords with their internal representation.
     All keywords must be entered lowercase. */
  Keyword kwTable[] = { 
    new Keyword("print", PRINT), // in this table. 
    new Keyword("input", INPUT),
    new Keyword("if", IF),
    new Keyword("then", THEN),
    new Keyword("goto", GOTO),
    new Keyword("for", FOR),
    new Keyword("next", NEXT),
    new Keyword("to", TO),
    new Keyword("gosub", GOSUB),
    new Keyword("return", RETURN),
    new Keyword("end", END)
  };

  private char[] prog; // refers to program array
  private int progIdx; // current index into program

  private String token; // holds current token  
  private int tokType;  // holds token's type  

  private int kwToken; // internal representation of a keyword

  // Support for FOR loops.
  class ForInfo {
    int var; // counter variable 
    double target; // target value 
    int loc; // index in source code to loop to 
  }

  // Stack for FOR loops.
  private Stack fStack;

  // Defines label table entries.
  class Label {
    String name; // label 
    int loc; // index of label's location in source file 
    public Label(String n, int i) {
      name = n;
      loc = i;
    }
  }

  // A map for labels.
  private TreeMap labelTable;

  // Stack for gosubs.
  private Stack gStack;

  // Relational operators.
  char rops[] = {
    GE, NE, LE, '<', '>', '=', 0
  };

  /* Create a string containing the relational
     operators in order to make checking for
     them more convenient. */
  String relops = new String(rops);

  // Constructor for SBasic.
  public SBasic(String progName) 
      throws InterpreterException {

    char tempbuf[] = new char[PROG_SIZE];
    int size;

    // Load the program to execute.
    size = loadProgram(tempbuf, progName);

    if(size != -1) {
      // Create a properly sized array to hold the program.
      prog = new char[size];

      // Copy the program into program array.
      System.arraycopy(tempbuf, 0, prog, 0, size);
    }
  }

  // Load a program.
  private int loadProgram(char[] p, String fname)
    throws InterpreterException
  {
    int size = 0;

    try {
      FileReader fr = new FileReader(fname);

      BufferedReader br = new BufferedReader(fr);

      size = br.read(p, 0, PROG_SIZE);

      fr.close();
    } catch(FileNotFoundException exc) {
      handleErr(FILENOTFOUND);
    } catch(IOException exc) {
      handleErr(FILEIOERROR);
    }   

    // If file ends with an EOF mark, back up.
    if(p[size-1] == (char) 26) size--;

    return size; // return size of program
  }

  // Execute the program.
  public void run() throws InterpreterException {

    // Initialize for new program run.
    vars = new double[26];  
    fStack = new Stack();
    labelTable = new TreeMap();
    gStack = new Stack();
    progIdx = 0;

    scanLabels(); // find the labels in the program 

    sbInterp(); // execute

  }

  // Entry point for the Small BASIC interpreter.
  private void sbInterp() throws InterpreterException
  {

    // This is the interpreter's main loop.
    do {
      getToken();
      // Check for assignment statement.
      if(tokType==VARIABLE) {
        putBack(); // return the var to the input stream 
        assignment(); // handle assignment statement 
      }
      else // is keyword
        switch(kwToken) {
          case PRINT:
            print();
            break;
          case GOTO:
            execGoto();
            break;
          case IF:
            execIf();
            break;
          case FOR:
            execFor();
            break;
          case NEXT:
            next();
            break;
          case INPUT:
            input();
            break;
          case GOSUB:
            gosub();
            break;
          case RETURN:
            greturn();
            break;
          case END:
            return;
        }
    } while (!token.equals(EOP));
  }

  // Find all labels. 
  private void scanLabels() throws InterpreterException
  {
    int i;
    Object result;

    // See if the first token in the file is a label.
    getToken();
    if(tokType==NUMBER) 
      labelTable.put(token, new Integer(progIdx));

    findEOL();

    do {     
      getToken();
      if(tokType==NUMBER) {// must be a line number
        result = labelTable.put(token,
                                new Integer(progIdx));
        if(result != null)
          handleErr(DUPLABEL);
      }

      // If not on a blank line, find next line. 
      if(kwToken != EOL) findEOL();
    } while(!token.equals(EOP));
    progIdx = 0; // reset index to start of program
  }

  // Find the start of the next line.
  private void findEOL()
  {
    while(progIdx < prog.length &&
          prog[progIdx] != '\n') ++progIdx;
    if(progIdx < prog.length) progIdx++;
  }

  // Assign a variable a value.
  private void assignment() throws InterpreterException
  {
    int var;
    double value;
    char vname;

    // Get the variable name.
    getToken();
    vname = token.charAt(0);

    if(!Character.isLetter(vname)) {
      handleErr(NOTVAR);
      return;
    }

    // Convert to index into variable table.
    var = (int) Character.toUpperCase(vname) - 'A';
   
    // Get the equal sign.
    getToken();
    if(!token.equals("=")) {
      handleErr(EQUALEXPECTED);
      return;
    }

    // Get the value to assign.
    value = evaluate();

    // Assign the value.
    vars[var] = value;
  }

  // Execute a simple version of the PRINT statement.
  private void print() throws InterpreterException
  {
    double result;
    int len=0, spaces;
    String lastDelim = "";

    do {
      getToken(); // get next list item 
      if(kwToken==EOL || token.equals(EOP)) break;

      if(tokType==QUOTEDSTR) { // is string
        System.out.print(token);
        len += token.length();
        getToken();
      }
      else { // is expression
        putBack();
        result = evaluate();
        getToken();
        System.out.print(result);

        // Add length of output to running total.
        Double t = new Double(result);
        len += t.toString().length(); // save length
      }
      lastDelim = token;

      // If comma, move to next tab stop.
      if(lastDelim.equals(",")) {
        // compute number of spaces to move to next tab
        spaces = 8 - (len % 8); 
        len += spaces; // add in the tabbing position
        while(spaces != 0) { 
          System.out.print(" ");
          spaces--;
        }
      }
      else if(token.equals(";")) {
        System.out.print(" ");
        len++;
      }
      else if(kwToken != EOL && !token.equals(EOP))
        handleErr(SYNTAX); 
    } while (lastDelim.equals(";") || lastDelim.equals(","));

    if(kwToken==EOL || token.equals(EOP)) {
      if(!lastDelim.equals(";") && !lastDelim.equals(","))
        System.out.println();
    }
    else handleErr(SYNTAX); 
  }

  // Execute a GOTO statement. 
  private void execGoto() throws InterpreterException
  {
    Integer loc;

    getToken(); // get label to go to 

    // Find the location of the label.
    loc = (Integer) labelTable.get(token);

    if(loc == null)
      handleErr(UNDEFLABEL); // label not defined 
    else // start program running at that loc
      progIdx = loc.intValue();
  }

  // Execute an IF statement.
  private void execIf() throws InterpreterException
  {
    double result;

    result = evaluate(); // get value of expression

    /* If the result is true (non-zero),
       process target of IF. Otherwise move on
       to next line in the program. */
    if(result != 0.0) { 
      getToken();
      if(kwToken != THEN) {
        handleErr(THENEXPECTED);
        return;
      } // else, target statement will be executed 
    }
    else findEOL(); // find start of next line 
  }

  // Execute a FOR loop. 
  private void execFor() throws InterpreterException
  {
    ForInfo stckvar = new ForInfo();
    double value;
    char vname;

    getToken(); // read the control variable 
    vname = token.charAt(0);
    if(!Character.isLetter(vname)) {
      handleErr(NOTVAR);
      return;
    }

    // Save index of control var.
    stckvar.var = Character.toUpperCase(vname) - 'A';

    getToken(); // read the equal sign
    if(token.charAt(0) != '=') {
      handleErr(EQUALEXPECTED);
      return;
    }

    value = evaluate(); // get initial value 

    vars[stckvar.var] = value;

    getToken(); // read and discard the TO
    if(kwToken != TO) handleErr(TOEXPECTED);

    stckvar.target = evaluate(); // get target value

    /* If loop can execute at least once,
       push info on stack. */
    if(value >= vars[stckvar.var]) { 
      stckvar.loc = progIdx;
      fStack.push(stckvar);
    }
    else // otherwise, skip loop code altogether
      while(kwToken != NEXT) getToken();
  }

  // Execute a NEXT statement. 
  private void next() throws InterpreterException
  {
    ForInfo stckvar;

    try {
      // Retrieve info for this For loop.
      stckvar = (ForInfo) fStack.pop();
      vars[stckvar.var]++; // increment control var
  
      // If done, return.
      if(vars[stckvar.var] > stckvar.target) return; 

      // Otherwise, restore the info.
      fStack.push(stckvar);
      progIdx = stckvar.loc;  // loop 
    } catch(EmptyStackException exc) {
      handleErr(NEXTWITHOUTFOR);
    }
  }

  // Execute a simple form of INPUT. 
  private void input() throws InterpreterException
  {
    int var;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -