No Description
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.

Expression.cs 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Threading;
  6. using Unity.VisualScripting.Antlr3.Runtime;
  7. using UnityEngine;
  8. namespace Unity.VisualScripting.Dependencies.NCalc
  9. {
  10. public class Expression
  11. {
  12. private Expression()
  13. {
  14. // Fix: the original grammar doesn't include a null identifier.
  15. Parameters["null"] = Parameters["NULL"] = null;
  16. }
  17. public Expression(string expression, EvaluateOptions options = EvaluateOptions.None) : this()
  18. {
  19. if (string.IsNullOrEmpty(expression))
  20. {
  21. throw new ArgumentException("Expression can't be empty", nameof(expression));
  22. }
  23. // Fix: The original grammar doesn't allow double quotes for strings.
  24. expression = expression.Replace('\"', '\'');
  25. OriginalExpression = expression;
  26. Options = options;
  27. }
  28. public Expression(LogicalExpression expression, EvaluateOptions options = EvaluateOptions.None) : this()
  29. {
  30. if (expression == null)
  31. {
  32. throw new ArgumentException("Expression can't be null", nameof(expression));
  33. }
  34. ParsedExpression = expression;
  35. Options = options;
  36. }
  37. public event EvaluateFunctionHandler EvaluateFunction;
  38. public event EvaluateParameterHandler EvaluateParameter;
  39. /// <summary>
  40. /// Textual representation of the expression to evaluate.
  41. /// </summary>
  42. protected readonly string OriginalExpression;
  43. protected Dictionary<string, IEnumerator> ParameterEnumerators;
  44. private Dictionary<string, object> _parameters;
  45. public EvaluateOptions Options { get; set; }
  46. public string Error { get; private set; }
  47. public LogicalExpression ParsedExpression { get; private set; }
  48. public Dictionary<string, object> Parameters
  49. {
  50. get
  51. {
  52. return _parameters ?? (_parameters = new Dictionary<string, object>());
  53. }
  54. set
  55. {
  56. _parameters = value;
  57. }
  58. }
  59. public void UpdateUnityTimeParameters()
  60. {
  61. Parameters["dt"] = Parameters["DT"] = Time.deltaTime;
  62. Parameters["second"] = Parameters["Second"] = 1 / Time.deltaTime;
  63. }
  64. /// <summary>
  65. /// Pre-compiles the expression in order to check syntax errors.
  66. /// If errors are detected, the Error property contains the message.
  67. /// </summary>
  68. /// <returns>True if the expression syntax is correct, otherwise false</returns>
  69. public bool HasErrors()
  70. {
  71. try
  72. {
  73. if (ParsedExpression == null)
  74. {
  75. ParsedExpression = Compile(OriginalExpression, (Options & EvaluateOptions.NoCache) == EvaluateOptions.NoCache);
  76. }
  77. // In case HasErrors() is called multiple times for the same expression
  78. return ParsedExpression != null && Error != null;
  79. }
  80. catch (Exception e)
  81. {
  82. Error = e.Message;
  83. return true;
  84. }
  85. }
  86. public object Evaluate(Flow flow)
  87. {
  88. if (HasErrors())
  89. {
  90. throw new EvaluationException(Error);
  91. }
  92. if (ParsedExpression == null)
  93. {
  94. ParsedExpression = Compile(OriginalExpression, (Options & EvaluateOptions.NoCache) == EvaluateOptions.NoCache);
  95. }
  96. var visitor = new EvaluationVisitor(flow, Options);
  97. visitor.EvaluateFunction += EvaluateFunction;
  98. visitor.EvaluateParameter += EvaluateParameter;
  99. visitor.Parameters = Parameters;
  100. // If array evaluation, execute the same expression multiple times
  101. if ((Options & EvaluateOptions.IterateParameters) == EvaluateOptions.IterateParameters)
  102. {
  103. var size = -1;
  104. ParameterEnumerators = new Dictionary<string, IEnumerator>();
  105. foreach (var parameter in Parameters.Values)
  106. {
  107. if (parameter is IEnumerable enumerable)
  108. {
  109. var localsize = 0;
  110. foreach (var o in enumerable)
  111. {
  112. localsize++;
  113. }
  114. if (size == -1)
  115. {
  116. size = localsize;
  117. }
  118. else if (localsize != size)
  119. {
  120. throw new EvaluationException("When IterateParameters option is used, IEnumerable parameters must have the same number of items.");
  121. }
  122. }
  123. }
  124. foreach (var key in Parameters.Keys)
  125. {
  126. var parameter = Parameters[key] as IEnumerable;
  127. if (parameter != null)
  128. {
  129. ParameterEnumerators.Add(key, parameter.GetEnumerator());
  130. }
  131. }
  132. var results = new List<object>();
  133. for (var i = 0; i < size; i++)
  134. {
  135. foreach (var key in ParameterEnumerators.Keys)
  136. {
  137. var enumerator = ParameterEnumerators[key];
  138. enumerator.MoveNext();
  139. Parameters[key] = enumerator.Current;
  140. }
  141. ParsedExpression.Accept(visitor);
  142. results.Add(visitor.Result);
  143. }
  144. return results;
  145. }
  146. else
  147. {
  148. ParsedExpression.Accept(visitor);
  149. return visitor.Result;
  150. }
  151. }
  152. public static LogicalExpression Compile(string expression, bool noCache)
  153. {
  154. LogicalExpression logicalExpression = null;
  155. if (_cacheEnabled && !noCache)
  156. {
  157. try
  158. {
  159. Rwl.AcquireReaderLock(Timeout.Infinite);
  160. if (_compiledExpressions.ContainsKey(expression))
  161. {
  162. Trace.TraceInformation("Expression retrieved from cache: " + expression);
  163. var wr = _compiledExpressions[expression];
  164. logicalExpression = wr.Target as LogicalExpression;
  165. if (wr.IsAlive && logicalExpression != null)
  166. {
  167. return logicalExpression;
  168. }
  169. }
  170. }
  171. finally
  172. {
  173. Rwl.ReleaseReaderLock();
  174. }
  175. }
  176. if (logicalExpression == null)
  177. {
  178. var lexer = new NCalcLexer(new ANTLRStringStream(expression));
  179. var parser = new NCalcParser(new CommonTokenStream(lexer));
  180. logicalExpression = parser.ncalcExpression().value;
  181. if (parser.Errors != null && parser.Errors.Count > 0)
  182. {
  183. throw new EvaluationException(String.Join(Environment.NewLine, parser.Errors.ToArray()));
  184. }
  185. if (_cacheEnabled && !noCache)
  186. {
  187. try
  188. {
  189. Rwl.AcquireWriterLock(Timeout.Infinite);
  190. _compiledExpressions[expression] = new WeakReference(logicalExpression);
  191. }
  192. finally
  193. {
  194. Rwl.ReleaseWriterLock();
  195. }
  196. CleanCache();
  197. Trace.TraceInformation("Expression added to cache: " + expression);
  198. }
  199. }
  200. return logicalExpression;
  201. }
  202. #region Cache management
  203. private static bool _cacheEnabled = true;
  204. private static Dictionary<string, WeakReference> _compiledExpressions = new Dictionary<string, WeakReference>();
  205. private static readonly ReaderWriterLock Rwl = new ReaderWriterLock();
  206. public static bool CacheEnabled
  207. {
  208. get
  209. {
  210. return _cacheEnabled;
  211. }
  212. set
  213. {
  214. _cacheEnabled = value;
  215. if (!CacheEnabled)
  216. {
  217. // Clears cache
  218. _compiledExpressions = new Dictionary<string, WeakReference>();
  219. }
  220. }
  221. }
  222. /// <summary>
  223. /// Removes unused entries from cached compiled expression.
  224. /// </summary>
  225. private static void CleanCache()
  226. {
  227. var keysToRemove = new List<string>();
  228. try
  229. {
  230. Rwl.AcquireWriterLock(Timeout.Infinite);
  231. foreach (var de in _compiledExpressions)
  232. {
  233. if (!de.Value.IsAlive)
  234. {
  235. keysToRemove.Add(de.Key);
  236. }
  237. }
  238. foreach (var key in keysToRemove)
  239. {
  240. _compiledExpressions.Remove(key);
  241. Trace.TraceInformation("Cache entry released: " + key);
  242. }
  243. }
  244. finally
  245. {
  246. Rwl.ReleaseReaderLock();
  247. }
  248. }
  249. #endregion
  250. }
  251. }