- JavaDoc

# Jep Java

- Introduction
- Basic Usage
- Variables
- Data types
- Operators
- Functions
- Custom Functions
- BigDecimal
- Modules
- Printing
- FAQ
- Migration
- Version History

# Advanced Features

- Manipulating Expressions
- Components
- Configurable Parser
- Serialization
- Threads
- Localization
- Grammar
- Other advanced features
- Use of Design Patterns in Jep

# Jep 3 Releases

Jep 4 Releases | Jep 3 Releases | Jep 2 Releases | Jep 1 Releases

## Version 3.5

### Major new features

Localization:

- All error messages now allow for localization.
- New accessor class `com.singularsys.jep.JepMessages`.
- Default properties file `com.singularsys.jep.messages.properties` provides default English messages
- Reworking of messages to use more consistent syntax and increased detail.
- New test class `com.singularsys.jeptests.system.MessagesTest` which checks Exceptions are thrown and prints all messages produced by Jep in the current locale.

Threads

- New `threadsafeevaluator` package which allows the same expression to be evaluated in multiple threads/Jep instances without needing to transfer.
- New `ImportationVisitor` class which allows quicker transfer of an expression between multiple threads/Jep instances.
- `ThreadSpeedTest` compares evaluation speed with multiple threads. This was previously named `ThreadTest` Both in the `com.singularsys.jepexamples.diagnostics` package.
- New `ThreadSafeSpeedTest` class used to test speeds using the `ThreadSafeEvaluator`.

Bound variables:

- New package which can tie a Jep variable to a field of an object. Changing the value of the Jep variable automatically changes and vice versa.

### Major changes

ConfigurableParser:

- Line and column number information added to Configurable parser error messages when available.
- New `LookaheadNIterator` which allows any given number of characters of lookahead.
- Expose callback method `GrammarParser.parsePrefixSuffix()` allowing GrammarMatchers to ask the parser for a prefix-terminal-suffix like "-2", "x", "5!" or "sin(x)". Implement in the ShuntingYard parser
- New `SingleArgFunctionMatcher` which can parse expressions like "sin 30" with a single simple argument and no brackets.
- Some new protected methods in `ShuntingYard` allowing test matching of prefix expressions
- New `prev()` for `Lookahead2Iterator` allow last token consumed to be examined, useful for debugging messages.
- New default constructor and `setInputIterator()` method for `Lookahead2Iterator` allows nested grammatical parsers.
- Protected `errorToken()` method for improved error reporting in `FunctionGrammarMatcher`
- Reworked action of `OperatorTokenMatcher` one `OperatorToken` will be produced for each operator encountered, allowing line and column numbers to be recorded. Changed constructors for `OperatorToken`.
- `GrammarParserFactory` and `TokenizerFactory` now implement `JepComponent` and these can now be specified with `jep.setComponent()` which simplifies the construction process.
- Rework internal operation of Ternary Operators, inner class is no longer static
- Added an optional GrammarMatcher `com.singularsys.jep.configurableparser.matchers.SingleArgFunctionMatcher` which can parse functions like "sin 30" with no brackets and a single argument.
- New `OperatorAsFunctionGrammarMatcher` which allows all operators to be used like functions, so it is possible to parse `+(1,2,3,4)`.
- The `VariableTable` has a method `removeNonConstants()` which removes all non-constant variables.
- `Variable` can have annotation using the `setHook(HookKey key, Object value)` and `Object getHook(HookKey key)` methods. These use the `Node.HookKey` interface.
- New `ComponentSubset` class to hold a partial set of components.

Functions:

- New `NullaryFunction` base class for functions with zero arguments. Implemented by `Random` and `ThreadSafeRandom` and `ConstantFunction`
- Moved `StringFunctionSet` from `com.singularsys.jep.functions.strings` to `com.singularsys.jep.misc` to remove package dependence.
- Function `Average` have altered functions specifying the Add, Divide methods used.
- Remove the `CallbackEvaluationI.Runnable` interfaces, impacting three classes `Case`, `Switch` and `SwitchDefault`, but no functional change.
- Add a `getID()` to `Comparative`
- Add a protected `getVariable()` method to `Ele` which is overridden by the thread-safe subclass `ThreadSafeEle`
- Add a new constructor `IllegalParameterException(PostfixMathCommandI pfmc, int pos, String expectedMsg, Object actualObject)`
- Remove several non-functional `run()` methods whose error behaviour is now handled by base class `PostfixMathCommand`
- Base 10 `Logarithm` now has correct values for negative and complex arguments
- Removed the `CheckStack()` protected method from `PostfixMathCommand`
- New `com.singularsys.jep.misc.threadsafeeval.ThreadSafeRandom` provides a faster random function based on Java's ThreadLocalRandom
- `Factorial` moved out of the `ExtendedOperatorSet` into its own class. The function throws exception when argument is greater than 20 causing overflow.
- `ExtendedOperatorSet` no longer includes a ternary conditional operator as duplicate that in the JavaOperatorSet.
- Functions can implement the `JepComponent` interface. Their `init(Jep)` method will be called whenever Jep is reinitialised. Likewise their `getLightWeightInstance()` will be called when building a function table for use in a separate thread.

BigDecimals:

- `BigDecFunctionTable` now provide the `if(cond,val1,val2), abs(val), signum(val), min(val1,val2,...), max(val1,val2,...), average(val1,val2,...), round(val), round(val,dp), roundSF(val,s), rint(val), rint(val,dp), ceil(val), floor(val)` functions by default.
- All functions coerce Number values into BigDecimal values.
- New `BigDecAbs`, `BigDecRound`, `BigDecRoundSigFig`, `BigDecSignum` functions.
- Internal structure of `BigDecAdd` etc. reworked so they work with the `Min, Max` and `Average` functions.
- New `BigDecTieBreakComparative` to allow predictable behaviour for min/max when given two equal big decimal numbers with different precisions

NullWrapper package:

- Reorganisation and renaming classes in package, with consistent naming generally now beginning `NullWrapped...` All function base classes and interfaces now moved to com.singularsys.jep.misc.functions. This will break existing code using this package.
- nullwrapped package now handles all functions, including those in the misc package.
- Bug fixed with NullWrapped versions of PostfixMathCommands with variable numbers of arguments. Evaluating these no longer cause exceptions.
- A new interface NullWrappedFunctionI created, to mark function which handle null wrapping correctly.
- NullWrapperFunctionFactory is no longer static
- Refactoring of NullWrappedFunctionTable and NullWrappedOperatorTable: the `getWrappedFunction(PostfixMathCommandI)` and `getSpecialFunction(PostfixMathCommandI)` functions moved to NullWrappedFunctionFactory. Breaks backward compatibility.
- Better error reporting with NullWrapped functions.
- Fixed bug with null wrapped lazy Logical operators so these now behave like SQL.

### Other new features

- The whole library now targets Java 1.7 rather than Java 1.5
- New `com.singularsys.jepexamples.diagnostics.DestructiveTests` diagnostic tool which checks the size of expressions which can be parsed/evaluated before Stack overflows.
- `Operator` now has an optional `printSymbol` property which can be used when printing out equations. This is of use when alphabetical operator names like "AND" are used, here the printSymbol is set to " AND " so that spaces appear when printing and `X==Y AND Z==W` is printed correctly.
- More complete tests for null values in `StandardEvaluator`
- A new `NullPrintVisitor` class for reduced memory footprint.
- New `ElementOf` function which can test if the first argument is in a list of items. `elementOf(x,"north","south","east","west")`
- New constructor for `IllegalParameterException` which allows details for expected result to be specified by a string.
- Default `PostfixMathCommand.run()` method which throws an exception reintroduced.
- New `OperatorAsFunctionGrammarMatcher` which allows specific operators to be treated as function, so you can have `+(1,2,3,4)`.
- Add an eq() method to `Complex` for testing equality using double ==.
- Add a single arg `buildFunctionNode(String,Node)` to `NodeFactory`.
- `VariableTableObserver` now has a switch to allow/dis-allow watching in change of variable values.
- The `Console` applications can set a double format to format numbers in printf like formats.
- History mechanism added to console applications.
- New method `Jep.setVariable(String,Object)` which works like `addVariable` but does not throw exceptions.
- Add a `trapUnsetValues` field `FastEvaluator` with corresponding getter and setters. Detects if a variable has an unset value.
- New `RealComponents` for the usecase where pure real evaluation is needed, function like sqrt(-1) return NaN rather than a complex number.
- The `DoNothingVisitor` now has a method `childrenHaveChanged(Node, Node[])` method to test if new children are different from the original.
- The `StandardVariableTable` and `RealVariableTable` now allow delayed initialisation with constants added when the VariableFactory is set in the init method.

### Removed features

- `PostfixMathCommand.checkStack()` method removed as of little utility.
- Unused interface `CallbackEvaluationI.Runnable` removed.
- Add method to Complex for printing a complex number in the (3.0+2.0 i) format when no number format is specified.

### Bug fixes

- Fixed bug with accessing 2D array elements in `Ele`.
- Fixed check for array bounds in `Ele` uses caught ArrayOutOfBounds exceptions rather than explicit checks.
- Fixed bug with setEle when the offset is zero in `Ele`.
- Fixed zero-impact bug with ID's of operator nodes in `NodeFactory`.
- Fixed bug where `VariableTable.clearValues()` called, but evaluators return previous values.
- Bug fix in `SymbolTokenMatcher` when parsing alternate symbols for operators.
- Fix bug with `NaryBinaryFunction` when given more than 2 arguments. (Not normally produced during parsing)
- Fixed bug with `Logarithm` (Log base 10) with complex arguments. Was giving results as natural logarithm.
- PrintVisitor did not work correctly with Complex constants.
- PrintVisitor now always puts brackets round unary ops on rhs, e.g., `a*(-b)`.

### Other changes

- Internal operation of some functions improved for minor speed up.
- Slight speed up in `RealEvaluator`, `FastEvaluator`
- The decorator constructors of `BitwiseOperatorTable` and `JavaOperatorTable` no longer set the basis operators instead using those in the supplied argument.
- The `LightWeightComponentSet` now uses the `NullPrintVisitor`.
- Changed access level modifiers of some fields in `Operator`, `FastEvaluator` and `PrintVisitor` to protected to allow use by subclasses
- Removed unused parser field in `SimpleNode` remove corresponding constructors in subclasses.
- Functions `Real`, `Str`, `BitComp` now implement `UnaryFunction`.
- Functions `BitAnd`, `BitOr` `BitXor` `LShift` `RShift` `URShift` now implement `BinaryFunction`.
- Functions `FromBase`, `Switch`, `SwitchDefault`, `ToBase`, `RShift`, and `URShift` now implement `NaryFunction`.
- Most methods in `NodeFactory` now have varargs parameters simplify the number of methods and several places they are called from. Will require corresponding changes in subclasses.
- Fix spelling of `basicIndetifierMatcher` and `dottedIndetifierMatcher`, replace with `basicIdentifierMatcher` and `dottedIdentifierMatcher` deprecate old versions.
- Add a `StackCheckingFastEvaluator` in the package `com.singularsys.jeptests.system` which can be used to detect some stack corruption errors.
- `PrintVisitor` in Full Bracket mode does no longer puts brackets around variables and positive constants as there is no ambiguity.
- Added a `sqrt()` function to the standard set of functions.

## Version 3.4

### Core Jep changes

- Allow strings to be used together with BigDecimals so that strings can be concatenated with + and compared in relations.
- Added an EmptyOperatorTable which has zero operators as a default. A consequence of this is moving of the OperatorKey interface to EmptyOperatorTable.
- The Jep class now has a constructor taking a list of components; some methods made protected to allow subclasses; has a `getAdditionComponent(Class<?>)` method to find components which instance a particular class.
- PrintVisitor adds an `append(String)` method allowing classes which implement PrintRulesI to append text to the output.
- The `VariableTable` has a new method `clearValues()` which clears the valid-value flag of all non-constant values. Constants are always valid.
- The standard parser is now generated with JavaCC 5.0 (previously JavaCC 4.0)

### Functions

- All function classes are no longer final to allow for sub-classing by users. Visibility of some methods increased to allow sub classing.
- The `round` function now uses Math.round and a new `rint` function is added which calls Math.rint. These differ in how 1.5 is rounded (rint rounds up to nearest even value, round always rounds down).
- The Average function can be configured to change behaviour for zero length arrays, either NaN is returned, or an Exception is thrown (the default). A `calc(List)` method makes it easier to create subclasses which act on lists of objects.
- The MinMax function now flattens its arguments so `min([1,[2,3]])` can be computed. The Comparative parameter can be set by subclasses.
- The new VSum function sums the elements in a vector or matrix.

### Configurable Parser

- New interfaces `TokenizerFactory`, `GrammarParserFactory` which allow different objects to be used for the tokenizing and parsing steps.
- `ShuntingYard` some methods made protected.
- `Tokenizer` constructor changed, line and column numbering start from 1.
- `OperatorTokenMatcher` improved handling of operators with word characters.
- `GrammarParser` has an additional method `public void setIterator(Lookahead2Iterator<Token>)` setting the iterator used by `parseSubExpression()`.

### Misc classes

- `MacroFunction` has an additional constructor for use with non-recursive functions.
- A new package `com.singularsys.jep.misc.lineNumbering` to allow line number information to be stored in nodes in the parse tree. With classes `LineNumberingNodeFactory`, `LineNumberingShuntingYard`.
- A new package `com.singularsys.jep.misc.nullwrapper` which provides functions and operators which propagate null values through results. These classes can be wrapped around other classes to add this functionality to existing classes.
- Additional constructions provided for visitors in `com.singularsys.jep.walkers` so they can be used as JepComponents.

### Tests and Examples

- JUnit Tests split into `system` and `unit` packages.

### Bug fixes

- Fixed bug with FastEvaluator when calling the same function twice.
- Fixed potential null reference exception in SimpleNode.hasNext()
- Fixed issue where PrintVisitor.getMode(int testmode) did not return the correct value.

## Version 3.3

### Core Jep changes

- New default evaluator FastEvaluator which achieves a 2x-3x speed improvement using the new interfaces. StandardEvaluator is still available for compatibility purposes.
- New constructor `Jep(JepComponent... comp)` which makes it easier to construct Jep with a specific set of components. For example, `new Jep(new StandardConfigurableParser())`.
- New version of the operator table OperatorTable2 which uses enums to specify keys. Methods that are common to all operator tables are declared in a new interface OperatorTableI. Note that `Jep.getOperatorTable()` now returns `OperatorTableI` which may break some code.
- Node now defines default implementations for `getName()`, `getValue()` making it easier to extract values without a cast.
- Node now defines methods `setHook()`, `getHook()` allowing annotation of nodes with key-value pairs.
- Unit tests converted to use JUnit 4.

### Functions

- New functions Switch, Case, Left, Right, Mid, Substring, LowerCase, UpperCase, Length, Trim.
- New base classes UnaryFunction, BinaryFunction, NaryFunction, and NaryBinaryFunction simplifying interface for defining user functions. For example, a `BinaryFunction` just needs to define an `Object eval(Object l, Object r)` method.
- New exception class IllegalParameterException sub-classing `EvaluationException` provides standardised error messages, for the common case of wrong arguments being passed to user functions.
- PostfixMathCommand defines convenience methods such as `int asInt()` to convert arguments to a specified type.
- New optional functions IsNull, IsNaN, IsInfinite, IsType for testing the value and type of arguments. These are not included by default.

### Examples

- Enhanced FunctionPlotter application allowing zooming and translation.
- New ParametrisedPlotter and PolarPlotter.
- New SpeedTest application for comparing different configurations.

## Version 3.2

General Changes:

- Added support for expression tree analysis using TreeAnalyser
- Fixed errors in the documentation of the default configuration
- Improved the operator table

Changes to the configurable parser:

- New StandardConfigurableParser class
- Parse error reporting with line and column numbers
- Added support for hexadecimal numbers (e.g. `0x1F`)
- Added support for bitwise operators (bitwise or: `a | b`, bit shifting `a << 2`) in BitwiseOperatorTable
- Added support for `a?b:c`, `x+=1`, `++x` syntax
- Added support for case-insensitive operators
- Added support for multiple expressions separated by semicolons
- Added support for multiple dimensional array access (`a[1][1]` accesses the first element of a two-dimensional array)
- Fixed issues with escape characters
- Fixed power and unary minus precedence to be consistent with the standard parser ("-3^2" should equal -9)

Known issues:

- `Jep.addVariable` does not notify the user when the specified value can not be set. This happens when a constant is already defined with the same name.

## Version 3.1

- Added serialization support
- Fixes bug prohibiting adding alphabetic operators to the configurable parser (such as AND)
- Added short circuit logical operator evaluation for && and || to speed up evaluation
- Added `avg`, `min`, and `max` functions
- Makes use of new Java 1.5 Math functions `log10`, `sinh`, `cosh`, `tanh`, and `hypot`
- Added StrictNaturalLogarithm which returns `NaN` for negative reals rather than complex.
- Fixed mistake in the Basic Usage section of the documentation

Known issues:

- The default settings for allowUndeclared, implicitMultiplication, and allowAssignment are true. The documentation falsely claims that the defaults are false.

## Version 3.0

- Added RealEvaluator for fast evaluation of expressions not containing strings, arrays or complex numbers
- Added BigDecComponents for high precision calculations using BigDecimal numbers
- New component architecture (pluggable parser, evaluator, and more)
- Added new configurable parser (allows alternate syntax)
- Added expression printing capabilities to the Jep class
- Added new functions: round, floor, ceil, lg (log base 2)
- Major package restructuring
- No longer available under the GPL license
- Changed error handling from hasError() function to exception throwing
- Switched from JavaCC 3.2 to JavaCC 4.0
- Switched compatibility from Java 1.2 to Java 1.5
- Switched from JUnit 3 to JUnit 4.1

Known issues:

- The default settings for allowUndeclared, implicitMultiplication, and allowAssignment are true. The documentation falsely claims that the defaults are false.