The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

275 lines
11KB

  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_JUCEHEADER__
  22. #define __JUCE_EXPRESSION_JUCEHEADER__
  23. #include "../memory/juce_ReferenceCountedObject.h"
  24. #include "../containers/juce_Array.h"
  25. #include "../memory/juce_ScopedPointer.h"
  26. //==============================================================================
  27. /**
  28. A class for dynamically evaluating simple numeric expressions.
  29. This class can parse a simple C-style string expression involving floating point
  30. numbers, named symbols and functions. The basic arithmetic operations of +, -, *, /
  31. are supported, as well as parentheses, and any alphanumeric identifiers are
  32. assumed to be named symbols which will be resolved when the expression is
  33. evaluated.
  34. Expressions which use identifiers and functions require a subclass of
  35. Expression::Scope to be supplied when evaluating them, and this object
  36. is expected to be able to resolve the symbol names and perform the functions that
  37. are used.
  38. */
  39. class JUCE_API Expression
  40. {
  41. public:
  42. //==============================================================================
  43. /** Creates a simple expression with a value of 0. */
  44. Expression();
  45. /** Destructor. */
  46. ~Expression();
  47. /** Creates a simple expression with a specified constant value. */
  48. explicit Expression (double constant);
  49. /** Creates a copy of an expression. */
  50. Expression (const Expression& other);
  51. /** Copies another expression. */
  52. Expression& operator= (const Expression& other);
  53. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  54. Expression (Expression&& other) noexcept;
  55. Expression& operator= (Expression&& other) noexcept;
  56. #endif
  57. /** Creates an expression by parsing a string.
  58. If there's a syntax error in the string, this will throw a ParseError exception.
  59. @throws ParseError
  60. */
  61. explicit Expression (const String& stringToParse);
  62. /** Returns a string version of the expression. */
  63. String toString() const;
  64. /** Returns an expression which is an addtion operation of two existing expressions. */
  65. Expression operator+ (const Expression& other) const;
  66. /** Returns an expression which is a subtraction operation of two existing expressions. */
  67. Expression operator- (const Expression& other) const;
  68. /** Returns an expression which is a multiplication operation of two existing expressions. */
  69. Expression operator* (const Expression& other) const;
  70. /** Returns an expression which is a division operation of two existing expressions. */
  71. Expression operator/ (const Expression& other) const;
  72. /** Returns an expression which performs a negation operation on an existing expression. */
  73. Expression operator-() const;
  74. /** Returns an Expression which is an identifier reference. */
  75. static Expression symbol (const String& symbol);
  76. /** Returns an Expression which is a function call. */
  77. static Expression function (const String& functionName, const Array<Expression>& parameters);
  78. /** Returns an Expression which parses a string from a character pointer, and updates the pointer
  79. to indicate where it finished.
  80. The pointer is incremented so that on return, it indicates the character that follows
  81. the end of the expression that was parsed.
  82. If there's a syntax error in the string, this will throw a ParseError exception.
  83. @throws ParseError
  84. */
  85. static Expression parse (String::CharPointerType& stringToParse);
  86. //==============================================================================
  87. /** When evaluating an Expression object, this class is used to resolve symbols and
  88. perform functions that the expression uses.
  89. */
  90. class JUCE_API Scope
  91. {
  92. public:
  93. Scope();
  94. virtual ~Scope();
  95. /** Returns some kind of globally unique ID that identifies this scope. */
  96. virtual String getScopeUID() const;
  97. /** Returns the value of a symbol.
  98. If the symbol is unknown, this can throw an Expression::EvaluationError exception.
  99. The member value is set to the part of the symbol that followed the dot, if there is
  100. one, e.g. for "foo.bar", symbol = "foo" and member = "bar".
  101. @throws Expression::EvaluationError
  102. */
  103. virtual Expression getSymbolValue (const String& symbol) const;
  104. /** Executes a named function.
  105. If the function name is unknown, this can throw an Expression::EvaluationError exception.
  106. @throws Expression::EvaluationError
  107. */
  108. virtual double evaluateFunction (const String& functionName,
  109. const double* parameters, int numParameters) const;
  110. /** Used as a callback by the Scope::visitRelativeScope() method.
  111. You should never create an instance of this class yourself, it's used by the
  112. expression evaluation code.
  113. */
  114. class Visitor
  115. {
  116. public:
  117. virtual ~Visitor() {}
  118. virtual void visit (const Scope&) = 0;
  119. };
  120. /** Creates a Scope object for a named scope, and then calls a visitor
  121. to do some kind of processing with this new scope.
  122. If the name is valid, this method must create a suitable (temporary) Scope
  123. object to represent it, and must call the Visitor::visit() method with this
  124. new scope.
  125. */
  126. virtual void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  127. };
  128. /** Evaluates this expression, without using a Scope.
  129. Without a Scope, no symbols can be used, and only basic functions such as sin, cos, tan,
  130. min, max are available.
  131. To find out about any errors during evaluation, use the other version of this method which
  132. takes a String parameter.
  133. */
  134. double evaluate() const;
  135. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  136. or functions that it uses.
  137. To find out about any errors during evaluation, use the other version of this method which
  138. takes a String parameter.
  139. */
  140. double evaluate (const Scope& scope) const;
  141. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  142. or functions that it uses.
  143. */
  144. double evaluate (const Scope& scope, String& evaluationError) const;
  145. /** Attempts to return an expression which is a copy of this one, but with a constant adjusted
  146. to make the expression resolve to a target value.
  147. E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return
  148. the expression "x + 3". Obviously some expressions can't be reversed in this way, in which
  149. case they might just be adjusted by adding a constant to the original expression.
  150. @throws Expression::EvaluationError
  151. */
  152. Expression adjustedToGiveNewResult (double targetValue, const Scope& scope) const;
  153. /** Represents a symbol that is used in an Expression. */
  154. struct Symbol
  155. {
  156. Symbol (const String& scopeUID, const String& symbolName);
  157. bool operator== (const Symbol&) const noexcept;
  158. bool operator!= (const Symbol&) const noexcept;
  159. String scopeUID; /**< The unique ID of the Scope that contains this symbol. */
  160. String symbolName; /**< The name of the symbol. */
  161. };
  162. /** Returns a copy of this expression in which all instances of a given symbol have been renamed. */
  163. Expression withRenamedSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope) const;
  164. /** Returns true if this expression makes use of the specified symbol.
  165. If a suitable scope is supplied, the search will dereference and recursively check
  166. all symbols, so that it can be determined whether this expression relies on the given
  167. symbol at any level in its evaluation. If the scope parameter is null, this just checks
  168. whether the expression contains any direct references to the symbol.
  169. @throws Expression::EvaluationError
  170. */
  171. bool referencesSymbol (const Symbol& symbol, const Scope& scope) const;
  172. /** Returns true if this expression contains any symbols. */
  173. bool usesAnySymbols() const;
  174. /** Returns a list of all symbols that may be needed to resolve this expression in the given scope. */
  175. void findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const;
  176. //==============================================================================
  177. /** An exception that can be thrown by Expression::parse(). */
  178. class ParseError : public std::exception
  179. {
  180. public:
  181. ParseError (const String& message);
  182. String description;
  183. };
  184. //==============================================================================
  185. /** Expression type.
  186. @see Expression::getType()
  187. */
  188. enum Type
  189. {
  190. constantType,
  191. functionType,
  192. operatorType,
  193. symbolType
  194. };
  195. /** Returns the type of this expression. */
  196. Type getType() const noexcept;
  197. /** If this expression is a symbol, function or operator, this returns its identifier. */
  198. String getSymbolOrFunction() const;
  199. /** Returns the number of inputs to this expression.
  200. @see getInput
  201. */
  202. int getNumInputs() const;
  203. /** Retrieves one of the inputs to this expression.
  204. @see getNumInputs
  205. */
  206. Expression getInput (int index) const;
  207. private:
  208. //==============================================================================
  209. class Term;
  210. struct Helpers;
  211. friend class Term;
  212. friend struct Helpers;
  213. friend class ScopedPointer<Term>;
  214. friend class ReferenceCountedObjectPtr<Term>;
  215. ReferenceCountedObjectPtr<Term> term;
  216. explicit Expression (Term*);
  217. };
  218. #endif // __JUCE_EXPRESSION_JUCEHEADER__