juce_Expression.cpp 39 KB

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