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.

1180 lines
39KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. class Expression::Term : public SingleThreadedReferenceCountedObject
  19. {
  20. public:
  21. Term() {}
  22. virtual ~Term() {}
  23. virtual Type getType() const noexcept = 0;
  24. virtual Term* clone() const = 0;
  25. virtual ReferenceCountedObjectPtr<Term> resolve (const Scope&, int recursionDepth) = 0;
  26. virtual String toString() const = 0;
  27. virtual double toDouble() const { return 0; }
  28. virtual int getInputIndexFor (const Term*) const { return -1; }
  29. virtual int getOperatorPrecedence() const { return 0; }
  30. virtual int getNumInputs() const { return 0; }
  31. virtual Term* getInput (int) const { return nullptr; }
  32. virtual ReferenceCountedObjectPtr<Term> negated();
  33. virtual ReferenceCountedObjectPtr<Term> createTermToEvaluateInput (const Scope&, const Term* /*inputTerm*/,
  34. double /*overallTarget*/, Term* /*topLevelTerm*/) const
  35. {
  36. jassertfalse;
  37. return ReferenceCountedObjectPtr<Term>();
  38. }
  39. virtual String getName() const
  40. {
  41. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  42. return String::empty;
  43. }
  44. virtual void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  45. {
  46. for (int i = getNumInputs(); --i >= 0;)
  47. getInput (i)->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  48. }
  49. class SymbolVisitor
  50. {
  51. public:
  52. virtual ~SymbolVisitor() {}
  53. virtual void useSymbol (const Symbol&) = 0;
  54. };
  55. virtual void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  56. {
  57. for (int i = getNumInputs(); --i >= 0;)
  58. getInput(i)->visitAllSymbols (visitor, scope, recursionDepth);
  59. }
  60. private:
  61. JUCE_DECLARE_NON_COPYABLE (Term)
  62. };
  63. //==============================================================================
  64. struct Expression::Helpers
  65. {
  66. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  67. static void checkRecursionDepth (const int depth)
  68. {
  69. if (depth > 256)
  70. throw EvaluationError ("Recursive symbol references");
  71. }
  72. friend class Expression::Term;
  73. //==============================================================================
  74. /** An exception that can be thrown by Expression::evaluate(). */
  75. class EvaluationError : public std::exception
  76. {
  77. public:
  78. EvaluationError (const String& desc) : description (desc)
  79. {
  80. DBG ("Expression::EvaluationError: " + description);
  81. }
  82. String description;
  83. };
  84. //==============================================================================
  85. class Constant : public Term
  86. {
  87. public:
  88. Constant (const double val, const bool resolutionTarget)
  89. : value (val), isResolutionTarget (resolutionTarget) {}
  90. Type getType() const noexcept { return constantType; }
  91. Term* clone() const { return new Constant (value, isResolutionTarget); }
  92. TermPtr resolve (const Scope&, int) { return this; }
  93. double toDouble() const { return value; }
  94. TermPtr negated() { return new Constant (-value, isResolutionTarget); }
  95. String toString() const
  96. {
  97. String s (value);
  98. if (isResolutionTarget)
  99. s = "@" + s;
  100. return s;
  101. }
  102. double value;
  103. bool isResolutionTarget;
  104. };
  105. //==============================================================================
  106. class BinaryTerm : public Term
  107. {
  108. public:
  109. BinaryTerm (Term* const l, Term* const r) : left (l), right (r)
  110. {
  111. jassert (l != nullptr && r != nullptr);
  112. }
  113. int getInputIndexFor (const Term* possibleInput) const
  114. {
  115. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  116. }
  117. Type getType() const noexcept { return operatorType; }
  118. int getNumInputs() const { return 2; }
  119. Term* getInput (int index) const { return index == 0 ? left.get() : (index == 1 ? right.get() : 0); }
  120. virtual double performFunction (double left, double right) const = 0;
  121. virtual void writeOperator (String& dest) const = 0;
  122. TermPtr resolve (const Scope& scope, int recursionDepth)
  123. {
  124. return new Constant (performFunction (left ->resolve (scope, recursionDepth)->toDouble(),
  125. right->resolve (scope, recursionDepth)->toDouble()), false);
  126. }
  127. String toString() const
  128. {
  129. String s;
  130. const int ourPrecendence = getOperatorPrecedence();
  131. if (left->getOperatorPrecedence() > ourPrecendence)
  132. s << '(' << left->toString() << ')';
  133. else
  134. s = left->toString();
  135. writeOperator (s);
  136. if (right->getOperatorPrecedence() >= ourPrecendence)
  137. s << '(' << right->toString() << ')';
  138. else
  139. s << right->toString();
  140. return s;
  141. }
  142. protected:
  143. const TermPtr left, right;
  144. TermPtr createDestinationTerm (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  145. {
  146. jassert (input == left || input == right);
  147. if (input != left && input != right)
  148. return TermPtr();
  149. const Term* const dest = findDestinationFor (topLevelTerm, this);
  150. if (dest == nullptr)
  151. return new Constant (overallTarget, false);
  152. return dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm);
  153. }
  154. };
  155. //==============================================================================
  156. class SymbolTerm : public Term
  157. {
  158. public:
  159. explicit SymbolTerm (const String& sym) : symbol (sym) {}
  160. TermPtr resolve (const Scope& scope, int recursionDepth)
  161. {
  162. checkRecursionDepth (recursionDepth);
  163. return scope.getSymbolValue (symbol).term->resolve (scope, recursionDepth + 1);
  164. }
  165. Type getType() const noexcept { return symbolType; }
  166. Term* clone() const { return new SymbolTerm (symbol); }
  167. String toString() const { return symbol; }
  168. String getName() const { return symbol; }
  169. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  170. {
  171. checkRecursionDepth (recursionDepth);
  172. visitor.useSymbol (Symbol (scope.getScopeUID(), symbol));
  173. scope.getSymbolValue (symbol).term->visitAllSymbols (visitor, scope, recursionDepth + 1);
  174. }
  175. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int /*recursionDepth*/)
  176. {
  177. if (oldSymbol.symbolName == symbol && scope.getScopeUID() == oldSymbol.scopeUID)
  178. symbol = newName;
  179. }
  180. String symbol;
  181. };
  182. //==============================================================================
  183. class Function : public Term
  184. {
  185. public:
  186. explicit Function (const String& name) : functionName (name) {}
  187. Function (const String& name, const Array<Expression>& params)
  188. : functionName (name), parameters (params)
  189. {}
  190. Type getType() const noexcept { return functionType; }
  191. Term* clone() const { return new Function (functionName, parameters); }
  192. int getNumInputs() const { return parameters.size(); }
  193. Term* getInput (int i) const { return parameters.getReference(i).term; }
  194. String getName() const { return functionName; }
  195. TermPtr resolve (const Scope& scope, int recursionDepth)
  196. {
  197. checkRecursionDepth (recursionDepth);
  198. double result = 0;
  199. const int numParams = parameters.size();
  200. if (numParams > 0)
  201. {
  202. HeapBlock<double> params ((size_t) numParams);
  203. for (int i = 0; i < numParams; ++i)
  204. params[i] = parameters.getReference(i).term->resolve (scope, recursionDepth + 1)->toDouble();
  205. result = scope.evaluateFunction (functionName, params, numParams);
  206. }
  207. else
  208. {
  209. result = scope.evaluateFunction (functionName, nullptr, 0);
  210. }
  211. return new Constant (result, false);
  212. }
  213. int getInputIndexFor (const Term* possibleInput) const
  214. {
  215. for (int i = 0; i < parameters.size(); ++i)
  216. if (parameters.getReference(i).term == possibleInput)
  217. return i;
  218. return -1;
  219. }
  220. String toString() const
  221. {
  222. if (parameters.size() == 0)
  223. return functionName + "()";
  224. String s (functionName + " (");
  225. for (int i = 0; i < parameters.size(); ++i)
  226. {
  227. s << parameters.getReference(i).term->toString();
  228. if (i < parameters.size() - 1)
  229. s << ", ";
  230. }
  231. s << ')';
  232. return s;
  233. }
  234. const String functionName;
  235. Array<Expression> parameters;
  236. };
  237. //==============================================================================
  238. class DotOperator : public BinaryTerm
  239. {
  240. public:
  241. DotOperator (SymbolTerm* const l, Term* const r) : BinaryTerm (l, r) {}
  242. TermPtr resolve (const Scope& scope, int recursionDepth)
  243. {
  244. checkRecursionDepth (recursionDepth);
  245. EvaluationVisitor visitor (right, recursionDepth + 1);
  246. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  247. return visitor.output;
  248. }
  249. Term* clone() const { return new DotOperator (getSymbol(), right); }
  250. String getName() const { return "."; }
  251. int getOperatorPrecedence() const { return 1; }
  252. void writeOperator (String& dest) const { dest << '.'; }
  253. double performFunction (double, double) const { return 0.0; }
  254. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  255. {
  256. checkRecursionDepth (recursionDepth);
  257. visitor.useSymbol (Symbol (scope.getScopeUID(), getSymbol()->symbol));
  258. SymbolVisitingVisitor v (right, visitor, recursionDepth + 1);
  259. try
  260. {
  261. scope.visitRelativeScope (getSymbol()->symbol, v);
  262. }
  263. catch (...) {}
  264. }
  265. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  266. {
  267. checkRecursionDepth (recursionDepth);
  268. getSymbol()->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  269. SymbolRenamingVisitor visitor (right, oldSymbol, newName, recursionDepth + 1);
  270. try
  271. {
  272. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  273. }
  274. catch (...) {}
  275. }
  276. private:
  277. //==============================================================================
  278. class EvaluationVisitor : public Scope::Visitor
  279. {
  280. public:
  281. EvaluationVisitor (const TermPtr& t, const int recursion)
  282. : input (t), output (t), recursionCount (recursion) {}
  283. void visit (const Scope& scope) { output = input->resolve (scope, recursionCount); }
  284. const TermPtr input;
  285. TermPtr output;
  286. const int recursionCount;
  287. private:
  288. JUCE_DECLARE_NON_COPYABLE (EvaluationVisitor)
  289. };
  290. class SymbolVisitingVisitor : public Scope::Visitor
  291. {
  292. public:
  293. SymbolVisitingVisitor (const TermPtr& t, SymbolVisitor& v, const int recursion)
  294. : input (t), visitor (v), recursionCount (recursion) {}
  295. void visit (const Scope& scope) { input->visitAllSymbols (visitor, scope, recursionCount); }
  296. private:
  297. const TermPtr input;
  298. SymbolVisitor& visitor;
  299. const int recursionCount;
  300. JUCE_DECLARE_NON_COPYABLE (SymbolVisitingVisitor)
  301. };
  302. class SymbolRenamingVisitor : public Scope::Visitor
  303. {
  304. public:
  305. SymbolRenamingVisitor (const TermPtr& t, const Expression::Symbol& symbol_, const String& newName_, const int recursionCount_)
  306. : input (t), symbol (symbol_), newName (newName_), recursionCount (recursionCount_) {}
  307. void visit (const Scope& scope) { input->renameSymbol (symbol, newName, scope, recursionCount); }
  308. private:
  309. const TermPtr input;
  310. const Symbol& symbol;
  311. const String newName;
  312. const int recursionCount;
  313. JUCE_DECLARE_NON_COPYABLE (SymbolRenamingVisitor)
  314. };
  315. SymbolTerm* getSymbol() const { return static_cast <SymbolTerm*> (left.get()); }
  316. JUCE_DECLARE_NON_COPYABLE (DotOperator)
  317. };
  318. //==============================================================================
  319. class Negate : public Term
  320. {
  321. public:
  322. explicit Negate (const TermPtr& t) : input (t)
  323. {
  324. jassert (t != nullptr);
  325. }
  326. Type getType() const noexcept { return operatorType; }
  327. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  328. int getNumInputs() const { return 1; }
  329. Term* getInput (int index) const { return index == 0 ? input.get() : nullptr; }
  330. Term* clone() const { return new Negate (input->clone()); }
  331. TermPtr resolve (const Scope& scope, int recursionDepth)
  332. {
  333. return new Constant (-input->resolve (scope, recursionDepth)->toDouble(), false);
  334. }
  335. String getName() const { return "-"; }
  336. TermPtr negated() { return input; }
  337. TermPtr createTermToEvaluateInput (const Scope& scope, const Term* t, double overallTarget, Term* topLevelTerm) const
  338. {
  339. (void) t;
  340. jassert (t == input);
  341. const Term* const dest = findDestinationFor (topLevelTerm, this);
  342. return new Negate (dest == nullptr ? new Constant (overallTarget, false)
  343. : dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm));
  344. }
  345. String toString() const
  346. {
  347. if (input->getOperatorPrecedence() > 0)
  348. return "-(" + input->toString() + ")";
  349. return "-" + input->toString();
  350. }
  351. private:
  352. const TermPtr input;
  353. };
  354. //==============================================================================
  355. class Add : public BinaryTerm
  356. {
  357. public:
  358. Add (Term* const l, Term* const r) : BinaryTerm (l, r) {}
  359. Term* clone() const { return new Add (left->clone(), right->clone()); }
  360. double performFunction (double lhs, double rhs) const { return lhs + rhs; }
  361. int getOperatorPrecedence() const { return 3; }
  362. String getName() const { return "+"; }
  363. void writeOperator (String& dest) const { dest << " + "; }
  364. TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  365. {
  366. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  367. if (newDest == nullptr)
  368. return TermPtr();
  369. return new Subtract (newDest, (input == left ? right : left)->clone());
  370. }
  371. private:
  372. JUCE_DECLARE_NON_COPYABLE (Add)
  373. };
  374. //==============================================================================
  375. class Subtract : public BinaryTerm
  376. {
  377. public:
  378. Subtract (Term* const l, Term* const r) : BinaryTerm (l, r) {}
  379. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  380. double performFunction (double lhs, double rhs) const { return lhs - rhs; }
  381. int getOperatorPrecedence() const { return 3; }
  382. String getName() const { return "-"; }
  383. void writeOperator (String& dest) const { dest << " - "; }
  384. TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  385. {
  386. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  387. if (newDest == nullptr)
  388. return TermPtr();
  389. if (input == left)
  390. return new Add (newDest, right->clone());
  391. return new Subtract (left->clone(), newDest);
  392. }
  393. private:
  394. JUCE_DECLARE_NON_COPYABLE (Subtract)
  395. };
  396. //==============================================================================
  397. class Multiply : public BinaryTerm
  398. {
  399. public:
  400. Multiply (Term* const l, Term* const r) : BinaryTerm (l, r) {}
  401. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  402. double performFunction (double lhs, double rhs) const { return lhs * rhs; }
  403. String getName() const { return "*"; }
  404. void writeOperator (String& dest) const { dest << " * "; }
  405. int getOperatorPrecedence() const { return 2; }
  406. TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  407. {
  408. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  409. if (newDest == nullptr)
  410. return TermPtr();
  411. return new Divide (newDest, (input == left ? right : left)->clone());
  412. }
  413. private:
  414. JUCE_DECLARE_NON_COPYABLE (Multiply)
  415. };
  416. //==============================================================================
  417. class Divide : public BinaryTerm
  418. {
  419. public:
  420. Divide (Term* const l, Term* const r) : BinaryTerm (l, r) {}
  421. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  422. double performFunction (double lhs, double rhs) const { return lhs / rhs; }
  423. String getName() const { return "/"; }
  424. void writeOperator (String& dest) const { dest << " / "; }
  425. int getOperatorPrecedence() const { return 2; }
  426. TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  427. {
  428. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  429. if (newDest == nullptr)
  430. return TermPtr();
  431. if (input == left)
  432. return new Multiply (newDest, right->clone());
  433. return new Divide (left->clone(), newDest);
  434. }
  435. private:
  436. JUCE_DECLARE_NON_COPYABLE (Divide)
  437. };
  438. //==============================================================================
  439. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  440. {
  441. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  442. if (inputIndex >= 0)
  443. return topLevel;
  444. for (int i = topLevel->getNumInputs(); --i >= 0;)
  445. {
  446. Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm);
  447. if (t != nullptr)
  448. return t;
  449. }
  450. return nullptr;
  451. }
  452. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  453. {
  454. jassert (term != nullptr);
  455. if (term->getType() == constantType)
  456. {
  457. Constant* const c = static_cast<Constant*> (term);
  458. if (c->isResolutionTarget || ! mustBeFlagged)
  459. return c;
  460. }
  461. if (term->getType() == functionType)
  462. return nullptr;
  463. const int numIns = term->getNumInputs();
  464. for (int i = 0; i < numIns; ++i)
  465. {
  466. Term* const input = term->getInput (i);
  467. if (input->getType() == constantType)
  468. {
  469. Constant* const c = static_cast<Constant*> (input);
  470. if (c->isResolutionTarget || ! mustBeFlagged)
  471. return c;
  472. }
  473. }
  474. for (int i = 0; i < numIns; ++i)
  475. {
  476. Constant* const c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  477. if (c != nullptr)
  478. return c;
  479. }
  480. return nullptr;
  481. }
  482. static bool containsAnySymbols (const Term* const t)
  483. {
  484. if (t->getType() == Expression::symbolType)
  485. return true;
  486. for (int i = t->getNumInputs(); --i >= 0;)
  487. if (containsAnySymbols (t->getInput (i)))
  488. return true;
  489. return false;
  490. }
  491. //==============================================================================
  492. class SymbolCheckVisitor : public Term::SymbolVisitor
  493. {
  494. public:
  495. SymbolCheckVisitor (const Symbol& symbol_) : wasFound (false), symbol (symbol_) {}
  496. void useSymbol (const Symbol& s) { wasFound = wasFound || s == symbol; }
  497. bool wasFound;
  498. private:
  499. const Symbol& symbol;
  500. JUCE_DECLARE_NON_COPYABLE (SymbolCheckVisitor)
  501. };
  502. //==============================================================================
  503. class SymbolListVisitor : public Term::SymbolVisitor
  504. {
  505. public:
  506. SymbolListVisitor (Array<Symbol>& list_) : list (list_) {}
  507. void useSymbol (const Symbol& s) { list.addIfNotAlreadyThere (s); }
  508. private:
  509. Array<Symbol>& list;
  510. JUCE_DECLARE_NON_COPYABLE (SymbolListVisitor)
  511. };
  512. //==============================================================================
  513. class Parser
  514. {
  515. public:
  516. //==============================================================================
  517. Parser (String::CharPointerType& stringToParse)
  518. : text (stringToParse)
  519. {
  520. }
  521. TermPtr readUpToComma()
  522. {
  523. if (text.isEmpty())
  524. return new Constant (0.0, false);
  525. const TermPtr e (readExpression());
  526. if (e == nullptr || ((! readOperator (",")) && ! text.isEmpty()))
  527. throw ParseError ("Syntax error: \"" + String (text) + "\"");
  528. return e;
  529. }
  530. private:
  531. String::CharPointerType& text;
  532. //==============================================================================
  533. static inline bool isDecimalDigit (const juce_wchar c) noexcept
  534. {
  535. return c >= '0' && c <= '9';
  536. }
  537. bool readChar (const juce_wchar required) noexcept
  538. {
  539. if (*text == required)
  540. {
  541. ++text;
  542. return true;
  543. }
  544. return false;
  545. }
  546. bool readOperator (const char* ops, char* const opType = nullptr) noexcept
  547. {
  548. text = text.findEndOfWhitespace();
  549. while (*ops != 0)
  550. {
  551. if (readChar ((juce_wchar) (uint8) *ops))
  552. {
  553. if (opType != nullptr)
  554. *opType = *ops;
  555. return true;
  556. }
  557. ++ops;
  558. }
  559. return false;
  560. }
  561. bool readIdentifier (String& identifier) noexcept
  562. {
  563. text = text.findEndOfWhitespace();
  564. String::CharPointerType t (text);
  565. int numChars = 0;
  566. if (t.isLetter() || *t == '_')
  567. {
  568. ++t;
  569. ++numChars;
  570. while (t.isLetterOrDigit() || *t == '_')
  571. {
  572. ++t;
  573. ++numChars;
  574. }
  575. }
  576. if (numChars > 0)
  577. {
  578. identifier = String (text, (size_t) numChars);
  579. text = t;
  580. return true;
  581. }
  582. return false;
  583. }
  584. Term* readNumber() noexcept
  585. {
  586. text = text.findEndOfWhitespace();
  587. String::CharPointerType t (text);
  588. const bool isResolutionTarget = (*t == '@');
  589. if (isResolutionTarget)
  590. {
  591. ++t;
  592. t = t.findEndOfWhitespace();
  593. text = t;
  594. }
  595. if (*t == '-')
  596. {
  597. ++t;
  598. t = t.findEndOfWhitespace();
  599. }
  600. if (isDecimalDigit (*t) || (*t == '.' && isDecimalDigit (t[1])))
  601. return new Constant (CharacterFunctions::readDoubleValue (text), isResolutionTarget);
  602. return nullptr;
  603. }
  604. TermPtr readExpression()
  605. {
  606. TermPtr lhs (readMultiplyOrDivideExpression());
  607. char opType;
  608. while (lhs != nullptr && readOperator ("+-", &opType))
  609. {
  610. TermPtr rhs (readMultiplyOrDivideExpression());
  611. if (rhs == nullptr)
  612. throw ParseError ("Expected expression after \"" + String::charToString ((juce_wchar) (uint8) opType) + "\"");
  613. if (opType == '+')
  614. lhs = new Add (lhs, rhs);
  615. else
  616. lhs = new Subtract (lhs, rhs);
  617. }
  618. return lhs;
  619. }
  620. TermPtr readMultiplyOrDivideExpression()
  621. {
  622. TermPtr lhs (readUnaryExpression());
  623. char opType;
  624. while (lhs != nullptr && readOperator ("*/", &opType))
  625. {
  626. TermPtr rhs (readUnaryExpression());
  627. if (rhs == nullptr)
  628. throw ParseError ("Expected expression after \"" + String::charToString ((juce_wchar) (uint8) opType) + "\"");
  629. if (opType == '*')
  630. lhs = new Multiply (lhs, rhs);
  631. else
  632. lhs = new Divide (lhs, rhs);
  633. }
  634. return lhs;
  635. }
  636. TermPtr readUnaryExpression()
  637. {
  638. char opType;
  639. if (readOperator ("+-", &opType))
  640. {
  641. TermPtr e (readUnaryExpression());
  642. if (e == nullptr)
  643. throw ParseError ("Expected expression after \"" + String::charToString ((juce_wchar) (uint8) opType) + "\"");
  644. if (opType == '-')
  645. e = e->negated();
  646. return e;
  647. }
  648. return readPrimaryExpression();
  649. }
  650. TermPtr readPrimaryExpression()
  651. {
  652. TermPtr e (readParenthesisedExpression());
  653. if (e != nullptr)
  654. return e;
  655. e = readNumber();
  656. if (e != nullptr)
  657. return e;
  658. return readSymbolOrFunction();
  659. }
  660. TermPtr readSymbolOrFunction()
  661. {
  662. String identifier;
  663. if (readIdentifier (identifier))
  664. {
  665. if (readOperator ("(")) // method call...
  666. {
  667. Function* const f = new Function (identifier);
  668. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  669. TermPtr param (readExpression());
  670. if (param == nullptr)
  671. {
  672. if (readOperator (")"))
  673. return func.release();
  674. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  675. }
  676. f->parameters.add (Expression (param));
  677. while (readOperator (","))
  678. {
  679. param = readExpression();
  680. if (param == nullptr)
  681. throw ParseError ("Expected expression after \",\"");
  682. f->parameters.add (Expression (param));
  683. }
  684. if (readOperator (")"))
  685. return func.release();
  686. throw ParseError ("Expected \")\"");
  687. }
  688. if (readOperator ("."))
  689. {
  690. TermPtr rhs (readSymbolOrFunction());
  691. if (rhs == nullptr)
  692. throw ParseError ("Expected symbol or function after \".\"");
  693. if (identifier == "this")
  694. return rhs;
  695. return new DotOperator (new SymbolTerm (identifier), rhs);
  696. }
  697. // just a symbol..
  698. jassert (identifier.trim() == identifier);
  699. return new SymbolTerm (identifier);
  700. }
  701. return TermPtr();
  702. }
  703. TermPtr readParenthesisedExpression()
  704. {
  705. if (! readOperator ("("))
  706. return TermPtr();
  707. const TermPtr e (readExpression());
  708. if (e == nullptr || ! readOperator (")"))
  709. return TermPtr();
  710. return e;
  711. }
  712. JUCE_DECLARE_NON_COPYABLE (Parser)
  713. };
  714. };
  715. //==============================================================================
  716. Expression::Expression()
  717. : term (new Expression::Helpers::Constant (0, false))
  718. {
  719. }
  720. Expression::~Expression()
  721. {
  722. }
  723. Expression::Expression (Term* const term_)
  724. : term (term_)
  725. {
  726. jassert (term != nullptr);
  727. }
  728. Expression::Expression (const double constant)
  729. : term (new Expression::Helpers::Constant (constant, false))
  730. {
  731. }
  732. Expression::Expression (const Expression& other)
  733. : term (other.term)
  734. {
  735. }
  736. Expression& Expression::operator= (const Expression& other)
  737. {
  738. term = other.term;
  739. return *this;
  740. }
  741. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  742. Expression::Expression (Expression&& other) noexcept
  743. : term (static_cast <ReferenceCountedObjectPtr<Term>&&> (other.term))
  744. {
  745. }
  746. Expression& Expression::operator= (Expression&& other) noexcept
  747. {
  748. term = static_cast <ReferenceCountedObjectPtr<Term>&&> (other.term);
  749. return *this;
  750. }
  751. #endif
  752. Expression::Expression (const String& stringToParse)
  753. {
  754. String::CharPointerType text (stringToParse.getCharPointer());
  755. Helpers::Parser parser (text);
  756. term = parser.readUpToComma();
  757. }
  758. Expression Expression::parse (String::CharPointerType& stringToParse)
  759. {
  760. Helpers::Parser parser (stringToParse);
  761. return Expression (parser.readUpToComma());
  762. }
  763. double Expression::evaluate() const
  764. {
  765. return evaluate (Expression::Scope());
  766. }
  767. double Expression::evaluate (const Expression::Scope& scope) const
  768. {
  769. try
  770. {
  771. return term->resolve (scope, 0)->toDouble();
  772. }
  773. catch (Helpers::EvaluationError&)
  774. {}
  775. return 0;
  776. }
  777. double Expression::evaluate (const Scope& scope, String& evaluationError) const
  778. {
  779. try
  780. {
  781. return term->resolve (scope, 0)->toDouble();
  782. }
  783. catch (Helpers::EvaluationError& e)
  784. {
  785. evaluationError = e.description;
  786. }
  787. return 0;
  788. }
  789. Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  790. Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  791. Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  792. Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  793. Expression Expression::operator-() const { return Expression (term->negated()); }
  794. Expression Expression::symbol (const String& symbol) { return Expression (new Helpers::SymbolTerm (symbol)); }
  795. Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  796. {
  797. return Expression (new Helpers::Function (functionName, parameters));
  798. }
  799. Expression Expression::adjustedToGiveNewResult (const double targetValue, const Expression::Scope& scope) const
  800. {
  801. ScopedPointer<Term> newTerm (term->clone());
  802. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  803. if (termToAdjust == nullptr)
  804. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  805. if (termToAdjust == nullptr)
  806. {
  807. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  808. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  809. }
  810. jassert (termToAdjust != nullptr);
  811. const Term* const parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  812. if (parent == nullptr)
  813. {
  814. termToAdjust->value = targetValue;
  815. }
  816. else
  817. {
  818. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (scope, termToAdjust, targetValue, newTerm));
  819. if (reverseTerm == nullptr)
  820. return Expression (targetValue);
  821. termToAdjust->value = reverseTerm->resolve (scope, 0)->toDouble();
  822. }
  823. return Expression (newTerm.release());
  824. }
  825. Expression Expression::withRenamedSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Scope& scope) const
  826. {
  827. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  828. if (oldSymbol.symbolName == newName)
  829. return *this;
  830. Expression e (term->clone());
  831. e.term->renameSymbol (oldSymbol, newName, scope, 0);
  832. return e;
  833. }
  834. bool Expression::referencesSymbol (const Expression::Symbol& symbolToCheck, const Scope& scope) const
  835. {
  836. Helpers::SymbolCheckVisitor visitor (symbolToCheck);
  837. try
  838. {
  839. term->visitAllSymbols (visitor, scope, 0);
  840. }
  841. catch (Helpers::EvaluationError&)
  842. {}
  843. return visitor.wasFound;
  844. }
  845. void Expression::findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const
  846. {
  847. try
  848. {
  849. Helpers::SymbolListVisitor visitor (results);
  850. term->visitAllSymbols (visitor, scope, 0);
  851. }
  852. catch (Helpers::EvaluationError&)
  853. {}
  854. }
  855. String Expression::toString() const { return term->toString(); }
  856. bool Expression::usesAnySymbols() const { return Helpers::containsAnySymbols (term); }
  857. Expression::Type Expression::getType() const noexcept { return term->getType(); }
  858. String Expression::getSymbolOrFunction() const { return term->getName(); }
  859. int Expression::getNumInputs() const { return term->getNumInputs(); }
  860. Expression Expression::getInput (int index) const { return Expression (term->getInput (index)); }
  861. //==============================================================================
  862. ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  863. {
  864. return new Helpers::Negate (this);
  865. }
  866. //==============================================================================
  867. Expression::ParseError::ParseError (const String& message)
  868. : description (message)
  869. {
  870. DBG ("Expression::ParseError: " + message);
  871. }
  872. //==============================================================================
  873. Expression::Symbol::Symbol (const String& scopeUID_, const String& symbolName_)
  874. : scopeUID (scopeUID_), symbolName (symbolName_)
  875. {
  876. }
  877. bool Expression::Symbol::operator== (const Symbol& other) const noexcept
  878. {
  879. return symbolName == other.symbolName && scopeUID == other.scopeUID;
  880. }
  881. bool Expression::Symbol::operator!= (const Symbol& other) const noexcept
  882. {
  883. return ! operator== (other);
  884. }
  885. //==============================================================================
  886. Expression::Scope::Scope() {}
  887. Expression::Scope::~Scope() {}
  888. Expression Expression::Scope::getSymbolValue (const String& symbol) const
  889. {
  890. throw Helpers::EvaluationError ("Unknown symbol: " + symbol);
  891. }
  892. double Expression::Scope::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  893. {
  894. if (numParams > 0)
  895. {
  896. if (functionName == "min")
  897. {
  898. double v = parameters[0];
  899. for (int i = 1; i < numParams; ++i)
  900. v = jmin (v, parameters[i]);
  901. return v;
  902. }
  903. if (functionName == "max")
  904. {
  905. double v = parameters[0];
  906. for (int i = 1; i < numParams; ++i)
  907. v = jmax (v, parameters[i]);
  908. return v;
  909. }
  910. if (numParams == 1)
  911. {
  912. if (functionName == "sin") return sin (parameters[0]);
  913. if (functionName == "cos") return cos (parameters[0]);
  914. if (functionName == "tan") return tan (parameters[0]);
  915. if (functionName == "abs") return std::abs (parameters[0]);
  916. }
  917. }
  918. throw Helpers::EvaluationError ("Unknown function: \"" + functionName + "\"");
  919. }
  920. void Expression::Scope::visitRelativeScope (const String& scopeName, Visitor&) const
  921. {
  922. throw Helpers::EvaluationError ("Unknown symbol: " + scopeName);
  923. }
  924. String Expression::Scope::getScopeUID() const
  925. {
  926. return String::empty;
  927. }