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.

1176 lines
38KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - 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 : 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 : 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 : 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.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 : 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 : 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. ignoreUnused (t);
  340. jassert (t == input);
  341. const Term* const dest = findDestinationFor (topLevelTerm, this);
  342. return *new Negate (dest == nullptr ? TermPtr (*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 (TermPtr l, TermPtr 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. if (auto newDest = createDestinationTerm (scope, input, overallTarget, topLevelTerm))
  367. return *new Subtract (newDest, *(input == left ? right : left)->clone());
  368. return {};
  369. }
  370. private:
  371. JUCE_DECLARE_NON_COPYABLE (Add)
  372. };
  373. //==============================================================================
  374. class Subtract : public BinaryTerm
  375. {
  376. public:
  377. Subtract (TermPtr l, TermPtr r) : BinaryTerm (l, r) {}
  378. Term* clone() const { return new Subtract (*left->clone(), *right->clone()); }
  379. double performFunction (double lhs, double rhs) const { return lhs - rhs; }
  380. int getOperatorPrecedence() const { return 3; }
  381. String getName() const { return "-"; }
  382. void writeOperator (String& dest) const { dest << " - "; }
  383. TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  384. {
  385. if (auto newDest = createDestinationTerm (scope, input, overallTarget, topLevelTerm))
  386. {
  387. if (input == left)
  388. return *new Add (*newDest, *right->clone());
  389. return *new Subtract (*left->clone(), *newDest);
  390. }
  391. return {};
  392. }
  393. private:
  394. JUCE_DECLARE_NON_COPYABLE (Subtract)
  395. };
  396. //==============================================================================
  397. class Multiply : public BinaryTerm
  398. {
  399. public:
  400. Multiply (TermPtr l, TermPtr 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. if (auto newDest = createDestinationTerm (scope, input, overallTarget, topLevelTerm))
  409. return *new Divide (newDest, *(input == left ? right : left)->clone());
  410. return {};
  411. }
  412. JUCE_DECLARE_NON_COPYABLE (Multiply)
  413. };
  414. //==============================================================================
  415. class Divide : public BinaryTerm
  416. {
  417. public:
  418. Divide (TermPtr l, TermPtr 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. auto newDest = createDestinationTerm (scope, input, overallTarget, topLevelTerm);
  427. if (newDest == nullptr)
  428. return {};
  429. if (input == left)
  430. return *new Multiply (*newDest, *right->clone());
  431. return *new Divide (*left->clone(), *newDest);
  432. }
  433. JUCE_DECLARE_NON_COPYABLE (Divide)
  434. };
  435. //==============================================================================
  436. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  437. {
  438. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  439. if (inputIndex >= 0)
  440. return topLevel;
  441. for (int i = topLevel->getNumInputs(); --i >= 0;)
  442. {
  443. Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm);
  444. if (t != nullptr)
  445. return t;
  446. }
  447. return nullptr;
  448. }
  449. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  450. {
  451. if (term == nullptr)
  452. {
  453. jassertfalse;
  454. return nullptr;
  455. }
  456. if (term->getType() == constantType)
  457. {
  458. Constant* const c = static_cast<Constant*> (term);
  459. if (c->isResolutionTarget || ! mustBeFlagged)
  460. return c;
  461. }
  462. if (term->getType() == functionType)
  463. return nullptr;
  464. const int numIns = term->getNumInputs();
  465. for (int i = 0; i < numIns; ++i)
  466. {
  467. Term* const input = term->getInput (i);
  468. if (input->getType() == constantType)
  469. {
  470. Constant* const c = static_cast<Constant*> (input);
  471. if (c->isResolutionTarget || ! mustBeFlagged)
  472. return c;
  473. }
  474. }
  475. for (int i = 0; i < numIns; ++i)
  476. if (auto c = findTermToAdjust (term->getInput (i), mustBeFlagged))
  477. return c;
  478. return nullptr;
  479. }
  480. static bool containsAnySymbols (const Term& 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& s) : symbol (s) {}
  494. void useSymbol (const Symbol& s) { wasFound = wasFound || s == symbol; }
  495. bool wasFound = false;
  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. auto 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. TermPtr parseError (const String& message)
  531. {
  532. if (error.isEmpty())
  533. error = message;
  534. return {};
  535. }
  536. //==============================================================================
  537. static 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.incrementToEndOfWhitespace();
  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.incrementToEndOfWhitespace();
  568. auto 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.incrementToEndOfWhitespace();
  591. auto t = text;
  592. bool isResolutionTarget = (*t == '@');
  593. if (isResolutionTarget)
  594. {
  595. ++t;
  596. t.incrementToEndOfWhitespace();
  597. text = t;
  598. }
  599. if (*t == '-')
  600. {
  601. ++t;
  602. t.incrementToEndOfWhitespace();
  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. auto lhs = readMultiplyOrDivideExpression();
  611. char opType;
  612. while (lhs != nullptr && readOperator ("+-", &opType))
  613. {
  614. auto 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. auto 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. if (auto e = readParenthesisedExpression())
  657. return e;
  658. if (auto e = readNumber())
  659. return e;
  660. return readSymbolOrFunction();
  661. }
  662. TermPtr readSymbolOrFunction()
  663. {
  664. String identifier;
  665. if (readIdentifier (identifier))
  666. {
  667. if (readOperator ("(")) // method call...
  668. {
  669. auto f = new Function (identifier);
  670. std::unique_ptr<Term> func (f); // (can't use std::unique_ptr<Function> in MSVC)
  671. auto param = readExpression();
  672. if (param == nullptr)
  673. {
  674. if (readOperator (")"))
  675. return TermPtr (func.release());
  676. return parseError ("Expected parameters after \"" + identifier + " (\"");
  677. }
  678. f->parameters.add (Expression (param.get()));
  679. while (readOperator (","))
  680. {
  681. param = readExpression();
  682. if (param == nullptr)
  683. return parseError ("Expected expression after \",\"");
  684. f->parameters.add (Expression (param.get()));
  685. }
  686. if (readOperator (")"))
  687. return TermPtr (func.release());
  688. return parseError ("Expected \")\"");
  689. }
  690. if (readOperator ("."))
  691. {
  692. TermPtr rhs (readSymbolOrFunction());
  693. if (rhs == nullptr)
  694. return parseError ("Expected symbol or function after \".\"");
  695. if (identifier == "this")
  696. return rhs;
  697. return *new DotOperator (new SymbolTerm (identifier), rhs);
  698. }
  699. // just a symbol..
  700. jassert (identifier.trim() == identifier);
  701. return *new SymbolTerm (identifier);
  702. }
  703. return {};
  704. }
  705. TermPtr readParenthesisedExpression()
  706. {
  707. if (! readOperator ("("))
  708. return {};
  709. auto e = readExpression();
  710. if (e == nullptr || ! readOperator (")"))
  711. return {};
  712. return e;
  713. }
  714. JUCE_DECLARE_NON_COPYABLE (Parser)
  715. };
  716. };
  717. //==============================================================================
  718. Expression::Expression()
  719. : term (new Expression::Helpers::Constant (0, false))
  720. {
  721. }
  722. Expression::~Expression()
  723. {
  724. }
  725. Expression::Expression (Term* t) : term (t)
  726. {
  727. jassert (term != nullptr);
  728. }
  729. Expression::Expression (const double constant)
  730. : term (new Expression::Helpers::Constant (constant, false))
  731. {
  732. }
  733. Expression::Expression (const Expression& other)
  734. : term (other.term)
  735. {
  736. }
  737. Expression& Expression::operator= (const Expression& other)
  738. {
  739. term = other.term;
  740. return *this;
  741. }
  742. Expression::Expression (Expression&& other) noexcept
  743. : term (std::move (other.term))
  744. {
  745. }
  746. Expression& Expression::operator= (Expression&& other) noexcept
  747. {
  748. term = std::move (other.term);
  749. return *this;
  750. }
  751. Expression::Expression (const String& stringToParse, String& parseError)
  752. {
  753. auto text = stringToParse.getCharPointer();
  754. Helpers::Parser parser (text);
  755. term = parser.readUpToComma();
  756. parseError = parser.error;
  757. }
  758. Expression Expression::parse (String::CharPointerType& stringToParse, String& parseError)
  759. {
  760. Helpers::Parser parser (stringToParse);
  761. Expression e (parser.readUpToComma().get());
  762. parseError = parser.error;
  763. return e;
  764. }
  765. double Expression::evaluate() const
  766. {
  767. return evaluate (Expression::Scope());
  768. }
  769. double Expression::evaluate (const Expression::Scope& scope) const
  770. {
  771. String err;
  772. return evaluate (scope, err);
  773. }
  774. double Expression::evaluate (const Scope& scope, String& evaluationError) const
  775. {
  776. try
  777. {
  778. return term->resolve (scope, 0)->toDouble();
  779. }
  780. catch (Helpers::EvaluationError& e)
  781. {
  782. evaluationError = e.description;
  783. }
  784. return 0;
  785. }
  786. Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  787. Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  788. Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  789. Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  790. Expression Expression::operator-() const { return Expression (term->negated().get()); }
  791. Expression Expression::symbol (const String& symbol) { return Expression (new Helpers::SymbolTerm (symbol)); }
  792. Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  793. {
  794. return Expression (new Helpers::Function (functionName, parameters));
  795. }
  796. Expression Expression::adjustedToGiveNewResult (const double targetValue, const Expression::Scope& scope) const
  797. {
  798. std::unique_ptr<Term> newTerm (term->clone());
  799. auto termToAdjust = Helpers::findTermToAdjust (newTerm.get(), true);
  800. if (termToAdjust == nullptr)
  801. termToAdjust = Helpers::findTermToAdjust (newTerm.get(), false);
  802. if (termToAdjust == nullptr)
  803. {
  804. newTerm.reset (new Helpers::Add (*newTerm.release(), *new Helpers::Constant (0, false)));
  805. termToAdjust = Helpers::findTermToAdjust (newTerm.get(), false);
  806. }
  807. jassert (termToAdjust != nullptr);
  808. if (const Term* parent = Helpers::findDestinationFor (newTerm.get(), termToAdjust))
  809. {
  810. if (Helpers::TermPtr reverseTerm = parent->createTermToEvaluateInput (scope, termToAdjust, targetValue, newTerm.get()))
  811. termToAdjust->value = Expression (reverseTerm.get()).evaluate (scope);
  812. else
  813. return Expression (targetValue);
  814. }
  815. else
  816. {
  817. termToAdjust->value = targetValue;
  818. }
  819. return Expression (newTerm.release());
  820. }
  821. Expression Expression::withRenamedSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Scope& scope) const
  822. {
  823. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  824. if (oldSymbol.symbolName == newName)
  825. return *this;
  826. Expression e (term->clone());
  827. e.term->renameSymbol (oldSymbol, newName, scope, 0);
  828. return e;
  829. }
  830. bool Expression::referencesSymbol (const Expression::Symbol& symbolToCheck, const Scope& scope) const
  831. {
  832. Helpers::SymbolCheckVisitor visitor (symbolToCheck);
  833. try
  834. {
  835. term->visitAllSymbols (visitor, scope, 0);
  836. }
  837. catch (Helpers::EvaluationError&)
  838. {}
  839. return visitor.wasFound;
  840. }
  841. void Expression::findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const
  842. {
  843. try
  844. {
  845. Helpers::SymbolListVisitor visitor (results);
  846. term->visitAllSymbols (visitor, scope, 0);
  847. }
  848. catch (Helpers::EvaluationError&)
  849. {}
  850. }
  851. String Expression::toString() const { return term->toString(); }
  852. bool Expression::usesAnySymbols() const { return Helpers::containsAnySymbols (*term); }
  853. Expression::Type Expression::getType() const noexcept { return term->getType(); }
  854. String Expression::getSymbolOrFunction() const { return term->getName(); }
  855. int Expression::getNumInputs() const { return term->getNumInputs(); }
  856. Expression Expression::getInput (int index) const { return Expression (term->getInput (index)); }
  857. //==============================================================================
  858. ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  859. {
  860. return *new Helpers::Negate (*this);
  861. }
  862. //==============================================================================
  863. Expression::Symbol::Symbol (const String& scope, const String& symbol)
  864. : scopeUID (scope), symbolName (symbol)
  865. {
  866. }
  867. bool Expression::Symbol::operator== (const Symbol& other) const noexcept
  868. {
  869. return symbolName == other.symbolName && scopeUID == other.scopeUID;
  870. }
  871. bool Expression::Symbol::operator!= (const Symbol& other) const noexcept
  872. {
  873. return ! operator== (other);
  874. }
  875. //==============================================================================
  876. Expression::Scope::Scope() {}
  877. Expression::Scope::~Scope() {}
  878. Expression Expression::Scope::getSymbolValue (const String& symbol) const
  879. {
  880. if (symbol.isNotEmpty())
  881. throw Helpers::EvaluationError ("Unknown symbol: " + symbol);
  882. return Expression();
  883. }
  884. double Expression::Scope::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  885. {
  886. if (numParams > 0)
  887. {
  888. if (functionName == "min")
  889. {
  890. double v = parameters[0];
  891. for (int i = 1; i < numParams; ++i)
  892. v = jmin (v, parameters[i]);
  893. return v;
  894. }
  895. if (functionName == "max")
  896. {
  897. double v = parameters[0];
  898. for (int i = 1; i < numParams; ++i)
  899. v = jmax (v, parameters[i]);
  900. return v;
  901. }
  902. if (numParams == 1)
  903. {
  904. if (functionName == "sin") return std::sin (parameters[0]);
  905. if (functionName == "cos") return std::cos (parameters[0]);
  906. if (functionName == "tan") return std::tan (parameters[0]);
  907. if (functionName == "abs") return std::abs (parameters[0]);
  908. }
  909. }
  910. throw Helpers::EvaluationError ("Unknown function: \"" + functionName + "\"");
  911. }
  912. void Expression::Scope::visitRelativeScope (const String& scopeName, Visitor&) const
  913. {
  914. throw Helpers::EvaluationError ("Unknown symbol: " + scopeName);
  915. }
  916. String Expression::Scope::getScopeUID() const
  917. {
  918. return {};
  919. }
  920. } // namespace juce