The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1180 lines
39KB

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