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.

1175 lines
39KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  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. namespace juce
  18. {
  19. class Expression::Term : public SingleThreadedReferenceCountedObject
  20. {
  21. public:
  22. Term() {}
  23. virtual ~Term() {}
  24. virtual Type getType() const noexcept = 0;
  25. virtual Term* clone() const = 0;
  26. virtual ReferenceCountedObjectPtr<Term> resolve (const Scope&, int recursionDepth) = 0;
  27. virtual String toString() const = 0;
  28. virtual double toDouble() const { return 0; }
  29. virtual int getInputIndexFor (const Term*) const { return -1; }
  30. virtual int getOperatorPrecedence() const { return 0; }
  31. virtual int getNumInputs() const { return 0; }
  32. virtual Term* getInput (int) const { return nullptr; }
  33. virtual ReferenceCountedObjectPtr<Term> negated();
  34. virtual ReferenceCountedObjectPtr<Term> createTermToEvaluateInput (const Scope&, const Term* /*inputTerm*/,
  35. double /*overallTarget*/, Term* /*topLevelTerm*/) const
  36. {
  37. jassertfalse;
  38. return ReferenceCountedObjectPtr<Term>();
  39. }
  40. virtual String getName() const
  41. {
  42. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  43. return {};
  44. }
  45. virtual void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  46. {
  47. for (int i = getNumInputs(); --i >= 0;)
  48. getInput (i)->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  49. }
  50. class SymbolVisitor
  51. {
  52. public:
  53. virtual ~SymbolVisitor() {}
  54. virtual void useSymbol (const Symbol&) = 0;
  55. };
  56. virtual void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  57. {
  58. for (int i = getNumInputs(); --i >= 0;)
  59. getInput (i)->visitAllSymbols (visitor, scope, recursionDepth);
  60. }
  61. private:
  62. JUCE_DECLARE_NON_COPYABLE (Term)
  63. };
  64. //==============================================================================
  65. struct Expression::Helpers
  66. {
  67. using TermPtr = ReferenceCountedObjectPtr<Term>;
  68. static void checkRecursionDepth (int depth)
  69. {
  70. if (depth > 256)
  71. throw EvaluationError ("Recursive symbol references");
  72. }
  73. friend class Expression::Term;
  74. //==============================================================================
  75. /** An exception that can be thrown by Expression::evaluate(). */
  76. class EvaluationError final : public std::exception
  77. {
  78. public:
  79. EvaluationError (const String& desc) : description (desc)
  80. {
  81. DBG ("Expression::EvaluationError: " + description);
  82. }
  83. String description;
  84. };
  85. //==============================================================================
  86. class Constant final : public Term
  87. {
  88. public:
  89. Constant (double val, bool resolutionTarget)
  90. : value (val), isResolutionTarget (resolutionTarget) {}
  91. Type getType() const noexcept { return constantType; }
  92. Term* clone() const { return new Constant (value, isResolutionTarget); }
  93. TermPtr resolve (const Scope&, int) { return *this; }
  94. double toDouble() const { return value; }
  95. TermPtr negated() { return *new Constant (-value, isResolutionTarget); }
  96. String toString() const
  97. {
  98. String s (value);
  99. if (isResolutionTarget)
  100. s = "@" + s;
  101. return s;
  102. }
  103. double value;
  104. bool isResolutionTarget;
  105. };
  106. //==============================================================================
  107. class BinaryTerm : public Term
  108. {
  109. public:
  110. BinaryTerm (TermPtr l, TermPtr r) : left (std::move (l)), right (std::move (r))
  111. {
  112. jassert (left != nullptr && right != nullptr);
  113. }
  114. int getInputIndexFor (const Term* possibleInput) const
  115. {
  116. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  117. }
  118. Type getType() const noexcept { return operatorType; }
  119. int getNumInputs() const { return 2; }
  120. Term* getInput (int index) const { return index == 0 ? left.get() : (index == 1 ? right.get() : nullptr); }
  121. virtual double performFunction (double left, double right) const = 0;
  122. virtual void writeOperator (String& dest) const = 0;
  123. TermPtr resolve (const Scope& scope, int recursionDepth)
  124. {
  125. return *new Constant (performFunction (left ->resolve (scope, recursionDepth)->toDouble(),
  126. right->resolve (scope, recursionDepth)->toDouble()), false);
  127. }
  128. String toString() const
  129. {
  130. String s;
  131. auto ourPrecendence = getOperatorPrecedence();
  132. if (left->getOperatorPrecedence() > ourPrecendence)
  133. s << '(' << left->toString() << ')';
  134. else
  135. s = left->toString();
  136. writeOperator (s);
  137. if (right->getOperatorPrecedence() >= ourPrecendence)
  138. s << '(' << right->toString() << ')';
  139. else
  140. s << right->toString();
  141. return s;
  142. }
  143. protected:
  144. const TermPtr left, right;
  145. TermPtr createDestinationTerm (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  146. {
  147. jassert (input == left || input == right);
  148. if (input != left && input != right)
  149. return {};
  150. if (auto dest = findDestinationFor (topLevelTerm, this))
  151. return dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm);
  152. return *new Constant (overallTarget, false);
  153. }
  154. };
  155. //==============================================================================
  156. class SymbolTerm final : 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 final : 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.get(); }
  194. String getName() const { return functionName; }
  195. TermPtr resolve (const Scope& scope, int recursionDepth)
  196. {
  197. checkRecursionDepth (recursionDepth);
  198. double result = 0;
  199. auto numParams = parameters.size();
  200. if (numParams > 0)
  201. {
  202. HeapBlock<double> params (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 final : public BinaryTerm
  239. {
  240. public:
  241. DotOperator (SymbolTerm* l, TermPtr r) : BinaryTerm (TermPtr (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 final : 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 final : 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 final : 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 final : 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, [[maybe_unused]] const Term* t, double overallTarget, Term* topLevelTerm) const
  338. {
  339. jassert (t == input);
  340. const Term* const dest = findDestinationFor (topLevelTerm, this);
  341. return *new Negate (dest == nullptr ? TermPtr (*new Constant (overallTarget, false))
  342. : dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm));
  343. }
  344. String toString() const
  345. {
  346. if (input->getOperatorPrecedence() > 0)
  347. return "-(" + input->toString() + ")";
  348. return "-" + input->toString();
  349. }
  350. private:
  351. const TermPtr input;
  352. };
  353. //==============================================================================
  354. class Add final : public BinaryTerm
  355. {
  356. public:
  357. Add (TermPtr l, TermPtr r) : BinaryTerm (l, r) {}
  358. Term* clone() const { return new Add (*left->clone(), *right->clone()); }
  359. double performFunction (double lhs, double rhs) const { return lhs + rhs; }
  360. int getOperatorPrecedence() const { return 3; }
  361. String getName() const { return "+"; }
  362. void writeOperator (String& dest) const { dest << " + "; }
  363. TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  364. {
  365. if (auto newDest = createDestinationTerm (scope, input, overallTarget, topLevelTerm))
  366. return *new Subtract (newDest, *(input == left ? right : left)->clone());
  367. return {};
  368. }
  369. private:
  370. JUCE_DECLARE_NON_COPYABLE (Add)
  371. };
  372. //==============================================================================
  373. class Subtract final : public BinaryTerm
  374. {
  375. public:
  376. Subtract (TermPtr l, TermPtr 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. if (auto newDest = createDestinationTerm (scope, input, overallTarget, topLevelTerm))
  385. {
  386. if (input == left)
  387. return *new Add (*newDest, *right->clone());
  388. return *new Subtract (*left->clone(), *newDest);
  389. }
  390. return {};
  391. }
  392. private:
  393. JUCE_DECLARE_NON_COPYABLE (Subtract)
  394. };
  395. //==============================================================================
  396. class Multiply final : public BinaryTerm
  397. {
  398. public:
  399. Multiply (TermPtr l, TermPtr r) : BinaryTerm (l, r) {}
  400. Term* clone() const { return new Multiply (*left->clone(), *right->clone()); }
  401. double performFunction (double lhs, double rhs) const { return lhs * rhs; }
  402. String getName() const { return "*"; }
  403. void writeOperator (String& dest) const { dest << " * "; }
  404. int getOperatorPrecedence() const { return 2; }
  405. TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  406. {
  407. if (auto newDest = createDestinationTerm (scope, input, overallTarget, topLevelTerm))
  408. return *new Divide (newDest, *(input == left ? right : left)->clone());
  409. return {};
  410. }
  411. JUCE_DECLARE_NON_COPYABLE (Multiply)
  412. };
  413. //==============================================================================
  414. class Divide final : public BinaryTerm
  415. {
  416. public:
  417. Divide (TermPtr l, TermPtr r) : BinaryTerm (l, r) {}
  418. Term* clone() const { return new Divide (*left->clone(), *right->clone()); }
  419. double performFunction (double lhs, double rhs) const { return lhs / rhs; }
  420. String getName() const { return "/"; }
  421. void writeOperator (String& dest) const { dest << " / "; }
  422. int getOperatorPrecedence() const { return 2; }
  423. TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  424. {
  425. auto newDest = createDestinationTerm (scope, input, overallTarget, topLevelTerm);
  426. if (newDest == nullptr)
  427. return {};
  428. if (input == left)
  429. return *new Multiply (*newDest, *right->clone());
  430. return *new Divide (*left->clone(), *newDest);
  431. }
  432. JUCE_DECLARE_NON_COPYABLE (Divide)
  433. };
  434. //==============================================================================
  435. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  436. {
  437. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  438. if (inputIndex >= 0)
  439. return topLevel;
  440. for (int i = topLevel->getNumInputs(); --i >= 0;)
  441. {
  442. Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm);
  443. if (t != nullptr)
  444. return t;
  445. }
  446. return nullptr;
  447. }
  448. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  449. {
  450. if (term == nullptr)
  451. {
  452. jassertfalse;
  453. return nullptr;
  454. }
  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. if (auto c = findTermToAdjust (term->getInput (i), mustBeFlagged))
  476. return c;
  477. return nullptr;
  478. }
  479. static bool containsAnySymbols (const Term& t)
  480. {
  481. if (t.getType() == Expression::symbolType)
  482. return true;
  483. for (int i = t.getNumInputs(); --i >= 0;)
  484. if (containsAnySymbols (*t.getInput (i)))
  485. return true;
  486. return false;
  487. }
  488. //==============================================================================
  489. class SymbolCheckVisitor final : public Term::SymbolVisitor
  490. {
  491. public:
  492. SymbolCheckVisitor (const Symbol& s) : symbol (s) {}
  493. void useSymbol (const Symbol& s) { wasFound = wasFound || s == symbol; }
  494. bool wasFound = false;
  495. private:
  496. const Symbol& symbol;
  497. JUCE_DECLARE_NON_COPYABLE (SymbolCheckVisitor)
  498. };
  499. //==============================================================================
  500. class SymbolListVisitor final : public Term::SymbolVisitor
  501. {
  502. public:
  503. SymbolListVisitor (Array<Symbol>& list_) : list (list_) {}
  504. void useSymbol (const Symbol& s) { list.addIfNotAlreadyThere (s); }
  505. private:
  506. Array<Symbol>& list;
  507. JUCE_DECLARE_NON_COPYABLE (SymbolListVisitor)
  508. };
  509. //==============================================================================
  510. class Parser
  511. {
  512. public:
  513. //==============================================================================
  514. Parser (String::CharPointerType& stringToParse) : text (stringToParse)
  515. {
  516. }
  517. TermPtr readUpToComma()
  518. {
  519. if (text.isEmpty())
  520. return *new Constant (0.0, false);
  521. auto e = readExpression();
  522. if (e == nullptr || ((! readOperator (",")) && ! text.isEmpty()))
  523. return parseError ("Syntax error: \"" + String (text) + "\"");
  524. return e;
  525. }
  526. String error;
  527. private:
  528. String::CharPointerType& text;
  529. TermPtr parseError (const String& message)
  530. {
  531. if (error.isEmpty())
  532. error = message;
  533. return {};
  534. }
  535. //==============================================================================
  536. static bool isDecimalDigit (const juce_wchar c) noexcept
  537. {
  538. return c >= '0' && c <= '9';
  539. }
  540. bool readChar (const juce_wchar required) noexcept
  541. {
  542. if (*text == required)
  543. {
  544. ++text;
  545. return true;
  546. }
  547. return false;
  548. }
  549. bool readOperator (const char* ops, char* const opType = nullptr) noexcept
  550. {
  551. text.incrementToEndOfWhitespace();
  552. while (*ops != 0)
  553. {
  554. if (readChar ((juce_wchar) (uint8) *ops))
  555. {
  556. if (opType != nullptr)
  557. *opType = *ops;
  558. return true;
  559. }
  560. ++ops;
  561. }
  562. return false;
  563. }
  564. bool readIdentifier (String& identifier) noexcept
  565. {
  566. text.incrementToEndOfWhitespace();
  567. auto t = text;
  568. int numChars = 0;
  569. if (t.isLetter() || *t == '_')
  570. {
  571. ++t;
  572. ++numChars;
  573. while (t.isLetterOrDigit() || *t == '_')
  574. {
  575. ++t;
  576. ++numChars;
  577. }
  578. }
  579. if (numChars > 0)
  580. {
  581. identifier = String (text, (size_t) numChars);
  582. text = t;
  583. return true;
  584. }
  585. return false;
  586. }
  587. Term* readNumber() noexcept
  588. {
  589. text.incrementToEndOfWhitespace();
  590. auto t = text;
  591. bool isResolutionTarget = (*t == '@');
  592. if (isResolutionTarget)
  593. {
  594. ++t;
  595. t.incrementToEndOfWhitespace();
  596. text = t;
  597. }
  598. if (*t == '-')
  599. {
  600. ++t;
  601. t.incrementToEndOfWhitespace();
  602. }
  603. if (isDecimalDigit (*t) || (*t == '.' && isDecimalDigit (t[1])))
  604. return new Constant (CharacterFunctions::readDoubleValue (text), isResolutionTarget);
  605. return nullptr;
  606. }
  607. TermPtr readExpression()
  608. {
  609. auto lhs = readMultiplyOrDivideExpression();
  610. char opType;
  611. while (lhs != nullptr && readOperator ("+-", &opType))
  612. {
  613. auto rhs = readMultiplyOrDivideExpression();
  614. if (rhs == nullptr)
  615. return parseError ("Expected expression after \"" + String::charToString ((juce_wchar) (uint8) opType) + "\"");
  616. if (opType == '+')
  617. lhs = *new Add (lhs, rhs);
  618. else
  619. lhs = *new Subtract (lhs, rhs);
  620. }
  621. return lhs;
  622. }
  623. TermPtr readMultiplyOrDivideExpression()
  624. {
  625. auto lhs = readUnaryExpression();
  626. char opType;
  627. while (lhs != nullptr && readOperator ("*/", &opType))
  628. {
  629. TermPtr rhs (readUnaryExpression());
  630. if (rhs == nullptr)
  631. return parseError ("Expected expression after \"" + String::charToString ((juce_wchar) (uint8) opType) + "\"");
  632. if (opType == '*')
  633. lhs = *new Multiply (lhs, rhs);
  634. else
  635. lhs = *new Divide (lhs, rhs);
  636. }
  637. return lhs;
  638. }
  639. TermPtr readUnaryExpression()
  640. {
  641. char opType;
  642. if (readOperator ("+-", &opType))
  643. {
  644. TermPtr e (readUnaryExpression());
  645. if (e == nullptr)
  646. return parseError ("Expected expression after \"" + String::charToString ((juce_wchar) (uint8) opType) + "\"");
  647. if (opType == '-')
  648. e = e->negated();
  649. return e;
  650. }
  651. return readPrimaryExpression();
  652. }
  653. TermPtr readPrimaryExpression()
  654. {
  655. if (auto e = readParenthesisedExpression())
  656. return e;
  657. if (auto e = readNumber())
  658. return e;
  659. return readSymbolOrFunction();
  660. }
  661. TermPtr readSymbolOrFunction()
  662. {
  663. String identifier;
  664. if (readIdentifier (identifier))
  665. {
  666. if (readOperator ("(")) // method call...
  667. {
  668. auto f = new Function (identifier);
  669. std::unique_ptr<Term> func (f); // (can't use std::unique_ptr<Function> in MSVC)
  670. auto param = readExpression();
  671. if (param == nullptr)
  672. {
  673. if (readOperator (")"))
  674. return TermPtr (func.release());
  675. return parseError ("Expected parameters after \"" + identifier + " (\"");
  676. }
  677. f->parameters.add (Expression (param.get()));
  678. while (readOperator (","))
  679. {
  680. param = readExpression();
  681. if (param == nullptr)
  682. return parseError ("Expected expression after \",\"");
  683. f->parameters.add (Expression (param.get()));
  684. }
  685. if (readOperator (")"))
  686. return TermPtr (func.release());
  687. return parseError ("Expected \")\"");
  688. }
  689. if (readOperator ("."))
  690. {
  691. TermPtr rhs (readSymbolOrFunction());
  692. if (rhs == nullptr)
  693. return parseError ("Expected symbol or function after \".\"");
  694. if (identifier == "this")
  695. return rhs;
  696. return *new DotOperator (new SymbolTerm (identifier), rhs);
  697. }
  698. // just a symbol..
  699. jassert (identifier.trim() == identifier);
  700. return *new SymbolTerm (identifier);
  701. }
  702. return {};
  703. }
  704. TermPtr readParenthesisedExpression()
  705. {
  706. if (! readOperator ("("))
  707. return {};
  708. auto e = readExpression();
  709. if (e == nullptr || ! readOperator (")"))
  710. return {};
  711. return e;
  712. }
  713. JUCE_DECLARE_NON_COPYABLE (Parser)
  714. };
  715. };
  716. //==============================================================================
  717. Expression::Expression()
  718. : term (new Expression::Helpers::Constant (0, false))
  719. {
  720. }
  721. Expression::~Expression()
  722. {
  723. }
  724. Expression::Expression (Term* t) : term (t)
  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. Expression::Expression (Expression&& other) noexcept
  742. : term (std::move (other.term))
  743. {
  744. }
  745. Expression& Expression::operator= (Expression&& other) noexcept
  746. {
  747. term = std::move (other.term);
  748. return *this;
  749. }
  750. Expression::Expression (const String& stringToParse, String& parseError)
  751. {
  752. auto text = stringToParse.getCharPointer();
  753. Helpers::Parser parser (text);
  754. term = parser.readUpToComma();
  755. parseError = parser.error;
  756. }
  757. Expression Expression::parse (String::CharPointerType& stringToParse, String& parseError)
  758. {
  759. Helpers::Parser parser (stringToParse);
  760. Expression e (parser.readUpToComma().get());
  761. parseError = parser.error;
  762. return e;
  763. }
  764. double Expression::evaluate() const
  765. {
  766. return evaluate (Expression::Scope());
  767. }
  768. double Expression::evaluate (const Expression::Scope& scope) const
  769. {
  770. String err;
  771. return evaluate (scope, err);
  772. }
  773. double Expression::evaluate (const Scope& scope, String& evaluationError) const
  774. {
  775. try
  776. {
  777. return term->resolve (scope, 0)->toDouble();
  778. }
  779. catch (Helpers::EvaluationError& e)
  780. {
  781. evaluationError = e.description;
  782. }
  783. return 0;
  784. }
  785. Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  786. Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  787. Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  788. Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  789. Expression Expression::operator-() const { return Expression (term->negated().get()); }
  790. Expression Expression::symbol (const String& symbol) { return Expression (new Helpers::SymbolTerm (symbol)); }
  791. Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  792. {
  793. return Expression (new Helpers::Function (functionName, parameters));
  794. }
  795. Expression Expression::adjustedToGiveNewResult (const double targetValue, const Expression::Scope& scope) const
  796. {
  797. std::unique_ptr<Term> newTerm (term->clone());
  798. auto termToAdjust = Helpers::findTermToAdjust (newTerm.get(), true);
  799. if (termToAdjust == nullptr)
  800. termToAdjust = Helpers::findTermToAdjust (newTerm.get(), false);
  801. if (termToAdjust == nullptr)
  802. {
  803. newTerm.reset (new Helpers::Add (*newTerm.release(), *new Helpers::Constant (0, false)));
  804. termToAdjust = Helpers::findTermToAdjust (newTerm.get(), false);
  805. }
  806. jassert (termToAdjust != nullptr);
  807. if (const Term* parent = Helpers::findDestinationFor (newTerm.get(), termToAdjust))
  808. {
  809. if (Helpers::TermPtr reverseTerm = parent->createTermToEvaluateInput (scope, termToAdjust, targetValue, newTerm.get()))
  810. termToAdjust->value = Expression (reverseTerm.get()).evaluate (scope);
  811. else
  812. return Expression (targetValue);
  813. }
  814. else
  815. {
  816. termToAdjust->value = targetValue;
  817. }
  818. return Expression (newTerm.release());
  819. }
  820. Expression Expression::withRenamedSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Scope& scope) const
  821. {
  822. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  823. if (oldSymbol.symbolName == newName)
  824. return *this;
  825. Expression e (term->clone());
  826. e.term->renameSymbol (oldSymbol, newName, scope, 0);
  827. return e;
  828. }
  829. bool Expression::referencesSymbol (const Expression::Symbol& symbolToCheck, const Scope& scope) const
  830. {
  831. Helpers::SymbolCheckVisitor visitor (symbolToCheck);
  832. try
  833. {
  834. term->visitAllSymbols (visitor, scope, 0);
  835. }
  836. catch (Helpers::EvaluationError&)
  837. {}
  838. return visitor.wasFound;
  839. }
  840. void Expression::findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const
  841. {
  842. try
  843. {
  844. Helpers::SymbolListVisitor visitor (results);
  845. term->visitAllSymbols (visitor, scope, 0);
  846. }
  847. catch (Helpers::EvaluationError&)
  848. {}
  849. }
  850. String Expression::toString() const { return term->toString(); }
  851. bool Expression::usesAnySymbols() const { return Helpers::containsAnySymbols (*term); }
  852. Expression::Type Expression::getType() const noexcept { return term->getType(); }
  853. String Expression::getSymbolOrFunction() const { return term->getName(); }
  854. int Expression::getNumInputs() const { return term->getNumInputs(); }
  855. Expression Expression::getInput (int index) const { return Expression (term->getInput (index)); }
  856. //==============================================================================
  857. ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  858. {
  859. return *new Helpers::Negate (*this);
  860. }
  861. //==============================================================================
  862. Expression::Symbol::Symbol (const String& scope, const String& symbol)
  863. : scopeUID (scope), symbolName (symbol)
  864. {
  865. }
  866. bool Expression::Symbol::operator== (const Symbol& other) const noexcept
  867. {
  868. return symbolName == other.symbolName && scopeUID == other.scopeUID;
  869. }
  870. bool Expression::Symbol::operator!= (const Symbol& other) const noexcept
  871. {
  872. return ! operator== (other);
  873. }
  874. //==============================================================================
  875. Expression::Scope::Scope() {}
  876. Expression::Scope::~Scope() {}
  877. Expression Expression::Scope::getSymbolValue (const String& symbol) const
  878. {
  879. if (symbol.isNotEmpty())
  880. throw Helpers::EvaluationError ("Unknown symbol: " + symbol);
  881. return Expression();
  882. }
  883. double Expression::Scope::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  884. {
  885. if (numParams > 0)
  886. {
  887. if (functionName == "min")
  888. {
  889. double v = parameters[0];
  890. for (int i = 1; i < numParams; ++i)
  891. v = jmin (v, parameters[i]);
  892. return v;
  893. }
  894. if (functionName == "max")
  895. {
  896. double v = parameters[0];
  897. for (int i = 1; i < numParams; ++i)
  898. v = jmax (v, parameters[i]);
  899. return v;
  900. }
  901. if (numParams == 1)
  902. {
  903. if (functionName == "sin") return std::sin (parameters[0]);
  904. if (functionName == "cos") return std::cos (parameters[0]);
  905. if (functionName == "tan") return std::tan (parameters[0]);
  906. if (functionName == "abs") return std::abs (parameters[0]);
  907. }
  908. }
  909. throw Helpers::EvaluationError ("Unknown function: \"" + functionName + "\"");
  910. }
  911. void Expression::Scope::visitRelativeScope (const String& scopeName, Visitor&) const
  912. {
  913. throw Helpers::EvaluationError ("Unknown symbol: " + scopeName);
  914. }
  915. String Expression::Scope::getScopeUID() const
  916. {
  917. return {};
  918. }
  919. } // namespace juce