Class ExpressionParser

java.lang.Object
org.bzdev.util.ExpressionParser
All Implemented Interfaces:
ObjectParser<Object>

public class ExpressionParser extends Object implements ObjectParser<Object>
Parser for expressions that produce numbers of type double. While most instance of ObjectParser provided in this package just implement the ObjectParser interface, ExpressionParser provides more capabilities. An ExpressionParser can remember previous values, can be configured to return values of various types, to accept various constants (enumeration constants or integer-valued fields) as arguments, and can evaluate functions and methods.

ExpressionParser also implements a scripting language named ESP. For the full syntax and capabilities, please see ExpressionParser and the ESP scripting language.

ExpressionParser provides two constructors. The first, ExpressionParser(Class...) creates an instance that provides functions that are implemented by public, static methods of the classes listed in the argument list. These are restricted to ones whose arguments and returned types are String, int, long, double, and boolean, Number, Double, Long, Integer, Boolean, and stream-related classes. The default behavior can be extended to allow more types and additional capabilities by using the second constructor ExpressionParser(Class[],Class[],Class[],Class[],Class[]). The arguments to this constructor are

  1. An array for classes providing the types that can be returned by methods or functions.
  2. An array of classes providing the types allowed as arguments for functions and methods.
  3. An array of classes providing those classes whose static methods will be used as functions (the effect is similar to using Java's static import statement).
  4. An array of classes providing those classes whose instance methods will be available.
  5. An array of classes provides those classes whose public, static, and final fields that are int-valued or enumeration constants will be available.
The methods and functions are filtered to include only those
  • whose return values are int, double, or any of the classes listed in the first argument to the constructor.
  • whose arguments are int, double, or any of the classes listed in the second argument to the { constructor.
  • Constructor Details

    • ExpressionParser

      public ExpressionParser(Class<?>... classes) throws IllegalAccessException
      Constructor. The arguments are classes that will be scanned for public, static methods that return a 'double' value and whose argument have the type
      • int. An argument of this type must be a literal or an expression guaranteed to return an int.
      • long. An argument of this type must be a literal or an expression guaranteed to return a long.
      • boolean. An argument of this type must be a literal (true or false) or an expression guaranteed to return a boolean.
      • String. An argument of this type must be a literal or a function guaranteed to return a string.
      • double. An argument of this type may be an expression, a literal, or a function call.
      Parameters:
      classes - the classes whose static methods will be used as functions
      Throws:
      IllegalAccessException - a requested class, method, or field could not be accessed
    • ExpressionParser

      public ExpressionParser(Class<?>[] returnTypes, Class<?>[] argumentTypes, Class<?>[] functionClasses, Class<?>[] methodClasses, Class<?>[] fieldClasses) throws IllegalAccessException
      Constructor for extended expressions.
      Parameters:
      returnTypes - the types that may be returned by function or method, or the type of an object whose constructors may be used
      argumentTypes - the types that can be used as function or method arguments
      functionClasses - the classes whose static methods will be used as functions.
      methodClasses - the classes whose public instance methods may be used.
      fieldClasses - the classes whose public, static, final fields may be used.
      Throws:
      IllegalAccessException - a requested class, method, or field could not be accessed
  • Method Details

    • setReader

      public void setReader(Reader reader)
      Set the reader. A reader can be used by a script for obtaining input. The reader can be overridden on a per-thread basis by calling setReaderTL(java.io.Reader).

      A null argument does not restore the initial value.

      Parameters:
      reader - the reader.
    • setWriter

      public void setWriter(PrintWriter writer)
      Set the writer. A writer can be used by a script for normal output. The writer can be overridden on a per-thread basis by calling setWriterTL(java.io.PrintWriter).

      A null argument does not restore the initial value.

      Parameters:
      writer - the writer.
    • setErrorWriter

      public void setErrorWriter(PrintWriter errorWriter)
      Set the error writer. A writer can be used by a script for error output. The error writer can be overridden on a per-thread basis by calling setErrorWriterTL(java.io.PrintWriter).

      A null argument does not restore the initial value.

      Parameters:
      errorWriter - the writer.
    • setReaderTL

      public void setReaderTL(Reader reader)
      Set the thread-specific reader. A reader can be used by a script for obtaining input. A thread-specific reader, if not null, will be chosen instead of the reader specified by setReader(java.io.Reader).
      Parameters:
      reader - the reader.
    • setWriterTL

      public void setWriterTL(PrintWriter writer)
      Set the thread-specific writer. A writer can be used by a script for normal output. A thread-specific writer, if not null, will be chosen instead of the writer specified by setWriter(java.io.PrintWriter).
      Parameters:
      writer - the writer.
    • setErrorWriterTL

      public void setErrorWriterTL(PrintWriter errorWriter)
      Set the thread-specific error writer. A writer can be used by a script for error output. A thread-specific error writer, if not null, will be chosen instead of the error writer specified by setErrorWriter(java.io.PrintWriter).
      Parameters:
      errorWriter - the writer.
    • isVoid

      public static final boolean isVoid(Object object)
      Determine if a value is void. Instances of ESPFunction can return a designated value to indicate that no value is actually returned. This method checks an object to see if it is this designated value.
      Parameters:
      object - the object to test
      Returns:
      true if the object is void; false otherwise
      See Also:
    • setGlobalBindings

      public void setGlobalBindings(Map<String,Object> gmap)
      Set Global bindings. Global bindings are provided because of the API used by the package javax.script. API.
      Parameters:
      gmap - the global bindings; null to remove them
    • setScriptingMode

      public void setScriptingMode() throws IllegalStateException
      Turn on scripting mode. When this method is called, this expression processor will accept lines that contain multiple expressions, separated by semicolon, and will not require an "=" at the start of a top-level expression. This method should be called before an expression is parsed if it is called at all.
      Throws:
      IllegalStateException
    • setImportMode

      public void setImportMode() throws IllegalStateException
      Turn on import mode. When this method is called, this expression processor will allow new classes to be added. It must be called before a script calls a function or method. It should be called before an expression is parsed if it is called at all.
      Throws:
      IllegalStateException
    • setScriptImportMode

      public void setScriptImportMode()
      Set Script-Import mode. If script-import mode is turned on, a script can import classes.
    • setGlobalMode

      public void setGlobalMode() throws IllegalStateException
      Turn on global mode. When this method is called, this expression processor will allow a variable named global to be accessed. This variable provides various methods.
      Throws:
      IllegalStateException
    • addClasses

      public void addClasses(Class<?>... classes) throws IllegalAccessException
      Add a class to all appropriate tables. This is equivalent to including the class in each of the array arguments for the constructor ExpressionParser(Class[],Class[],Class[],Class[],Class[]). Primitive classes are ignored.
      Parameters:
      classes - the classes to add
      Throws:
      IllegalAccessException - a class or method is not accessible
    • findRVFMethod

      Find the method implementing a function. The argument is the name of a static method with one double-precision argument that returns a double-precision value, and must include enough of the class name to be unique given the classes used to define functions.
      Parameters:
      fname - the name of the function
      Returns:
      the method
      Throws:
      IllegalStateException - classes are missing or fname does not name a method that is recognized
      NoSuchMethodException - a method does not exist
      IllegalArgumentException - fname is not syntactically the name of a method
    • addFunction

      public void addFunction(String name, String[] args, String expressions, String filename, boolean synchronizedFunction)
      Add a named function, specifying a file name for its input file.
      Parameters:
      name - the name of the function
      args - the formal parameters for the function
      expressions - the expressions the represent the body of a function
      filename - the name of the file containing the function's expressions
      synchronizedFunction - true if this function is synchronized on this expression parser, false otherwise
    • addFunction

      public void addFunction(String name, String[] args, String expressions, boolean synchronizedFunction)
      Add a named function.
      Parameters:
      name - the name of the function
      args - the formal parameters for the function
      expressions - the expressions the represent the body of a function
      synchronizedFunction - true if this function is synchronized on this expression parser, false otherwise
    • getConstants

      public List<String> getConstants()
      Get the fully qualified names for enumeration constants and fields provided by this expression parser.

      This method is provided for applications that can list the available constants as part of a 'help' or documentation subsystem.

      Returns:
      the constants
    • getReturnClasses

      public ArrayList<Class<?>> getReturnClasses()
      Get the classes for objects that can be returned by this parser. The values returned do not include primitive types.

      This method is provided for applications that can list the types of objects that can be returned as part of a 'help' or documentation subsystem.

      Returns:
      the classes
    • getArgumentClasses

      public ArrayList<Class<?>> getArgumentClasses()
      Get the classes for objects that can be uses as arguments for functions or methods provided by this expression parser. The values returned do not include primitive types.

      This method is provided for applications that can list the types of objects that can be used as arguments as part of a 'help' or documentation subsystem.

      Returns:
      the classes
    • getConstructors

      public List<String> getConstructors()
      Get the constructors supported by this expression parser. Each element in the returned list consists of a fully qualified class name followed by an open parenthesis, a comma-separated list of the class names for the arguments, and a closing parenthesis.

      This method is provided for applications that can list the constructors and their arguments as part of a 'help' or documentation subsystem.

      Returns:
      a list of the constructors
    • getFunctions

      public List<String> getFunctions()
      Get the functions supported by this expression parser. Each element in the returned list consists of a fully qualified class name followed the function name that is in turn followed by an open parenthesis, a comma-separated list of the class names for the arguments, and a closing parenthesis.

      This method is provided for applications that can list functions and their arguments as part of a 'help' or documentation subsystem.

      Returns:
      a list of the functions
    • getMethods

      public List<String> getMethods()
      Get the methods supported by this expression parser. Each element in the returned list consists of a fully qualified class name followed by a colon, a space, and the method name. The method name is in turn followed by an open parenthesis, a comma-separated list of the class names for the arguments, and a closing parenthesis.

      This method is provided for applications that can list methods and their arguments as part of a 'help' or documentation subsystem.

      Returns:
      a list of the methods
    • keylistForConstants

      public TemplateProcessor.KeyMapList keylistForConstants()
      Get a key list for generating a table of constants. The key list will contain a sequence of key maps with the following keys:
      • href - The URL provided by the HREF attribute of an an <A>element, not including the delimiting quotes.
      • item - the fully qualified name of a constant
      This method is provided for generating HTML pages that can point to API documentation. The method createAPIMap(List) must be called before this method is used.
      Returns:
      the key list
    • keylistForReturnClasses

      public TemplateProcessor.KeyMapList keylistForReturnClasses()
      Get a key list for generating a table of classes, instances of which can be returned by an expression. The key list will contain a sequence of key maps with the following keys:
      • href - The URL provided by the HREF attribute of an an <A>element, not including the delimiting quotes.
      • item - the fully qualified class name of the class an expression can return
      This method is provided for generating HTML pages that can point to API documentation. The method createAPIMap(List) must be called before this method is used.
      Returns:
      the key list
    • keylistForArgumentClasses

      public TemplateProcessor.KeyMapList keylistForArgumentClasses()
      Get a key list for generating a table of . The key list will contain a sequence of key maps with the following keys:
      • href - The URL provided by the HREF attribute of an an <A>element, not including the delimiting quotes.
      • item - the fully qualified class name of a class for an argument to a constructor, function or method recognized by this expression parser
      This method is provided for generating HTML pages that can point to API documentation. The method createAPIMap(List) must be called before this method is used.
      Returns:
      the key list
    • keylistForConstructors

      public TemplateProcessor.KeyMapList keylistForConstructors()
      Get a key list for generating a table of constructors. The key list will contain a sequence of key maps with the following keys:
      • href - The URL provided by the HREF attribute of an an <A>element, not including the delimiting quotes.
      • class - the fully qualified class name for the object a constructor will create.
      • item - the simple class name followed by an open parenthesis, a comma-separated list of the types of the constructor's arguments, followed by a closing parenthesis.
      • arguments - an opening parenthesis, followed by a comma-separated list of argument class names, followed by a closing parenthesis.
      This method is provided for generating HTML pages that can point to API documentation. The method createAPIMap(List) must be called before this method is used.
      Returns:
      the key list
    • keylistForFunctions

      public TemplateProcessor.KeyMapList keylistForFunctions()
      Get a key list for generating a table of functions. The key list will contain a sequence of key maps with the following keys:
      • href - The URL provided by the HREF attribute of an an <A>element, not including the delimiting quotes.
      • class - the fully qualified class name for a class, one of whose static methods implements the function.
      • item - the name of the static method representing the function followed by an open parenthesis, a comma-separated list of the types of the function's arguments, followed by a closing parenthesis.
      • method - the simple name of the function.
      • arguments - an opening parenthesis, followed by a comma-separated list of argument class names, followed by a closing parenthesis.
      This method is provided for generating HTML pages that can point to API documentation. The method createAPIMap(List) must be called before this method is used.
      Returns:
      the key list
    • keylistForMethods

      public TemplateProcessor.KeyMapList keylistForMethods()
      Get a key list for generating a table of instance methods, excluding methods for String. The key list will contain a sequence of key maps with the following keys:
      • href - The URL provided by the HREF attribute of an an <A>element, not including the delimiting quotes.
      • class - the fully qualified class name for the class declaring a method.
      • item - the name of the method followed by an open parenthesis, a comma-separated list of the types of the method's arguments, followed by a closing parenthesis.
      • method - the simple name of the function.
      • arguments - an opening parenthesis, followed by a comma-separated list of argument class names, followed by a closing parenthesis.
      This method is provided for generating HTML pages that can point to API documentation. The method createAPIMap(List) must be called before this method is used.
      Returns:
      the key list
    • keylistForMethods

      public TemplateProcessor.KeyMapList keylistForMethods(boolean hideString)
      Get a key list for generating a table of instance methods. The key list will contain a sequence of key maps with the following keys:
      • href - The URL provided by the HREF attribute of an an <A>element, not including the delimiting quotes.
      • class - the fully qualified class name for the class declaring a method.
      • method - the simple name of the function.
      • item - the name of the method followed by an open parenthesis, a comma-separated list of the types of the method's arguments, followed by a closing parenthesis.
      • arguments - an opening parenthesis, followed by a comma-separated list of argument class names, followed by a closing parenthesis.
      This method is provided for generating HTML pages that can point to API documentation. The method createAPIMap(List) must be called before this method is used.
      Parameters:
      hideString - true if methods of String should not be shown; false otherwise
      Returns:
      the key list
    • appliesTo

      public boolean appliesTo(String string)
      Description copied from interface: ObjectParser
      Determine this parser applies to a given string.

      The default implementation simply calls ObjectParser.matches(String) and returns the results of calling that method. This method should be overridden when less restrictive criteria can be used. For example, a parser that provides a Color might accept strings that start with 'rgb(', 'rgba(', etc. Then a syntax error can be reported if ObjectParser.matches(String) returns false.

      Specified by:
      appliesTo in interface ObjectParser<Object>
      Parameters:
      string - a string to parse
      Returns:
      true if this string should be used with this parser; false otherwise
    • get

      public Object get(String name)
      Get the value of a variable or function.
      Parameters:
      name - the name of the variable or function
      Returns:
      the value of the variable or the lambda expression (an instance of ExpressionParser.ESPFunction) implementing the function
    • exists

      public boolean exists(String name)
      Determine if a variable or function exists.
      Parameters:
      name - the name of the variable
      Returns:
      true if the variable exists; false otherwise
    • set

      public void set(String name, Object value)
      Set the value of a variable.
      Parameters:
      name - the name of the variable
      value - the value of the variable
    • remove

      public Object remove(String name)
      Remove a variable.
      Parameters:
      name - the name of the variable
      Returns:
      the value of the variable being removed
    • variables

      public Set<String> variables()
      Get the variables for this expression parser.
      Returns:
      a set containing the names of the variables
    • clear

      public void clear()
      Remove all variables from this expression parser and reset it.
    • matches

      public boolean matches(String s)
      Description copied from interface: ObjectParser
      Determine if a string is syntactically valid.
      Specified by:
      matches in interface ObjectParser<Object>
      Parameters:
      s - the string
      Returns:
      true if the test succeeds; false if it fails
    • setBindings

      public void setBindings(Map<String,Object> bindings)
      Set the bindings for this parser. Bindings are maps that assign objects to variable names for variables defined outside a function or object. The map should be a synchronized map if an application is multithreaded.
      Parameters:
      bindings - the binding
    • getBindings

      public Map<String,Object> getBindings()
      Set the bindings for this parser. Bindings are maps that assign objects to variable names.
      Returns:
      the bindings
    • parse

      public Object parse(String s) throws ObjectParser.Exception
      Description copied from interface: ObjectParser
      Parse a string and return the corresponding object.
      Specified by:
      parse in interface ObjectParser<Object>
      Parameters:
      s - the string
      Returns:
      the corresponding object
      Throws:
      ObjectParser.Exception - if the string could not be successfully parsed or the object could not be created
    • parse

      public Object parse(String s, String filename)
      Parse a string and return the corresponding object. The filename argument is simply a string that will be used as a label to denote the source of the first argument, and will nearly always be a file name.
      Parameters:
      s - the string
      filename - a name to label the first argument
      Returns:
      the corresponding object
      Throws:
      ObjectParser.Exception - if the string could not be successfully parsed or the object could not be created
    • parse

      public Object parse(String s, String filename, Map<String,Object> bindings)
      Parse a string and return the corresponding object. The filename argument is simply a string that will be used as a label to denote the source of the first argument, and will nearly always be a file name.
      Parameters:
      s - the string
      filename - a name to label the first argument
      bindings - a map assigning objects to variable names
      Returns:
      the corresponding object
      Throws:
      ObjectParser.Exception - if the string could not be successfully parsed or the object could not be created
    • parse

      public Object parse(String s, Map<String,Object> bindings) throws ObjectParser.Exception
      Parse a string and return the corresponding object
      Parameters:
      s - the string
      bindings - a map assigning objects to variable names
      Returns:
      the corresponding object
      Throws:
      ObjectParser.Exception - if the string could not be successfully parsed or the object could not be created
    • setPrefixMode

      public void setPrefixMode()
      Set prefix mode. Prefix mode requires that a script start with an '=' or the keywords "var" "function", or "synchronized" followed by "function". This mode does not have to be set unless scripting mode is enabled.
    • findDocURL

      public URL findDocURL(Class<?> clasz)
      Find the URL for a javadoc file for the given class.
      Parameters:
      clasz - the class
      Returns:
      the URL
    • findDocURL

      public URL findDocURL(String classname)
      Find the URL for a javadoc file for the given class name.
      Parameters:
      classname - the fully qualified class name
      Returns:
      the URL
    • findDocURL

      public URL findDocURL(Class<?> clasz, String rest)
      Find the URL for a javadoc file for the given class and field, method or constructor within that class.
      Parameters:
      clasz - the class
      rest - the remainder of the method, field, or constructor specification
      Returns:
      the URL
    • findDocURL

      public URL findDocURL(String classname, String rest)
      Find the URL for a javadoc file for the given class name and field, method or constructor within that class.
      Parameters:
      classname - the name of the class
      rest - the remainder of the method, field, or constructor specification
      Returns:
      the URL
    • createAPIMap

      public void createAPIMap(List<URL> apis) throws IOException
      Create a table mapping package names to the location containing the HTML files for that package's documentation. For the javadoc directories provided by the JDK, the name of the final component in the path is "api" and that directory will contain a file named either element-list or package-list.
      Parameters:
      apis - a list of the URLS for javadoc directories
      Throws:
      IOException - an IO error occurred