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.

1170 lines
39KB

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