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.

1174 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. 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 (static_cast<TermPtr&&> (l)), right (static_cast<TermPtr&&> (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() : 0); }
  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. const int 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* const l, TermPtr r) : BinaryTerm (l, r) {}
  242. TermPtr resolve (const Scope& scope, int recursionDepth)
  243. {
  244. checkRecursionDepth (recursionDepth);
  245. EvaluationVisitor visitor (right, recursionDepth + 1);
  246. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  247. return visitor.output;
  248. }
  249. Term* clone() const { return new DotOperator (getSymbol(), right.get()); }
  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 ? 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. const TermPtr 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. jassert (term != nullptr);
  452. if (term->getType() == constantType)
  453. {
  454. Constant* const c = static_cast<Constant*> (term);
  455. if (c->isResolutionTarget || ! mustBeFlagged)
  456. return c;
  457. }
  458. if (term->getType() == functionType)
  459. return nullptr;
  460. const int numIns = term->getNumInputs();
  461. for (int i = 0; i < numIns; ++i)
  462. {
  463. Term* const input = term->getInput (i);
  464. if (input->getType() == constantType)
  465. {
  466. Constant* const c = static_cast<Constant*> (input);
  467. if (c->isResolutionTarget || ! mustBeFlagged)
  468. return c;
  469. }
  470. }
  471. for (int i = 0; i < numIns; ++i)
  472. {
  473. Constant* const c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  474. if (c != nullptr)
  475. return c;
  476. }
  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 : 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 : 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. const TermPtr 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. Term* parseError (const String& message)
  530. {
  531. if (error.isEmpty())
  532. error = message;
  533. return nullptr;
  534. }
  535. //==============================================================================
  536. static inline 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 = text.findEndOfWhitespace();
  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 = text.findEndOfWhitespace();
  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 = text.findEndOfWhitespace();
  590. auto t = text;
  591. bool isResolutionTarget = (*t == '@');
  592. if (isResolutionTarget)
  593. {
  594. ++t;
  595. t = t.findEndOfWhitespace();
  596. text = t;
  597. }
  598. if (*t == '-')
  599. {
  600. ++t;
  601. t = t.findEndOfWhitespace();
  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. TermPtr lhs (readMultiplyOrDivideExpression());
  610. char opType;
  611. while (lhs != nullptr && readOperator ("+-", &opType))
  612. {
  613. TermPtr 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. TermPtr 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. TermPtr e (readParenthesisedExpression());
  656. if (e != nullptr)
  657. return e;
  658. e = readNumber();
  659. if (e != nullptr)
  660. return e;
  661. return readSymbolOrFunction();
  662. }
  663. TermPtr readSymbolOrFunction()
  664. {
  665. String identifier;
  666. if (readIdentifier (identifier))
  667. {
  668. if (readOperator ("(")) // method call...
  669. {
  670. Function* const f = new Function (identifier);
  671. std::unique_ptr<Term> func (f); // (can't use std::unique_ptr<Function> in MSVC)
  672. TermPtr param (readExpression());
  673. if (param == nullptr)
  674. {
  675. if (readOperator (")"))
  676. return func.release();
  677. return parseError ("Expected parameters after \"" + identifier + " (\"");
  678. }
  679. f->parameters.add (Expression (param));
  680. while (readOperator (","))
  681. {
  682. param = readExpression();
  683. if (param == nullptr)
  684. return parseError ("Expected expression after \",\"");
  685. f->parameters.add (Expression (param));
  686. }
  687. if (readOperator (")"))
  688. return func.release();
  689. return parseError ("Expected \")\"");
  690. }
  691. if (readOperator ("."))
  692. {
  693. TermPtr rhs (readSymbolOrFunction());
  694. if (rhs == nullptr)
  695. return parseError ("Expected symbol or function after \".\"");
  696. if (identifier == "this")
  697. return rhs;
  698. return new DotOperator (new SymbolTerm (identifier), rhs);
  699. }
  700. // just a symbol..
  701. jassert (identifier.trim() == identifier);
  702. return new SymbolTerm (identifier);
  703. }
  704. return {};
  705. }
  706. TermPtr readParenthesisedExpression()
  707. {
  708. if (! readOperator ("("))
  709. return {};
  710. const TermPtr e (readExpression());
  711. if (e == nullptr || ! readOperator (")"))
  712. return {};
  713. return e;
  714. }
  715. JUCE_DECLARE_NON_COPYABLE (Parser)
  716. };
  717. };
  718. //==============================================================================
  719. Expression::Expression()
  720. : term (new Expression::Helpers::Constant (0, false))
  721. {
  722. }
  723. Expression::~Expression()
  724. {
  725. }
  726. Expression::Expression (Term* t) : term (t)
  727. {
  728. jassert (term != nullptr);
  729. }
  730. Expression::Expression (const double constant)
  731. : term (new Expression::Helpers::Constant (constant, false))
  732. {
  733. }
  734. Expression::Expression (const Expression& other)
  735. : term (other.term)
  736. {
  737. }
  738. Expression& Expression::operator= (const Expression& other)
  739. {
  740. term = other.term;
  741. return *this;
  742. }
  743. Expression::Expression (Expression&& other) noexcept
  744. : term (static_cast<ReferenceCountedObjectPtr<Term>&&> (other.term))
  745. {
  746. }
  747. Expression& Expression::operator= (Expression&& other) noexcept
  748. {
  749. term = static_cast<ReferenceCountedObjectPtr<Term>&&> (other.term);
  750. return *this;
  751. }
  752. Expression::Expression (const String& stringToParse, String& parseError)
  753. {
  754. auto text = stringToParse.getCharPointer();
  755. Helpers::Parser parser (text);
  756. term = parser.readUpToComma();
  757. parseError = parser.error;
  758. }
  759. Expression Expression::parse (String::CharPointerType& stringToParse, String& parseError)
  760. {
  761. Helpers::Parser parser (stringToParse);
  762. Expression e (parser.readUpToComma());
  763. parseError = parser.error;
  764. return e;
  765. }
  766. double Expression::evaluate() const
  767. {
  768. return evaluate (Expression::Scope());
  769. }
  770. double Expression::evaluate (const Expression::Scope& scope) const
  771. {
  772. String err;
  773. return evaluate (scope, err);
  774. }
  775. double Expression::evaluate (const Scope& scope, String& evaluationError) const
  776. {
  777. try
  778. {
  779. return term->resolve (scope, 0)->toDouble();
  780. }
  781. catch (Helpers::EvaluationError& e)
  782. {
  783. evaluationError = e.description;
  784. }
  785. return 0;
  786. }
  787. Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  788. Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  789. Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  790. Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  791. Expression Expression::operator-() const { return Expression (term->negated()); }
  792. Expression Expression::symbol (const String& symbol) { return Expression (new Helpers::SymbolTerm (symbol)); }
  793. Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  794. {
  795. return Expression (new Helpers::Function (functionName, parameters));
  796. }
  797. Expression Expression::adjustedToGiveNewResult (const double targetValue, const Expression::Scope& scope) const
  798. {
  799. std::unique_ptr<Term> newTerm (term->clone());
  800. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm.get(), true);
  801. if (termToAdjust == nullptr)
  802. termToAdjust = Helpers::findTermToAdjust (newTerm.get(), false);
  803. if (termToAdjust == nullptr)
  804. {
  805. newTerm.reset (new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false)));
  806. termToAdjust = Helpers::findTermToAdjust (newTerm.get(), false);
  807. }
  808. jassert (termToAdjust != nullptr);
  809. if (const Term* parent = Helpers::findDestinationFor (newTerm.get(), termToAdjust))
  810. {
  811. if (Helpers::TermPtr reverseTerm = parent->createTermToEvaluateInput (scope, termToAdjust, targetValue, newTerm.get()))
  812. termToAdjust->value = Expression (reverseTerm).evaluate (scope);
  813. else
  814. return Expression (targetValue);
  815. }
  816. else
  817. {
  818. termToAdjust->value = targetValue;
  819. }
  820. return Expression (newTerm.release());
  821. }
  822. Expression Expression::withRenamedSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Scope& scope) const
  823. {
  824. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  825. if (oldSymbol.symbolName == newName)
  826. return *this;
  827. Expression e (term->clone());
  828. e.term->renameSymbol (oldSymbol, newName, scope, 0);
  829. return e;
  830. }
  831. bool Expression::referencesSymbol (const Expression::Symbol& symbolToCheck, const Scope& scope) const
  832. {
  833. Helpers::SymbolCheckVisitor visitor (symbolToCheck);
  834. try
  835. {
  836. term->visitAllSymbols (visitor, scope, 0);
  837. }
  838. catch (Helpers::EvaluationError&)
  839. {}
  840. return visitor.wasFound;
  841. }
  842. void Expression::findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const
  843. {
  844. try
  845. {
  846. Helpers::SymbolListVisitor visitor (results);
  847. term->visitAllSymbols (visitor, scope, 0);
  848. }
  849. catch (Helpers::EvaluationError&)
  850. {}
  851. }
  852. String Expression::toString() const { return term->toString(); }
  853. bool Expression::usesAnySymbols() const { return Helpers::containsAnySymbols (*term); }
  854. Expression::Type Expression::getType() const noexcept { return term->getType(); }
  855. String Expression::getSymbolOrFunction() const { return term->getName(); }
  856. int Expression::getNumInputs() const { return term->getNumInputs(); }
  857. Expression Expression::getInput (int index) const { return Expression (term->getInput (index)); }
  858. //==============================================================================
  859. ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  860. {
  861. return new Helpers::Negate (this);
  862. }
  863. //==============================================================================
  864. Expression::Symbol::Symbol (const String& scope, const String& symbol)
  865. : scopeUID (scope), symbolName (symbol)
  866. {
  867. }
  868. bool Expression::Symbol::operator== (const Symbol& other) const noexcept
  869. {
  870. return symbolName == other.symbolName && scopeUID == other.scopeUID;
  871. }
  872. bool Expression::Symbol::operator!= (const Symbol& other) const noexcept
  873. {
  874. return ! operator== (other);
  875. }
  876. //==============================================================================
  877. Expression::Scope::Scope() {}
  878. Expression::Scope::~Scope() {}
  879. Expression Expression::Scope::getSymbolValue (const String& symbol) const
  880. {
  881. if (symbol.isNotEmpty())
  882. throw Helpers::EvaluationError ("Unknown symbol: " + symbol);
  883. return Expression();
  884. }
  885. double Expression::Scope::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  886. {
  887. if (numParams > 0)
  888. {
  889. if (functionName == "min")
  890. {
  891. double v = parameters[0];
  892. for (int i = 1; i < numParams; ++i)
  893. v = jmin (v, parameters[i]);
  894. return v;
  895. }
  896. if (functionName == "max")
  897. {
  898. double v = parameters[0];
  899. for (int i = 1; i < numParams; ++i)
  900. v = jmax (v, parameters[i]);
  901. return v;
  902. }
  903. if (numParams == 1)
  904. {
  905. if (functionName == "sin") return std::sin (parameters[0]);
  906. if (functionName == "cos") return std::cos (parameters[0]);
  907. if (functionName == "tan") return std::tan (parameters[0]);
  908. if (functionName == "abs") return std::abs (parameters[0]);
  909. }
  910. }
  911. throw Helpers::EvaluationError ("Unknown function: \"" + functionName + "\"");
  912. }
  913. void Expression::Scope::visitRelativeScope (const String& scopeName, Visitor&) const
  914. {
  915. throw Helpers::EvaluationError ("Unknown symbol: " + scopeName);
  916. }
  917. String Expression::Scope::getScopeUID() const
  918. {
  919. return {};
  920. }
  921. } // namespace juce