juce_Expression.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. #ifndef JUCE_EXPRESSION_H_INCLUDED
  22. #define JUCE_EXPRESSION_H_INCLUDED
  23. //==============================================================================
  24. /**
  25. A class for dynamically evaluating simple numeric expressions.
  26. This class can parse a simple C-style string expression involving floating point
  27. numbers, named symbols and functions. The basic arithmetic operations of +, -, *, /
  28. are supported, as well as parentheses, and any alphanumeric identifiers are
  29. assumed to be named symbols which will be resolved when the expression is
  30. evaluated.
  31. Expressions which use identifiers and functions require a subclass of
  32. Expression::Scope to be supplied when evaluating them, and this object
  33. is expected to be able to resolve the symbol names and perform the functions that
  34. are used.
  35. */
  36. class JUCE_API Expression
  37. {
  38. public:
  39. //==============================================================================
  40. /** Creates a simple expression with a value of 0. */
  41. Expression();
  42. /** Destructor. */
  43. ~Expression();
  44. /** Creates a simple expression with a specified constant value. */
  45. explicit Expression (double constant);
  46. /** Creates a copy of an expression. */
  47. Expression (const Expression&);
  48. /** Copies another expression. */
  49. Expression& operator= (const Expression&);
  50. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  51. Expression (Expression&&) noexcept;
  52. Expression& operator= (Expression&&) noexcept;
  53. #endif
  54. /** Creates an expression by parsing a string.
  55. If there's a syntax error in the string, this will throw a ParseError exception.
  56. @throws ParseError
  57. */
  58. explicit Expression (const String& stringToParse);
  59. /** Returns a string version of the expression. */
  60. String toString() const;
  61. /** Returns an expression which is an addition operation of two existing expressions. */
  62. Expression operator+ (const Expression&) const;
  63. /** Returns an expression which is a subtraction operation of two existing expressions. */
  64. Expression operator- (const Expression&) const;
  65. /** Returns an expression which is a multiplication operation of two existing expressions. */
  66. Expression operator* (const Expression&) const;
  67. /** Returns an expression which is a division operation of two existing expressions. */
  68. Expression operator/ (const Expression&) const;
  69. /** Returns an expression which performs a negation operation on an existing expression. */
  70. Expression operator-() const;
  71. /** Returns an Expression which is an identifier reference. */
  72. static Expression symbol (const String& symbol);
  73. /** Returns an Expression which is a function call. */
  74. static Expression function (const String& functionName, const Array<Expression>& parameters);
  75. /** Returns an Expression which parses a string from a character pointer, and updates the pointer
  76. to indicate where it finished.
  77. The pointer is incremented so that on return, it indicates the character that follows
  78. the end of the expression that was parsed.
  79. If there's a syntax error in the string, this will throw a ParseError exception.
  80. @throws ParseError
  81. */
  82. static Expression parse (String::CharPointerType& stringToParse);
  83. //==============================================================================
  84. /** When evaluating an Expression object, this class is used to resolve symbols and
  85. perform functions that the expression uses.
  86. */
  87. class JUCE_API Scope
  88. {
  89. public:
  90. Scope();
  91. virtual ~Scope();
  92. /** Returns some kind of globally unique ID that identifies this scope. */
  93. virtual String getScopeUID() const;
  94. /** Returns the value of a symbol.
  95. If the symbol is unknown, this can throw an Expression::EvaluationError exception.
  96. The member value is set to the part of the symbol that followed the dot, if there is
  97. one, e.g. for "foo.bar", symbol = "foo" and member = "bar".
  98. @throws Expression::EvaluationError
  99. */
  100. virtual Expression getSymbolValue (const String& symbol) const;
  101. /** Executes a named function.
  102. If the function name is unknown, this can throw an Expression::EvaluationError exception.
  103. @throws Expression::EvaluationError
  104. */
  105. virtual double evaluateFunction (const String& functionName,
  106. const double* parameters, int numParameters) const;
  107. /** Used as a callback by the Scope::visitRelativeScope() method.
  108. You should never create an instance of this class yourself, it's used by the
  109. expression evaluation code.
  110. */
  111. class Visitor
  112. {
  113. public:
  114. virtual ~Visitor() {}
  115. virtual void visit (const Scope&) = 0;
  116. };
  117. /** Creates a Scope object for a named scope, and then calls a visitor
  118. to do some kind of processing with this new scope.
  119. If the name is valid, this method must create a suitable (temporary) Scope
  120. object to represent it, and must call the Visitor::visit() method with this
  121. new scope.
  122. */
  123. virtual void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  124. };
  125. /** Evaluates this expression, without using a Scope.
  126. Without a Scope, no symbols can be used, and only basic functions such as sin, cos, tan,
  127. min, max are available.
  128. To find out about any errors during evaluation, use the other version of this method which
  129. takes a String parameter.
  130. */
  131. double evaluate() const;
  132. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  133. or functions that it uses.
  134. To find out about any errors during evaluation, use the other version of this method which
  135. takes a String parameter.
  136. */
  137. double evaluate (const Scope& scope) const;
  138. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  139. or functions that it uses.
  140. */
  141. double evaluate (const Scope& scope, String& evaluationError) const;
  142. /** Attempts to return an expression which is a copy of this one, but with a constant adjusted
  143. to make the expression resolve to a target value.
  144. E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return
  145. the expression "x + 3". Obviously some expressions can't be reversed in this way, in which
  146. case they might just be adjusted by adding a constant to the original expression.
  147. @throws Expression::EvaluationError
  148. */
  149. Expression adjustedToGiveNewResult (double targetValue, const Scope& scope) const;
  150. /** Represents a symbol that is used in an Expression. */
  151. struct Symbol
  152. {
  153. Symbol (const String& scopeUID, const String& symbolName);
  154. bool operator== (const Symbol&) const noexcept;
  155. bool operator!= (const Symbol&) const noexcept;
  156. String scopeUID; /**< The unique ID of the Scope that contains this symbol. */
  157. String symbolName; /**< The name of the symbol. */
  158. };
  159. /** Returns a copy of this expression in which all instances of a given symbol have been renamed. */
  160. Expression withRenamedSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope) const;
  161. /** Returns true if this expression makes use of the specified symbol.
  162. If a suitable scope is supplied, the search will dereference and recursively check
  163. all symbols, so that it can be determined whether this expression relies on the given
  164. symbol at any level in its evaluation. If the scope parameter is null, this just checks
  165. whether the expression contains any direct references to the symbol.
  166. @throws Expression::EvaluationError
  167. */
  168. bool referencesSymbol (const Symbol& symbol, const Scope& scope) const;
  169. /** Returns true if this expression contains any symbols. */
  170. bool usesAnySymbols() const;
  171. /** Returns a list of all symbols that may be needed to resolve this expression in the given scope. */
  172. void findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const;
  173. //==============================================================================
  174. /** An exception that can be thrown by Expression::parse(). */
  175. class ParseError : public std::exception
  176. {
  177. public:
  178. ParseError (const String& message);
  179. String description;
  180. };
  181. //==============================================================================
  182. /** Expression type.
  183. @see Expression::getType()
  184. */
  185. enum Type
  186. {
  187. constantType,
  188. functionType,
  189. operatorType,
  190. symbolType
  191. };
  192. /** Returns the type of this expression. */
  193. Type getType() const noexcept;
  194. /** If this expression is a symbol, function or operator, this returns its identifier. */
  195. String getSymbolOrFunction() const;
  196. /** Returns the number of inputs to this expression.
  197. @see getInput
  198. */
  199. int getNumInputs() const;
  200. /** Retrieves one of the inputs to this expression.
  201. @see getNumInputs
  202. */
  203. Expression getInput (int index) const;
  204. private:
  205. //==============================================================================
  206. class Term;
  207. struct Helpers;
  208. friend class Term;
  209. friend struct Helpers;
  210. friend struct ContainerDeletePolicy<Term>;
  211. friend class ReferenceCountedObjectPtr<Term>;
  212. ReferenceCountedObjectPtr<Term> term;
  213. explicit Expression (Term*);
  214. };
  215. #endif // JUCE_EXPRESSION_H_INCLUDED