/
ExpressionBuilderGraphExtensions.cs
1371 lines (1223 loc) · 59.5 KB
/
ExpressionBuilderGraphExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using Bonsai.Dag;
using System.Linq.Expressions;
using System.Reactive.Disposables;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Concurrency;
using System.ComponentModel;
using Bonsai.Properties;
using System.Globalization;
namespace Bonsai.Expressions
{
/// <summary>
/// Provides a set of static methods for serializing, building and otherwise manipulating
/// expression builder workflows.
/// </summary>
public static class ExpressionBuilderGraphExtensions
{
/// <summary>
/// Generates an <see cref="Expression"/> node from a collection of zero or more
/// input arguments. The result can be chained with other builders in a workflow.
/// </summary>
/// <param name="builder">The expression builder.</param>
/// <param name="arguments">
/// A collection of <see cref="Expression"/> nodes that represents the input arguments.
/// </param>
/// <returns>An <see cref="Expression"/> tree node.</returns>
public static Expression Build(this ExpressionBuilder builder, params Expression[] arguments)
{
return builder.Build(arguments);
}
/// <summary>
/// Determines whether the specified <see cref="ExpressionBuilder"/> represents a build dependency.
/// </summary>
/// <param name="builder">The <see cref="ExpressionBuilder"/> to test.</param>
/// <returns>
/// true if the specified <see cref="ExpressionBuilder"/> represents a
/// build dependency; otherwise, false.
/// </returns>
public static bool IsBuildDependency(this ExpressionBuilder builder)
{
var element = ExpressionBuilder.GetWorkflowElement(builder);
return ExpressionBuilder.IsBuildDependency(element as IArgumentBuilder);
}
/// <summary>
/// Sets the value of a workflow property to a different value.
/// </summary>
/// <param name="source">The expression builder workflow for which to set the property.</param>
/// <param name="name">The name of the workflow property.</param>
/// <param name="value">The new value.</param>
public static void SetWorkflowProperty(this ExpressionBuilderGraph source, string name, object value)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("The workflow property name cannot be null or whitespace.", nameof(name));
}
var memberChain = name.Split(new[] { ExpressionHelper.MemberSeparator }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < memberChain.Length - 1; i++)
{
var workflowBuilders = (from node in source
let builder = ExpressionBuilder.Unwrap(node.Value) as WorkflowExpressionBuilder
where builder != null && builder.Name == memberChain[i]
select builder).ToArray();
if (workflowBuilders.Length == 0)
{
throw new KeyNotFoundException(string.Format(Resources.Exception_PropertyNotFound, name));
}
else if (workflowBuilders.Length > 1)
{
throw new InvalidOperationException(string.Format(
Resources.Exception_AmbiguousNamedElement,
string.Join(ExpressionHelper.MemberSeparator, memberChain, 0, i + 1)));
}
source = workflowBuilders[0].Workflow;
}
name = memberChain[memberChain.Length - 1];
var propertyDescriptor = TypeDescriptor.GetProperties(source).Find(name, false);
if (propertyDescriptor == null)
{
throw new KeyNotFoundException(string.Format(Resources.Exception_PropertyNotFound, name));
}
if (value != null && value.GetType() != propertyDescriptor.PropertyType)
{
value = propertyDescriptor.Converter.ConvertFrom(null, CultureInfo.InvariantCulture, value);
}
propertyDescriptor.SetValue(source, value);
}
#region Error Handling
static WorkflowException BuildRuntimeExceptionStack(string message, ExpressionBuilder builder, Exception innerException, IEnumerable<ExpressionBuilder> callStack)
{
var exception = new WorkflowRuntimeException(message, builder, innerException);
foreach (var caller in callStack)
{
exception = new WorkflowRuntimeException(message, caller, exception);
}
return exception;
}
/// <summary>
/// Redirects any build or execution errors signaled by <see cref="InspectBuilder"/> nodes in
/// the specified expression builder workflow into an empty observable sequence.
/// </summary>
/// <param name="source">The expression builder workflow for which to redirect errors.</param>
/// <returns>
/// An observable sequence with no elements except for error termination messages.
/// </returns>
[Obsolete]
public static IObservable<Unit> InspectErrors(this ExpressionBuilderGraph source)
{
return InspectErrors(source, Enumerable.Empty<ExpressionBuilder>())
.Merge(Scheduler.Immediate)
.SelectMany(xs => Observable.Throw(xs, Unit.Default));
}
/// <summary>
/// Redirects any build or execution errors signaled by <see cref="InspectBuilder"/> nodes in
/// the specified expression builder workflow into a single observable sequence.
/// </summary>
/// <param name="source">The expression builder workflow for which to redirect errors.</param>
/// <returns>
/// An observable sequence where all elements are errors raised by
/// <see cref="InspectBuilder"/> nodes.
/// </returns>
public static IObservable<Exception> InspectErrorsEx(this ExpressionBuilderGraph source)
{
return InspectErrors(source, Enumerable.Empty<ExpressionBuilder>()).Merge(Scheduler.Immediate);
}
static IEnumerable<IObservable<Exception>> InspectErrors(this ExpressionBuilderGraph source, IEnumerable<ExpressionBuilder> callStack)
{
foreach (var builder in from node in source
let inspectBuilder = node.Value as InspectBuilder
where inspectBuilder != null && inspectBuilder.ObservableType != null
select inspectBuilder)
{
var inspectBuilder = builder;
yield return inspectBuilder.ErrorEx.Select(xs => BuildRuntimeExceptionStack(xs.Message, inspectBuilder, xs, callStack));
if (inspectBuilder.Builder is IWorkflowExpressionBuilder workflowExpression && workflowExpression.Workflow != null)
{
foreach (var error in workflowExpression.Workflow.InspectErrors(Enumerable.Repeat(inspectBuilder, 1).Concat(callStack)))
{
yield return error;
}
}
}
}
#endregion
/// <summary>
/// Generates an expression tree from the specified expression builder workflow.
/// </summary>
/// <param name="source">
/// The expression builder workflow for which to generate the expression tree.
/// </param>
/// <returns>
/// An <see cref="Expression"/> tree representing the evaluation of the full
/// expression builder workflow.
/// </returns>
public static Expression Build(this ExpressionBuilderGraph source)
{
return Build(source, (ExpressionBuilder)null);
}
/// <summary>
/// Generates an expression tree from the specified expression builder workflow
/// evaluated up to the specified build target.
/// </summary>
/// <param name="source">
/// The expression builder workflow for which to generate the expression tree.
/// </param>
/// <param name="buildTarget">
/// The expression builder node up to which the workflow will be evaluated.
/// </param>
/// <returns>
/// An <see cref="Expression"/> tree representing the evaluation of the expression
/// builder workflow up to the specified <paramref name="buildTarget"/>.
/// </returns>
public static Expression Build(this ExpressionBuilderGraph source, ExpressionBuilder buildTarget)
{
return Build(source, buildTarget, Enumerable.Empty<Expression>());
}
/// <summary>
/// Generates an expression tree from the specified expression builder workflow and array
/// of build arguments.
/// </summary>
/// <param name="source">
/// The expression builder workflow for which to generate the expression tree.
/// </param>
/// <param name="buildArguments">
/// The array of <see cref="Expression"/> objects to be assigned as workflow input arguments
/// in the context of generating the expression tree.
/// </param>
/// <returns>
/// An <see cref="Expression"/> tree representing the evaluation of the full
/// expression builder workflow.
/// </returns>
public static Expression Build(this ExpressionBuilderGraph source, params Expression[] buildArguments)
{
return Build(source, null, (IEnumerable<Expression>)buildArguments);
}
/// <summary>
/// Generates an expression tree from the specified expression builder workflow and a sequence
/// of build arguments.
/// </summary>
/// <param name="source">
/// The expression builder workflow for which to generate the expression tree.
/// </param>
/// <param name="buildArguments">
/// The sequence of <see cref="Expression"/> objects to be assigned as workflow input arguments
/// in the context of generating the expression tree.
/// </param>
/// <returns>
/// An <see cref="Expression"/> tree representing the evaluation of the full
/// expression builder workflow.
/// </returns>
public static Expression Build(this ExpressionBuilderGraph source, IEnumerable<Expression> buildArguments)
{
return Build(source, null, buildArguments);
}
/// <summary>
/// Generates an expression tree from the specified expression builder workflow and array of
/// build arguments, evaluated up to the specified build target.
/// </summary>
/// <param name="source">
/// The expression builder workflow for which to generate the expression tree.
/// </param>
/// <param name="buildTarget">
/// The expression builder node up to which the workflow will be evaluated.
/// </param>
/// <param name="buildArguments">
/// The array of <see cref="Expression"/> objects to be assigned as workflow input arguments
/// in the context of generating the expression tree.
/// </param>
/// <returns>
/// An <see cref="Expression"/> tree representing the evaluation of the expression
/// builder workflow up to the specified <paramref name="buildTarget"/>.
/// </returns>
public static Expression Build(this ExpressionBuilderGraph source, ExpressionBuilder buildTarget, params Expression[] buildArguments)
{
return Build(source, buildTarget, (IEnumerable<Expression>)buildArguments);
}
/// <summary>
/// Generates an expression tree from the specified expression builder workflow and a sequence of
/// build arguments, evaluated up to the specified build target.
/// </summary>
/// <param name="source">
/// The expression builder workflow for which to generate the expression tree.
/// </param>
/// <param name="buildTarget">
/// The expression builder node up to which the workflow will be evaluated.
/// </param>
/// <param name="buildArguments">
/// The sequence of <see cref="Expression"/> objects to be assigned as workflow input arguments
/// in the context of generating the expression tree.
/// </param>
/// <returns>
/// An <see cref="Expression"/> tree representing the evaluation of the expression
/// builder workflow up to the specified <paramref name="buildTarget"/>.
/// </returns>
public static Expression Build(this ExpressionBuilderGraph source, ExpressionBuilder buildTarget, IEnumerable<Expression> buildArguments)
{
// Add/remove build dependencies
var buildContext = new BuildContext(buildTarget);
using (var dependencies = AddBuildDependencies(source, buildContext))
{
return BuildNested(source, buildArguments, buildContext);
}
}
#region Argument Lists
class ArgumentList : IEnumerable<Expression>
{
readonly SortedList<int, ExpressionArgument> arguments = new SortedList<int, ExpressionArgument>();
internal static readonly ArgumentList Empty = new ArgumentList();
public int Count { get; private set; }
public void Add(int key, ExpressionArgument argument)
{
arguments.Add(key, argument);
if (argument.NestedArguments != null) Count += argument.NestedArguments.Length;
else Count++;
}
public IEnumerator<Expression> GetEnumerator()
{
foreach (var argument in arguments.Values)
{
if (argument.NestedArguments != null)
{
foreach (var nestedArgument in argument.NestedArguments)
{
yield return nestedArgument;
}
}
else yield return argument.Expression;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
struct ExpressionArgument
{
public Expression Expression;
public Expression[] NestedArguments;
}
static ArgumentList GetArgumentList(
Dictionary<ExpressionBuilder, ArgumentList> argumentLists,
ExpressionBuilder builder)
{
ArgumentList argumentList;
if (argumentLists.TryGetValue(builder, out argumentList))
{
argumentLists.Remove(builder);
return argumentList;
}
return ArgumentList.Empty;
}
static void UpdateArgumentList(
Dictionary<ExpressionBuilder, ArgumentList> argumentLists,
Edge<ExpressionBuilder, ExpressionBuilderArgument> successor,
Expression expression)
{
ExpressionArgument argument;
argument.Expression = expression;
var disable = expression as DisableExpression;
argument.NestedArguments = disable?.Arguments;
UpdateArgumentList(argumentLists, successor, argument);
}
static void UpdateArgumentList(
Dictionary<ExpressionBuilder, ArgumentList> argumentLists,
Edge<ExpressionBuilder, ExpressionBuilderArgument> successor,
ExpressionArgument argument)
{
if (!argumentLists.TryGetValue(successor.Target.Value, out ArgumentList argumentList))
{
argumentList = new ArgumentList();
argumentLists.Add(successor.Target.Value, argumentList);
}
try { argumentList.Add(successor.Label.Index, argument); }
catch (ArgumentException e)
{
throw new WorkflowBuildException(e.Message, successor.Target.Value, e);
}
}
static void RegisterPropertyName(ExpressionBuilder builder, ExternalizedMapping mapping, ref HashSet<string> externalizedProperties)
{
if (externalizedProperties == null) externalizedProperties = new HashSet<string>();
var propertyName = mapping.ExternalizedName;
if (!externalizedProperties.Add(propertyName))
{
throw new WorkflowBuildException(string.Format("A workflow property with the name '{0}' already exists.", propertyName), builder);
}
}
#endregion
#region Dependency Preprocessor
class DependencyNode
{
public DependencyElement Publish;
public List<DependencyElement> Subscribe = new List<DependencyElement>();
}
class DependencyLink
{
public string Name;
public ExpressionBuilderGraph Workflow;
public Node<ExpressionBuilder, ExpressionBuilderArgument> Publish;
public Node<ExpressionBuilder, ExpressionBuilderArgument> Subscribe;
public DependencyLink(
string name,
ExpressionBuilderGraph workflow,
Node<ExpressionBuilder, ExpressionBuilderArgument> publish,
Node<ExpressionBuilder, ExpressionBuilderArgument> subscribe)
{
Name = name;
Workflow = workflow;
Publish = publish;
Subscribe = subscribe;
}
}
static DependencyNode GetOrCreateDependency(ref Dictionary<string, DependencyNode> dependencies, string name)
{
if (dependencies == null)
{
dependencies = new Dictionary<string, DependencyNode>();
}
if (!dependencies.TryGetValue(name, out DependencyNode dependency))
{
dependency = new DependencyNode();
dependencies.Add(name, dependency);
}
return dependency;
}
class DependencyElement
{
public ExpressionBuilder Element;
public Node<ExpressionBuilder, ExpressionBuilderArgument> Node;
public DependencyElement InnerDependency;
public DependencyElement(ExpressionBuilder element, Node<ExpressionBuilder, ExpressionBuilderArgument> node)
: this(element, node, null)
{
}
public DependencyElement(ExpressionBuilder element, Node<ExpressionBuilder, ExpressionBuilderArgument> node, DependencyElement innerDependency)
{
Element = element;
Node = node;
InnerDependency = innerDependency;
}
}
static IEnumerable<DependencyElement> SelectDependencyElements(ExpressionBuilderGraph source, IBuildContext buildContext)
{
foreach (var node in source)
{
var builder = node.Value;
var element = ExpressionBuilder.Unwrap(builder);
if (element is IGroupWorkflowBuilder groupBuilder)
{
try { groupBuilder.BuildContext = buildContext; }
catch (Exception e)
{
throw new WorkflowBuildException(e.Message, builder, e);
}
try
{
var workflow = groupBuilder.Workflow;
if (workflow == null) continue;
var dependencyContext = groupBuilder is IncludeWorkflowBuilder includeBuilder ? new IncludeContext(buildContext, includeBuilder.Path) : buildContext;
var enumerator = SelectDependencyElements(workflow, dependencyContext).GetEnumerator();
while (true)
{
try { if (!enumerator.MoveNext()) break; }
catch (Exception e)
{
throw new WorkflowBuildException(e.Message, builder, e);
}
var dependencyElement = enumerator.Current;
yield return new DependencyElement(dependencyElement.Element, node, dependencyElement);
}
}
finally { groupBuilder.BuildContext = null; }
}
else yield return new DependencyElement(element, node);
}
}
static DependencyLink CreateDependencyLink(string name, ExpressionBuilderGraph workflow, DependencyElement publish, DependencyElement subscribe)
{
var publishNode = publish?.Node;
var subscribeNode = subscribe?.Node;
if (publishNode == subscribeNode && publishNode != null)
{
var group = (IGroupWorkflowBuilder)ExpressionBuilder.Unwrap(publishNode.Value);
return CreateDependencyLink(name, group.Workflow, publish.InnerDependency, subscribe.InnerDependency);
}
else return new DependencyLink(name, workflow, publishNode, subscribeNode);
}
static WorkflowBuildException BuildDependencyLinkExceptionStack(Exception innerException, DependencyElement dependencyElement)
{
if (dependencyElement.InnerDependency != null)
{
innerException = BuildDependencyLinkExceptionStack(innerException, dependencyElement.InnerDependency);
}
return new WorkflowBuildException(innerException.Message, dependencyElement.Node.Value, innerException);
}
static IEnumerable<DependencyLink> FindBuildDependencies(ExpressionBuilderGraph source, IBuildContext buildContext)
{
Dictionary<string, DependencyNode> dependencies = null;
foreach (var dependencyElement in SelectDependencyElements(source, buildContext))
{
var node = dependencyElement.Node;
var workflowElement = dependencyElement.Element;
if (workflowElement is SubjectExpressionBuilder subjectBuilder && !string.IsNullOrEmpty(subjectBuilder.Name))
{
// Connect to any existing subscribers
var dependency = GetOrCreateDependency(ref dependencies, subjectBuilder.Name);
if (dependency.Publish == null)
{
dependency.Publish = dependencyElement;
foreach (var subscriber in dependency.Subscribe)
{
yield return CreateDependencyLink(subjectBuilder.Name, source, dependencyElement, subscriber);
}
}
}
if (workflowElement is IRequireSubject requireSubject && !string.IsNullOrEmpty(requireSubject.Name))
{
// Connect to publisher (if available)
var dependency = GetOrCreateDependency(ref dependencies, requireSubject.Name);
if (dependency.Publish != null)
{
yield return CreateDependencyLink(requireSubject.Name, source, dependency.Publish, dependencyElement);
}
else dependency.Subscribe.Add(dependencyElement);
}
if (workflowElement is WorkflowExpressionBuilder workflowBuilder)
{
// Recurse through nested workflows and handle any unsatisfied dependencies
var enumerator = FindBuildDependencies(workflowBuilder.Workflow, buildContext).GetEnumerator();
while (true)
{
try { if (!enumerator.MoveNext()) break; }
catch (Exception e)
{
throw BuildDependencyLinkExceptionStack(e, dependencyElement);
}
var link = enumerator.Current;
if (link.Publish == null)
{
var dependency = GetOrCreateDependency(ref dependencies, link.Name);
if (dependency.Publish != null)
{
yield return CreateDependencyLink(link.Name, source, dependency.Publish, dependencyElement);
}
else dependency.Subscribe.Add(dependencyElement);
}
else yield return link;
}
}
}
if (dependencies != null)
{
// Emit unsatisfied link dependencies
foreach (var dependency in dependencies)
{
if (dependency.Value.Publish != null) continue;
foreach (var subscriber in dependency.Value.Subscribe)
{
yield return CreateDependencyLink(dependency.Key, source, null, subscriber);
}
}
}
}
class BuildDependency
{
public readonly ExpressionBuilderGraph Workflow;
public readonly Node<ExpressionBuilder, ExpressionBuilderArgument> Source;
public readonly Edge<ExpressionBuilder, ExpressionBuilderArgument> Edge;
public BuildDependency(DependencyLink link)
{
Workflow = link.Workflow;
Source = link.Publish;
Edge = Workflow.AddEdge(link.Publish, link.Subscribe, null);
}
}
static IDisposable AddBuildDependencies(ExpressionBuilderGraph source, IBuildContext buildContext)
{
var dependencies = new List<BuildDependency>();
var disposable = Disposable.Create(() =>
{
foreach (var dependency in dependencies)
{
dependency.Workflow.RemoveEdge(dependency.Source, dependency.Edge);
}
});
try
{
foreach (var link in FindBuildDependencies(source, buildContext).Where(link => link.Publish != null && link.Subscribe != null))
{
var dependency = new BuildDependency(link);
dependencies.Add(dependency);
}
return disposable;
}
catch
{
disposable.Dispose();
throw;
}
}
#endregion
#region Cycle Detection
static DependencyElement FindCyclicalDependency(ExpressionBuilderGraph source, IBuildContext buildContext)
{
return (from dependency in SelectDependencyElements(source, buildContext)
where dependency.Element is SubscribeSubject
from successor in dependency.Node.Successors
where successor.Target.DepthFirstSearch().Contains(dependency.Node)
select dependency)
.FirstOrDefault();
}
static Exception CreateDependencyException(string message, DependencyElement element)
{
var stack = new Stack<DependencyElement>();
while (element != null)
{
stack.Push(element);
element = element.InnerDependency;
}
var exception = default(Exception);
foreach (var dependency in stack)
{
exception = new WorkflowBuildException(message, dependency.Node.Value, exception);
}
return exception;
}
#endregion
#region Nested Workflows
internal static IEnumerable<WorkflowInputBuilder> GetNestedParameters(this ExpressionBuilderGraph source)
{
return from node in source
let inputBuilder = ExpressionBuilder.Unwrap(node.Value) as WorkflowInputBuilder
where inputBuilder != null
orderby inputBuilder.Index ascending
select inputBuilder;
}
internal static Expression BuildNested(this ExpressionBuilderGraph source, IEnumerable<Expression> arguments, IBuildContext buildContext)
{
var parameters = source.GetNestedParameters();
foreach (var assignment in parameters.Zip(arguments, (parameter, argument) => new { parameter, argument }))
{
assignment.parameter.Source = assignment.argument;
}
try { return source.Build(buildContext); }
catch
{
foreach (var node in source)
{
if (node.Value is InspectBuilder builder)
{
builder.ResetVisualizerMappings();
}
}
throw;
}
finally
{
foreach (var parameter in parameters)
{
parameter.Source = null;
}
}
}
#endregion
#region Build Sequence
internal static Expression Build(this ExpressionBuilderGraph source, IBuildContext buildContext)
{
Expression output = null;
HashSet<string> externalizedProperties = null;
var argumentLists = new Dictionary<ExpressionBuilder, ArgumentList>();
var dependencyLists = new Dictionary<ExpressionBuilder, ArgumentList>();
var edgeCollection = new List<Edge<ExpressionBuilder, ExpressionBuilderArgument>>();
var componentConnections = new List<Expression>();
var multicastMap = new List<MulticastScope>();
var connections = new List<Expression>();
if (!TopologicalSort.TrySort(source, out IEnumerable<DirectedGraph<ExpressionBuilder, ExpressionBuilderArgument>> buildOrder))
{
var cyclicalDependency = FindCyclicalDependency(source, buildContext);
if (cyclicalDependency == null) throw new WorkflowBuildException("The workflow contains unspecified cyclical build dependencies.");
var name = ((SubscribeSubject)cyclicalDependency.Element).Name;
var message = string.Format("The specified variable '{0}' is defined in terms of itself.", name);
throw CreateDependencyException(message, cyclicalDependency);
}
foreach (var component in buildOrder)
{
Expression workflowOutput = null;
foreach (var node in component)
{
Expression expression;
var builder = node.Value;
var arguments = GetArgumentList(argumentLists, builder);
// Propagate build target in case of a nested workflow
var workflowElement = ExpressionBuilder.Unwrap(builder);
var requireBuildContext = workflowElement as IRequireBuildContext;
if (requireBuildContext != null)
{
try { requireBuildContext.BuildContext = buildContext; }
catch (Exception e)
{
throw new WorkflowBuildException(e.Message, builder, e);
}
}
var argumentRange = builder.ArgumentRange;
if (argumentRange == null)
{
throw new WorkflowBuildException("Argument range not set in expression builder node.", builder);
}
if (arguments.Count < argumentRange.LowerBound)
{
throw new WorkflowBuildException(string.Format(Resources.Exception_UnsupportedMinArgumentCount, argumentRange.LowerBound), builder);
}
if (arguments.Count > argumentRange.UpperBound)
{
throw new WorkflowBuildException(string.Format(Resources.Exception_UnsupportedMaxArgumentCount, argumentRange.UpperBound), builder);
}
var externalizedBuilder = workflowElement as IExternalizedMappingBuilder;
if (externalizedBuilder != null)
{
foreach (var property in externalizedBuilder.GetExternalizedProperties())
{
RegisterPropertyName(builder, property, ref externalizedProperties);
}
}
try
{
expression = builder.Build(arguments);
}
catch (Exception e)
{
throw new WorkflowBuildException(e.Message, builder, e);
}
finally
{
if (requireBuildContext != null)
{
requireBuildContext.BuildContext = null;
}
}
// Merge build dependencies
var reducible = ExpressionBuilder.IsReducible(expression);
var buildDependencies = GetArgumentList(dependencyLists, builder);
if (buildDependencies.Count > 0 && reducible)
{
expression = ExpressionBuilder.MergeBuildDependencies(expression, buildDependencies);
}
// Check if build target was reached
if (builder == buildContext.BuildTarget)
{
buildContext.BuildResult = expression;
}
if (buildContext.BuildResult != null)
{
return expression;
}
// Filter disabled successors for property mapping nodes
var argumentBuilder = workflowElement as IArgumentBuilder;
var propertyMappingBuilder = ExpressionBuilder.IsBuildDependency(argumentBuilder);
IList<Edge<ExpressionBuilder, ExpressionBuilderArgument>> nodeSuccessors;
if (propertyMappingBuilder)
{
edgeCollection.Clear();
edgeCollection.AddRange(node.Successors.Where(edge => !(ExpressionBuilder.Unwrap(edge.Target.Value) is DisableBuilder)));
nodeSuccessors = edgeCollection;
}
else nodeSuccessors = node.Successors;
// Remove all closing scopes
var disable = expression as DisableExpression;
var successorCount = requireBuildContext != null
? nodeSuccessors.Count(edge => edge.Label != null)
: nodeSuccessors.Count;
multicastMap.RemoveAll(scope =>
{
var referencesRemoved = scope.References.RemoveAll(reference => reference == builder);
if (scope.References.Count == 0 && disable == null)
{
try
{
expression = scope.Close(expression);
return true;
}
catch (Exception e)
{
throw new WorkflowBuildException(e.Message, builder, e);
}
}
if (referencesRemoved > 0)
{
var expandedArguments = disable?.Arguments.Skip(1).GetEnumerator();
do
{
// If there are no successors, or the expression is a disabled build dependency, this scope should never close
if (successorCount == 0 || expression == DisconnectExpression.Instance) scope.References.Add(null);
else scope.References.AddRange(nodeSuccessors
.Where(successor => successor.Label != null)
.Select(successor => successor.Target.Value));
}
while (expandedArguments != null && expandedArguments.MoveNext());
}
return false;
});
// Evaluate irreducible extension expressions
if (!reducible)
{
// Disconnect disabled build dependencies from their immediate successors
if (expression == DisconnectExpression.Instance)
{
componentConnections.AddRange(arguments);
continue;
}
// Validate externalized properties
if (externalizedBuilder != null)
{
var argument = expression;
foreach (var successor in nodeSuccessors)
{
var successorElement = ExpressionBuilder.GetWorkflowElement(successor.Target.Value);
var successorInstance = Expression.Constant(successorElement);
foreach (var property in externalizedBuilder.GetExternalizedProperties())
{
try { argument = ExpressionBuilder.BuildPropertyMapping(argument, successorInstance, property.Name); }
catch (Exception e)
{
throw new WorkflowBuildException(e.Message, builder, e);
}
}
}
continue;
}
// Do not generate output sequences if the result expression is empty
if (expression == EmptyExpression.Instance)
{
continue;
}
// Do not generate output or successor sequences if the result expression type is void
if (successorCount > 0 && disable == null)
{
try { if (expression.Type == typeof(void)) continue; }
catch (Exception e)
{
throw new WorkflowBuildException(e.Message, builder, e);
}
}
}
if (workflowElement is WorkflowOutputBuilder outputBuilder)
{
if (successorCount > 0)
{
throw new WorkflowBuildException("The workflow output must be a terminal node.", builder);
}
if (workflowOutput != null || output != null)
{
throw new WorkflowBuildException("Workflows cannot have more than one output.", builder);
}
workflowOutput = expression;
continue;
}
if (successorCount > 1 && reducible)
{
// Start a new multicast scope
MulticastBranchBuilder multicastBuilder;
if (propertyMappingBuilder)
{
// Property mappings get replayed across subscriptions
multicastBuilder = new ReplayLatestBranchBuilder();
}
else multicastBuilder = new PublishBranchBuilder();
expression = multicastBuilder.Build(expression);
// Ensure publish/subscribe subject dependencies are not multicast
var multicastScope = new MulticastScope(multicastBuilder);
multicastScope.References.AddRange(nodeSuccessors
.Where(successor => successor.Label != null)
.Select(successor => successor.Target.Value));
multicastMap.Insert(0, multicastScope);
}
foreach (var successor in nodeSuccessors)
{
if (successor.Label == null) continue;
var argument = expression;
var buildDependency = false;
if (argumentBuilder != null)
{
try { buildDependency = !argumentBuilder.BuildArgument(argument, successor, out argument); }
catch (Exception e)
{
throw new WorkflowBuildException(e.Message, builder, e);
}
}
if (buildDependency)
{
UpdateArgumentList(dependencyLists, successor, argument);
}
else UpdateArgumentList(argumentLists, successor, argument);
}
if (successorCount == 0)
{
if (disable != null) componentConnections.AddRange(disable.Arguments);
else componentConnections.Add(expression);
}
}
// Prune disabled multicast branches from output
multicastMap.RemoveAll(scope =>
{
var index = -1;
int? argumentIndex = null;
var branchesRemoved = componentConnections.RemoveAll(connection =>
{
index++;
if (connection is MulticastBranchExpression branchExpression &&
branchExpression == scope.MulticastBuilder.BranchExpression)
{
argumentIndex ??= index;
return true;
}
return false;
});
var activeBranches = scope.References.Count - branchesRemoved;
if (activeBranches > 1) return false;
if (activeBranches == 1) scope.MulticastBuilder.BranchExpression.Cancel();
if (activeBranches == 0) componentConnections.Insert(argumentIndex.Value, scope.MulticastBuilder.Source);
return true;
});
var componentOutput = ExpressionBuilder.BuildOutput(workflowOutput, componentConnections);
multicastMap.RemoveAll(scope =>
{
componentOutput = scope.Close(componentOutput);
return true;
});
if (workflowOutput != null) output = componentOutput;
else connections.Add(componentOutput);
multicastMap.Clear();
componentConnections.Clear();