public static IEnumerable <SearchItem> Print(SearchExpressionContext c) { var skipCount = 0; if (SearchExpression.GetFormatString(c.args[0], out var formatStr)) { skipCount++; } var outputValueFieldName = System.Guid.NewGuid().ToString("N"); foreach (var expr in c.args.Skip(skipCount)) { if (expr == null) { yield return(null); continue; } var str = new List <string>(); var dataSet = SearchExpression.ProcessValues(expr.Execute(c), outputValueFieldName, item => { var valueStr = SearchExpression.FormatItem(c.search, item, formatStr); str.Add(valueStr); return(valueStr); }); foreach (var item in dataSet) { yield return(item); } Debug.Log($"[{string.Join(",", str)}]"); } }
public static IEnumerable <SearchItem> Count(SearchExpressionContext c) { foreach (var arg in c.args) { yield return(SearchExpression.CreateItem(arg.Execute(c).Count(), c.ResolveAlias(arg, "Count"))); } }
public static IEnumerable <SearchItem> CurrentFolder(SearchExpressionContext c) { string currentSelectedPath = string.Empty; if (ProjectBrowser.s_LastInteractedProjectBrowser) { if (ProjectBrowser.s_LastInteractedProjectBrowser.IsTwoColumns()) { currentSelectedPath = ProjectBrowser.s_LastInteractedProjectBrowser.GetActiveFolderPath() ?? string.Empty; } else { currentSelectedPath = ProjectBrowser.GetSelectedPath() ?? string.Empty; var isFile = File.Exists(currentSelectedPath); var isDirectory = Directory.Exists(currentSelectedPath); if (!isDirectory && !isFile) { currentSelectedPath = string.Empty; } else if (isFile) { currentSelectedPath = Path.GetDirectoryName(currentSelectedPath) ?? string.Empty; } } } if (!string.IsNullOrEmpty(currentSelectedPath)) { currentSelectedPath = currentSelectedPath.ConvertSeparatorsToUnity(); } yield return(SearchExpression.CreateItem(currentSelectedPath, c.ResolveAlias("CurrentFolder"))); }
public SearchExpressionContext(SearchExpressionRuntime runtime, SearchExpression expression, SearchExpression[] args, SearchExpressionExecutionFlags flags) { this.runtime = runtime; this.expression = expression; this.flags = flags; this.args = args; }
internal static SearchExpression CreateStreamExpression(SearchExpression currentStream, string name = "<streamexpr>") { var exp = new SearchExpression(SearchExpressionType.Function, name.GetStringView(), new SearchExpressionEvaluator("StreamEvaluator", context => currentStream.Execute(context), SearchExpressionEvaluationHints.Default)); return(exp); }
internal static SearchItem CreateSearchExpressionItem(SearchExpression expr) { return(new SearchItem("") { data = expr }); }
static T Aggregate <T>(SearchItem item, string selector, T agg, Func <double, T, bool> comparer, Func <double, T, T> aggregator) where T : struct { if (item != null && SearchExpression.TryConvertToDouble(item, out var d, selector) && comparer(d, agg)) { return(aggregator(d, agg)); } return(agg); }
public static IEnumerable <SearchItem> ToNumber(SearchExpressionContext c) { return(c.args.SelectMany(e => e.Execute(c)).Select(item => { SearchExpression.TryConvertToDouble(item, out var value); return SearchExpression.CreateItem(value); })); }
public static IEnumerable <SearchItem> Selector(SearchExpressionContext c) { if (!c.expression.types.IsText()) { c.ThrowError($"Invalid selector"); } yield return(SearchExpression.CreateItem(c.ResolveAlias("Selector"), c.expression.innerText, c.expression.innerText.ToString())); }
public static IEnumerable <SearchItem> Text(SearchExpressionContext c) { if (c.args.Length == 0) { c.ThrowError("Text needs 1 argument"); } return(c.args.Select(e => SearchExpression.CreateItem(e.outerText.ToString()))); }
private static IEnumerable <SearchItem> SpreadExpression(string query, SearchExpressionContext c) { var spreaded = new List <SpreadContext>(); var toSpread = new List <SpreadContext>() { new SpreadContext(query.ToString(), c.ResolveAlias()) }; foreach (var e in c.args) { spreaded = new List <SpreadContext>(); foreach (var r in e.Execute(c)) { if (r != null) { foreach (var q in toSpread) { if (r.value == null) { continue; } var replacement = r.value.ToString(); if (replacement.LastIndexOf(' ') != -1) { replacement = '"' + replacement + '"'; } var pattern = @"[\[\{]?" + Regex.Escape(e.outerText.ToString()) + @"[\}\]]?"; spreaded.Add(new SpreadContext(Regex.Replace(q.query, pattern, replacement), alias: c.ResolveAlias(e, replacement))); } } else { yield return(null); } } toSpread = spreaded; } foreach (var s in spreaded) { if (c.flags.HasFlag(SearchExpressionExecutionFlags.Expand)) { yield return(SearchExpression.CreateSearchExpressionItem(s.query, s.alias)); } else { foreach (var r in RunQuery(c, s.query)) { yield return(r); } } } }
public static bool IsSelectorLiteral(SearchExpression selector) { if (selector.types.HasAny(SearchExpressionType.Text | SearchExpressionType.Selector)) { return(true); } if (selector.types.HasFlag(SearchExpressionType.QueryString) && selector.parameters.Length == 0) { return(true); } return(false); }
public static IEnumerable <SearchItem> Format(SearchExpressionContext c) { var skipCount = 0; if (SearchExpression.GetFormatString(c.args[0], out var formatStr)) { skipCount++; } var items = c.args.Skip(skipCount).SelectMany(e => e.Execute(c)); var dataSet = SearchExpression.ProcessValues(items, null, item => SearchExpression.FormatItem(c.search, item, formatStr)); return(dataSet); }
public static IEnumerable <SearchItem> Apply(SearchExpressionContext c) { if (c.args.Length == 0) { c.ThrowError("Invalid Arguments"); } var resultStreamExpr = c.args[0]; if (!resultStreamExpr.types.IsIterable()) { c.ThrowError($"No iterators", resultStreamExpr.outerText); } var exprs = new List <SearchExpression>(c.expression.parameters.Length); for (var i = 1; i < c.expression.parameters.Length; ++i) { var templateExpr = c.expression.parameters[i]; var currentStreamName = $"apply@stream#{i}"; var currentStream = EvaluatorUtils.CreateStreamExpression(resultStreamExpr, currentStreamName); var args = new[] { currentStream }.Concat(templateExpr.parameters).ToArray(); var innerText = templateExpr.innerText; var evaluator = templateExpr.evaluator; if (templateExpr.types.HasFlag(SearchExpressionType.Function)) { // Back patch arguments var restOfArguments = templateExpr.innerText.Substring(templateExpr.evaluator.name.Length + 1); innerText = $"{templateExpr.evaluator.name}{{{currentStreamName}, {restOfArguments}}}".GetStringView(); } else if (templateExpr.types.HasFlag(SearchExpressionType.Text)) { // String literal used as an evaluator name: var filterFunction = EvaluatorManager.GetEvaluatorByNameDuringEvaluation(templateExpr.innerText.ToString(), templateExpr.innerText, c); innerText = $"{templateExpr.innerText}{{{currentStreamName}}}".GetStringView(); evaluator = filterFunction; } else { c.ThrowError($"Bad argument type", templateExpr.outerText); } var patchedExpr = new SearchExpression(templateExpr.types, templateExpr.outerText, innerText, evaluator, args); exprs.Add(patchedExpr); resultStreamExpr = patchedExpr; } // Pull on the last element to start the evaluation chain return(exprs.Last().Execute(c)); }
public static void SetupColumns(SearchContext context, SearchExpression expression) { if (!(context.searchView is QuickSearch qs) || !(qs.resultView is TableView tv)) { return; } if (expression.evaluator.name == nameof(Evaluators.Select)) { var selectors = expression.parameters.Skip(1).Where(e => Evaluators.IsSelectorLiteral(e)); var tableViewFields = new List <SearchField>(selectors.Select(s => new SearchField(s.innerText.ToString(), s.alias.ToString()))); tv.SetupColumns(tableViewFields); } }
private SearchExpression ParseExpression(SearchContext context, SearchProvider expressionProvider) { try { return(SearchExpression.Parse(context)); } catch (SearchExpressionParseException ex) { var queryError = new SearchQueryError(ex.index, ex.length, ex.Message, context, expressionProvider, fromSearchQuery: true, SearchQueryErrorType.Error); context.AddSearchQueryError(queryError); return(null); } }
public static bool Check(SearchExpression e, SearchExpressionContext c) { var result = e.Execute(c); var count = result.Count(); if (count == 0) { return(false); } if (count == 1) { return(IsTrue(result.First())); } return(true); }
public static IEnumerable <SearchItem> Range(SearchExpressionContext c) { var range = new RangeDouble(); var alias = c.ResolveAlias("Range"); foreach (var sr in c.args[0].Execute(c)) { if (GetRange(sr, ref range)) { break; } else { yield return(null); } } if (!range.valid) { if (c.args.Length < 2) { c.ThrowError("No expression to end range"); } foreach (var sr in c.args[1].Execute(c)) { if (GetRange(sr, ref range)) { break; } else { yield return(null); } } } if (!range.valid) { c.ThrowError("Incomplete range"); } for (double d = range.start.Value; d < range.end.Value; d += 1d) { yield return(SearchExpression.CreateItem(d, alias)); } }
public static bool GetFormatString(SearchExpression expr, out string formatStr) { formatStr = null; if (expr.types.HasFlag(SearchExpressionType.Text)) { formatStr = expr.innerText.ToString(); return(true); } if (expr.types.HasFlag(SearchExpressionType.Selector)) { formatStr = expr.outerText.ToString(); return(true); } return(false); }
public static IEnumerable <SearchItem> If(SearchExpressionContext c) { if (c.args.Length < 2) { c.ThrowError("Not enough parameters for if"); } bool cond = false; foreach (var item in c.args[0].Execute(c)) { if (item == null) { yield return(null); } else { cond |= SearchExpression.IsTrue(item); if (!cond) { break; } } } if (cond) { foreach (var item in c.args[1].Execute(c)) { yield return(item); } } else if (c.args.Length == 2) { // Nothing to do. } else { foreach (var item in c.args[2].Execute(c)) { yield return(item); } } }
public static IEnumerable <SearchItem> Evaluate(SearchExpressionContext c, SearchExpression expression) { var concurrentList = new ConcurrentBag <SearchItem>(); var yieldSignal = new EventWaitHandle(false, EventResetMode.AutoReset); var task = Task.Run(() => { var enumerable = expression.Execute(c, SearchExpressionExecutionFlags.ThreadedEvaluation); foreach (var searchItem in enumerable) { if (searchItem != null) { concurrentList.Add(searchItem); yieldSignal.Set(); } } }); while (!concurrentList.IsEmpty || !TaskHelper.IsTaskFinished(task)) { if (!yieldSignal.WaitOne(0)) { if (concurrentList.IsEmpty) { Dispatcher.ProcessOne(); } yield return(null); } while (concurrentList.TryTake(out var item)) { yield return(item); } } if (task.IsFaulted && task.Exception?.InnerException != null) { if (task.Exception.InnerException is SearchExpressionEvaluatorException sex) { throw sex; } UnityEngine.Debug.LogException(task.Exception.InnerException); } }
public static IEnumerable <SearchItem> GroupBy(SearchExpressionContext c) { string selector = null; if (c.args.Length > 1) { selector = c.args[1].innerText.ToString(); } var outputValueFieldName = System.Guid.NewGuid().ToString("N"); var dataSet = SelectorManager.SelectValues(c.search, c.args[0].Execute(c), selector, outputValueFieldName); foreach (var _group in dataSet.GroupBy(item => item.GetValue(outputValueFieldName))) { var group = _group; var groupId = group.Key?.ToString() ?? $"group{++s_NextGroupId}"; if (c.HasFlag(SearchExpressionExecutionFlags.Expand)) { var evaluator = new SearchExpressionEvaluator(groupId, _ => group, SearchExpressionEvaluationHints.Default); var genExpr = new SearchExpression(SearchExpressionType.Group, groupId.GetStringView(), groupId.GetStringView(), (group.Key?.ToString() ?? groupId).GetStringView(), evaluator); yield return(EvaluatorUtils.CreateSearchExpressionItem(genExpr)); } else { SearchProvider groupProvider = null; foreach (var item in group) { if (groupProvider == null) { groupProvider = SearchUtils.CreateGroupProvider(item.provider, groupId, s_NextGroupId); } item.provider = groupProvider; yield return(item); } } } }
public static IEnumerable <SearchItem> Sum(SearchExpressionContext c) { var skipCount = 0; string selector = null; if (c.args[0].types.HasFlag(SearchExpressionType.Selector)) { skipCount++; selector = c.args[0].innerText.ToString(); } foreach (var arg in c.args.Skip(skipCount)) { var sum = 0d; foreach (var r in arg.Execute(c)) { sum = Aggregate(r, selector, sum, (d, _sum) => _sum + d); } yield return(SearchExpression.CreateItem(sum, c.ResolveAlias(arg, "Sum"))); } }
public static IEnumerable <SearchItem> Max(SearchExpressionContext c) { var skipCount = 0; string selector = null; if (c.args[0].types.HasFlag(SearchExpressionType.Selector)) { skipCount++; selector = c.args[0].innerText.ToString(); } foreach (var arg in c.args.Skip(skipCount)) { double max = double.MinValue; foreach (var r in arg.Execute(c)) { max = Aggregate(r, selector, max, (d, _max) => d > _max); } yield return(SearchExpression.CreateItem(max, c.ResolveAlias(arg, "Max"))); } }
public static IEnumerable <SearchItem> Avg(SearchExpressionContext c) { var skipCount = 0; string selector = null; if (c.args[0].types.HasFlag(SearchExpressionType.Selector)) { skipCount++; selector = c.args[0].innerText.ToString(); } foreach (var arg in c.args.Skip(skipCount)) { var avg = Average.Zero; foreach (var r in arg.Execute(c)) { avg = Aggregate(r, selector, avg, (d, _avg) => _avg.Add(d)); } yield return(SearchExpression.CreateItem(avg.result, c.ResolveAlias(arg, "Average"))); } }
static IEnumerable <SearchItem> Random(SearchExpressionContext c, SearchExpression e) { var set = new List <SearchItem>(); foreach (var item in e.Execute(c)) { if (item != null) { set.Add(item); } yield return(null); // Wait until we have all results. } var randomItem = Random(set); // Rename random item label if an alias is defined. if (c.ResolveAlias(e) is string alias) { randomItem.label = alias; } yield return(randomItem); }
public string ResolveAlias(SearchExpression expr, string defaultLabel = null) { if (expr != null && !expr.alias.IsNullOrEmpty()) { return(expr.alias.ToString()); } if (runtime.frames == null) { return(defaultLabel); } foreach (var f in runtime.frames) { if (!f.valid) { continue; } if (!f.expression.alias.IsNullOrEmpty()) { return(f.expression.alias.ToString()); } } return(defaultLabel); }
public static IEnumerable <SearchItem> Selection(SearchExpressionContext c) { var selection = TaskEvaluatorManager.EvaluateMainThread(() => { var instanceIds = UnityEditor.Selection.instanceIDs; return(instanceIds.Select(id => { string assetPath = AssetDatabase.GetAssetPath(id); return new SelectionResult(id, assetPath); }).ToList()); }); foreach (var selectionResult in selection) { if (string.IsNullOrEmpty(selectionResult.assetPath)) { yield return(SearchExpression.CreateItem(selectionResult.instanceId, c.ResolveAlias("Selection"))); } else { yield return(SearchExpression.CreateItem(selectionResult.assetPath, c.ResolveAlias("Selection"))); } } }
public static IEnumerable <SearchItem> Constant(SearchExpressionContext c) { if (c.expression.types.HasAny(SearchExpressionType.Function)) { using (c.runtime.Push(c.args[0], c.args.Skip(1))) yield return(Constant(c.runtime.current).First()); } else if (c.expression.types.HasAny(SearchExpressionType.Number)) { yield return(SearchExpression.CreateItem(c.expression.GetNumberValue(), c.expression.alias.ToString())); } else if (c.expression.types.HasAny(SearchExpressionType.Text | SearchExpressionType.Keyword)) { yield return(SearchExpression.CreateItem(c.expression.innerText.ToString(), c.expression.alias.ToString())); } else if (c.expression.types.HasAny(SearchExpressionType.Boolean)) { yield return(SearchExpression.CreateItem(c.expression.GetBooleanValue(), c.expression.alias.ToString())); } else { c.ThrowError($"Invalid constant expression"); } }
public static IEnumerable <SearchItem> IsTrue(SearchExpressionContext c) { foreach (var e in c.args) { bool isTrue = false; foreach (var item in e.Execute(c)) { if (item == null) { yield return(null); } else { isTrue |= SearchExpression.IsTrue(item); if (!isTrue) { break; } } } yield return(SearchExpression.CreateItem(isTrue, c.ResolveAlias(e, "IsTrue"))); } }