dawnparser.java

来自「java写的多功能文件编辑器」· Java 代码 · 共 1,051 行 · 第 1/2 页

JAVA
1,051
字号
  public void exec() throws DawnRuntimeException  {    if (st == null)      throw new DawnRuntimeException(this, "parser cannot execute a non-existent script");    try    {      for( ; ; )      {        if (stopped)          return;        switch(st.nextToken())        {          case StreamTokenizer.TT_EOL:            lineno++;            break;          case StreamTokenizer.TT_EOF:            // end of script            return;          case StreamTokenizer.TT_NUMBER:            stack.push(new Double(st.nval));            break;          case StreamTokenizer.TT_WORD:            if (st.sval.equals("needs") || st.sval.equals("needsGlobal"))            {              int keyWord = (st.sval.equals("needs") ? 0 : 1);              if (st.nextToken() == StreamTokenizer.TT_WORD)              {                if (keyWord == 1)                  installPackage(st.sval);                else                  installPackage(DawnParser.class, st.sval, this);                break;              } else {                st.pushBack();                throw new DawnRuntimeException(this, "bad usage of \'needs\' or \'needsGlobal\'" +                                                     "reserved keyword");              }            }            Function func = (Function) functions.get(st.sval);            if (func != null)              func.invoke(this);            else            {              func = (Function) runtimeFunctions.get(st.sval);              if (func != null)                func.invoke(this);              else                stack.push(st.sval);            }            break;          case '-':            Function fc;            if (st.nextToken() == StreamTokenizer.TT_WORD)            {              fc = (Function) functions.get('-' + st.sval);              if (fc == null)              {                fc = (Function) runtimeFunctions.get('-' + st.sval);                if (fc == null)                {                  st.pushBack();                  fc = (Function) functions.get("-");                }              }            } else {              st.pushBack();              fc = (Function) functions.get("-");            }            if (fc != null)              fc.invoke(this);            break;          case '"': case '\'':            pushString(st.sval);            break;        }      }    } catch (IOException ioe) {      throw new DawnRuntimeException(this, "unexpected error occured during parsing");    }  }  /**   * Returns the <code>Hashtable</code> which contains the local variables.   */  public Hashtable getVariables()  {    return runtimeVariables;  }  /**   * Returns the <code>Hashtable</code> which contains the global variables.   */  public Hashtable getGlobalVariables()  {    return variables;  }  /**   * Returns the value of a given variable. Note that global variables got   * priority on runtime ones.   * @param var The variable to be recalled      */  public Object getVariable(String var)  {    Object obj = variables.get(var);    if (obj == null)      obj = runtimeVariables.get(var);    return obj;  }  /**   * Sets a runtime variable. Runtime variables are stored temporarily. After   * the execution of the script, they are flushed.   * @param var The variable name   * @param value An <code>Object</code> containg the variable value   */  public void setVariable(String var, Object value)  {    if (value == null)      runtimeVariables.remove(var);    else if (!functions.contains(var) && !runtimeFunctions.contains(var))      runtimeVariables.put(var, value);  }  /**   * Sets a global variable. Global variables are stored permanently, until the   * JVM is killed or until the method <code>clearGlobalVariables()</code> is called.   * @param var The variable name   * @param value An <code>Object</code> containg the variable value   */  public static void setGlobalVariable(String var, Object value)  {    if (value == null)      variables.remove(var);    else if (!functions.contains(var))      variables.put(var, value);  }  /**   * Clears all the global variables.   */  public static void clearGlobalVariables()  {    variables.clear();  }  /**   * Returns current line number in the script.   */  public int lineno()  {    // return st.lineno();    return lineno;  }  /**   * Returns a <code>String</code> containing a simple description of the current stack   * state. All the levels are shown, each labeled by its level number.   */  public String dump()  {    Object o;    StringBuffer buf = new StringBuffer();    for (int i = 0; i < stack.size(); i++)    {      buf.append(stack.size() - 1 - i).append(':');      o = stack.elementAt(i);      if (o instanceof Vector)        buf.append("array[").append(((Vector) o).size()).append(']');      else        buf.append(o);      buf.append('\n');    }    return buf.toString();  }  /**   * Get topmost element of the stack and return is as a double value   * if it can. Otherwise, an exception is thrown. In any case, the   * element is removed from the stack.   */  public double popNumber() throws DawnRuntimeException  {    checkEmpty(null);    Object obj = stack.pop();    if (!(obj instanceof Double))    {      throw new DawnRuntimeException(this, "bad argument type");    }    return ((Double) obj).doubleValue();  }  /**   * Get topmost element of the stack and return is as a double value   * if it can. Otherwise, an exception is thrown.   */  public double peekNumber() throws DawnRuntimeException  {    checkEmpty(null);    Object obj = stack.peek();    if (!(obj instanceof Double))    {      throw new DawnRuntimeException(this, "bad argument type");    }    return ((Double) obj).doubleValue();  }  /**   * Pushes a number on top of the stack.   * @param number The number to be put on the stack   */  public void pushNumber(double number)  {    stack.push(new Double(number));  }  /**   * Get the topmost element of the stack and returns it as   * a <code>String</code>. If the string is enclosed by " quote   * characters, they are removed. The element is removed from the stack.   */  public String popString() throws DawnRuntimeException  {    checkEmpty(null);    String str = stack.pop().toString();    if (str.length() != 0 && str.startsWith("\"") && str.endsWith("\""))      str = str.substring(1, str.length() - 1);    return str;  }  /**   * Get the topmost element of the stack and returns it as   * a <code>String</code>. If the string is enclosed by " quote   * characters, they are removed.   */  public String peekString() throws DawnRuntimeException  {    checkEmpty(null);    String str = stack.peek().toString();    if (str.length() != 0 && str.startsWith("\"") && str.endsWith("\""))      str = str.substring(1, str.length() - 1);    return str;  }  /**   * Puts a <code>String</code> on top of the stack.   * @param str The string to be put on the stack   */  public void pushString(String str)  {    if (str.length() == 2 && str.charAt(0) == '\"' && str.charAt(1) == '\"')      stack.push("\"\"");    else      stack.push('"' + str + '"');  }  /**   * Gets topmost stack element and returns it as a <code>Vector</code>   * which is the Java object for Dawn arrays. The element is removed   * from the stack.   */  public Vector popArray() throws DawnRuntimeException  {    checkEmpty(null);    Object obj = stack.pop();    if (!(obj instanceof Vector))    {      throw new DawnRuntimeException(this, "bad argument type");    }    return (Vector) obj;  }  /**   * Gets topmost stack element and returns it as a <code>Vector</code>   * which is the Java object for Dawn arrays.   */  public Vector peekArray() throws DawnRuntimeException  {    checkEmpty(null);    Object obj = stack.peek();    if (!(obj instanceof Vector))    {      throw new DawnRuntimeException(this, "bad argument type");    }    return (Vector) obj;  }  /**   * Pushes an array on top of the stack.   * @param array The array to be put on the stack   */  public void pushArray(Vector array)  {    stack.push(array);  }  /**   * Returns topmost objet of the stack and remove it.   */  public Object pop() throws DawnRuntimeException  {    checkEmpty(null);    return stack.pop();  }  /**   * Returns topmost object of the stack.   */  public Object peek() throws DawnRuntimeException  {    checkEmpty(null);    return stack.peek();  }  /**   * Puts an object on the top of the stack.   * @param obj The object to be put on the top   */  public void push(Object obj)  {    stack.push(obj);  }  /**   * Tells wether topmost object is a numeric value or not.   */  public boolean isTopNumeric()  {    return stack.peek() instanceof Double;  }  /**   * Tells wether topmost object is a string or not.   */  public boolean isTopString()  {    Object obj = stack.peek();    if (obj instanceof String)    {      String str = (String) obj;      if (str.startsWith("\"") && str.endsWith("\""))        return true;    }    return false;  }  /**   * Tells wether topmost object is an array or not.   */  public boolean isTopArray()  {    return stack.peek() instanceof Vector;  }  /**   * Tells wether topmost object is a literal identifier or not.   */  public boolean isTopLiteral()  {    return !isTopString() && !isTopNumeric() && !isTopArray();  }  /**   * Returns topmost stack element type.   */  public int getTopType()  {    if (isTopNumeric())      return DAWN_NUMERIC_TYPE;    else if (isTopString())      return DAWN_STRING_TYPE;    else if (isTopArray())      return DAWN_ARRAY_TYPE;    else      return DAWN_LITERAL_TYPE;  }  /**   * Adds given function to the global functions list.   * @param function The <code>Function</code> to be added   */  public static void addGlobalFunction(Function function)  {    if (function == null)      return;    String name = function.getName();    if (!name.equals("needs") && !name.equals("needsGlobal"))      functions.put(name, function);  }  /**   * Adds given function to the runtime functions list.   * @param function The <code>Function</code> to be added   */  public void addRuntimeFunction(Function function)  {    if (function == null)      return;    String name = function.getName();    if (!name.equals("needs") && !name.equals("needsGlobal"))      runtimeFunctions.put(name, function);  }  /**   * Creates dynamically a function which can execute the Dawn script   * passed in parameter.   * @param code The Dawn code which will be executed by the returned   *             function on invoke() call   */  public Function createOnFlyFunction(final String code)  {    return new Function()    {      public void invoke(DawnParser parser) throws DawnRuntimeException      {        StreamTokenizer _st = st;        Hashtable _variables = (Hashtable) runtimeVariables.clone();        st = createTokenizer(new StringReader(code));        exec();        st = _st;        // copy changed variables        String _varName;        for (Enumeration e = runtimeVariables.keys(); e.hasMoreElements(); )        {          _varName = (String) e.nextElement();          if (_variables.get(_varName) != null)          {            _variables.put(_varName, runtimeVariables.get(_varName));          }        }        runtimeVariables = (Hashtable) _variables.clone();      }    };  }  /**   * Creates dynamically a function which can execute the Dawn script   * passed in parameter. The function is added to the global functions   * list and not returned.   * @param name Function Dawn name   * @param code The Dawn code which will be executed by function   */  public static void createGlobalFunction(String name, final String code)  {    if (name == null || name.length() == 0 || name.equals("needs") ||        name.equals("needsGlobal") || code == null)      return;    functions.put(name, new Function(name)    {      public void invoke(DawnParser parser) throws DawnRuntimeException      {        StreamTokenizer _st = parser.getStream();        parser.setStream(parser.createTokenizer(new StringReader(code)));        parser.exec();        parser.setStream(_st);      }    });  }  /**   * Creates dynamically a function which can execute the Dawn script   * passed in parameter. The function is added to the runtime functions   * list and not returned.   * @param name Function Dawn name   * @param code The Dawn code which will be executed by function   */  public void createRuntimeFunction(String name, final String code)  {    if (name == null || name.length() == 0 || name.equals("needs") ||        name.equals("needsGlobal") || code == null)      return;    runtimeFunctions.put(name, new Function(name)    {      public void invoke(DawnParser parser) throws DawnRuntimeException      {        StreamTokenizer _st = st;        st = createTokenizer(new StringReader(code));        exec();        st = _st;      }    });  }}// End of DawnParser.java

⌨️ 快捷键说明

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