-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
VisualBasicHelper.cs
1737 lines (1531 loc) · 74.8 KB
/
VisualBasicHelper.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
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace Microsoft.VisualBasic.Activities
{
using System;
using System.Activities;
using System.Activities.ExpressionParser;
using System.Activities.Expressions;
using System.CodeDom;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime;
using System.Runtime.Collections;
using System.Text;
using System.Threading;
using Microsoft.Compiler.VisualBasic;
using System.Collections.ObjectModel;
using Microsoft.VisualBasic.CompilerServices;
using System.Security;
using System.Security.Permissions;
class VisualBasicHelper
{
internal static string Language
{
get
{
return "VB";
}
}
// the following assemblies are provided to the compiler by default
// items are public so the decompiler knows which assemblies it doesn't need to reference for interfaces
public static readonly HashSet<Assembly> DefaultReferencedAssemblies = new HashSet<Assembly>
{
typeof(int).Assembly, // mscorlib
typeof(CodeTypeDeclaration).Assembly, // System
typeof(Expression).Assembly, // System.Core
typeof(Microsoft.VisualBasic.Strings).Assembly, // Microsoft.VisualBasic
typeof(Activity).Assembly // System.Activities
};
public static AssemblyName GetFastAssemblyName(Assembly assembly)
{
return AssemblyReference.GetFastAssemblyName(assembly);
}
// cache for type's all base types, interfaces, generic arguments, element type
// HopperCache is a psuedo-MRU cache
const int typeReferenceCacheMaxSize = 100;
static object typeReferenceCacheLock = new object();
static HopperCache typeReferenceCache = new HopperCache(typeReferenceCacheMaxSize, false);
static ulong lastTimestamp = 0;
// Cache<(expressionText+ReturnType+Assemblies+Imports), LambdaExpression>
// LambdaExpression represents raw ExpressionTrees right out of the vb hosted compiler
// these raw trees are yet to be rewritten with appropriate Variables
const int rawTreeCacheMaxSize = 128;
static object rawTreeCacheLock = new object();
[Fx.Tag.SecurityNote(Critical = "Critical because it caches objects created under a demand for FullTrust.")]
[SecurityCritical]
static HopperCache rawTreeCache;
static HopperCache RawTreeCache
{
[Fx.Tag.SecurityNote(Critical = "Critical because it access critical member rawTreeCache.")]
[SecurityCritical]
get
{
if (rawTreeCache == null)
{
rawTreeCache = new HopperCache(rawTreeCacheMaxSize, false);
}
return rawTreeCache;
}
}
const int HostedCompilerCacheSize = 10;
[Fx.Tag.SecurityNote(Critical = "Critical because it holds HostedCompilerWrappers which hold HostedCompiler instances, which require FullTrust.")]
[SecurityCritical]
static Dictionary<HashSet<Assembly>, HostedCompilerWrapper> HostedCompilerCache;
[Fx.Tag.SecurityNote(Critical = "Critical because it creates Microsoft.Compiler.VisualBasic.HostedCompiler, which is in a non-APTCA assembly, and thus has a LinkDemand.",
Safe = "Safe because it puts the HostedCompiler instance into the HostedCompilerCache member, which is SecurityCritical and we are demanding FullTrust.")]
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
static HostedCompilerWrapper GetCachedHostedCompiler(HashSet<Assembly> assemblySet)
{
if (HostedCompilerCache == null)
{
// we don't want to newup a Dictionary everytime GetCachedHostedCompiler is called only to find out the cache is already initialized.
Interlocked.CompareExchange(ref HostedCompilerCache,
new Dictionary<HashSet<Assembly>, HostedCompilerWrapper>(HostedCompilerCacheSize, HashSet<Assembly>.CreateSetComparer()),
null);
}
lock (HostedCompilerCache)
{
HostedCompilerWrapper hcompilerWrapper;
if (HostedCompilerCache.TryGetValue(assemblySet, out hcompilerWrapper))
{
hcompilerWrapper.Reserve(unchecked(++VisualBasicHelper.lastTimestamp));
return hcompilerWrapper;
}
if (HostedCompilerCache.Count >= HostedCompilerCacheSize)
{
// Find oldest used compiler to kick out
ulong oldestTimestamp = ulong.MaxValue;
HashSet<Assembly> oldestCompiler = null;
foreach (KeyValuePair<HashSet<Assembly>, HostedCompilerWrapper> kvp in HostedCompilerCache)
{
if (oldestTimestamp > kvp.Value.Timestamp)
{
oldestCompiler = kvp.Key;
oldestTimestamp = kvp.Value.Timestamp;
}
}
if (oldestCompiler != null)
{
hcompilerWrapper = HostedCompilerCache[oldestCompiler];
HostedCompilerCache.Remove(oldestCompiler);
hcompilerWrapper.MarkAsKickedOut();
}
}
hcompilerWrapper = new HostedCompilerWrapper(new HostedCompiler(assemblySet.ToList()));
HostedCompilerCache[assemblySet] = hcompilerWrapper;
hcompilerWrapper.Reserve(unchecked(++VisualBasicHelper.lastTimestamp));
return hcompilerWrapper;
}
}
string textToCompile;
HashSet<Assembly> referencedAssemblies;
HashSet<string> namespaceImports;
LocationReferenceEnvironment environment;
CodeActivityPublicEnvironmentAccessor? publicAccessor;
// this is a flag to differentiate the cached short-cut Rewrite from the normal post-compilation Rewrite
bool isShortCutRewrite = false;
public VisualBasicHelper(string expressionText, HashSet<AssemblyName> refAssemNames, HashSet<string> namespaceImportsNames)
: this(expressionText)
{
Initialize(refAssemNames, namespaceImportsNames);
}
VisualBasicHelper(string expressionText)
{
this.textToCompile = expressionText;
}
public string TextToCompile { get { return this.textToCompile; } }
void Initialize(HashSet<AssemblyName> refAssemNames, HashSet<string> namespaceImportsNames)
{
this.namespaceImports = namespaceImportsNames;
foreach (AssemblyName assemblyName in refAssemNames)
{
if (this.referencedAssemblies == null)
{
this.referencedAssemblies = new HashSet<Assembly>();
}
Assembly loaded = AssemblyReference.GetAssembly(assemblyName);
if (loaded != null)
{
this.referencedAssemblies.Add(loaded);
}
}
}
public static void GetAllImportReferences(Activity activity, bool isDesignTime, out IList<string> namespaces, out IList<AssemblyReference> assemblies)
{
List<string> namespaceList = new List<string>();
List<AssemblyReference> assemblyList = new List<AssemblyReference>();
// Start with the defaults; any settings on the Activity will be added to these
// The default settings are mutable, so we need to re-copy this list on every call
ExtractNamespacesAndReferences(VisualBasicSettings.Default, namespaceList, assemblyList);
LocationReferenceEnvironment environment = activity.GetParentEnvironment();
if (environment == null || environment.Root == null)
{
namespaces = namespaceList;
assemblies = assemblyList;
return;
}
VisualBasicSettings rootVBSettings = VisualBasic.GetSettings(environment.Root);
if (rootVBSettings != null)
{
// We have VBSettings
ExtractNamespacesAndReferences(rootVBSettings, namespaceList, assemblyList);
}
else
{
// Use TextExpression settings
IList<string> rootNamespaces;
IList<AssemblyReference> rootAssemblies;
if (isDesignTime)
{
// When called via VisualBasicDesignerHelper, we don't know whether or not
// we're in an implementation, so check both.
rootNamespaces = TextExpression.GetNamespacesForImplementation(environment.Root);
rootAssemblies = TextExpression.GetReferencesForImplementation(environment.Root);
if (rootNamespaces.Count == 0 && rootAssemblies.Count == 0)
{
rootNamespaces = TextExpression.GetNamespaces(environment.Root);
rootAssemblies = TextExpression.GetReferences(environment.Root);
}
}
else
{
rootNamespaces = TextExpression.GetNamespacesInScope(activity);
rootAssemblies = TextExpression.GetReferencesInScope(activity);
}
namespaceList.AddRange(rootNamespaces);
assemblyList.AddRange(rootAssemblies);
}
namespaces = namespaceList;
assemblies = assemblyList;
}
static void ExtractNamespacesAndReferences(VisualBasicSettings vbSettings,
IList<string> namespaces, IList<AssemblyReference> assemblies)
{
foreach (VisualBasicImportReference importReference in vbSettings.ImportReferences)
{
namespaces.Add(importReference.Import);
assemblies.Add(new AssemblyReference
{
Assembly = importReference.EarlyBoundAssembly,
AssemblyName = importReference.AssemblyName
});
}
}
public static Expression<Func<ActivityContext, T>> Compile<T>(string expressionText, CodeActivityPublicEnvironmentAccessor publicAccessor, bool isLocationExpression)
{
IList<string> localNamespaces;
IList<AssemblyReference> localAssemblies;
GetAllImportReferences(publicAccessor.ActivityMetadata.CurrentActivity,
false, out localNamespaces, out localAssemblies);
VisualBasicHelper helper = new VisualBasicHelper(expressionText);
HashSet<AssemblyName> localReferenceAssemblies = new HashSet<AssemblyName>();
HashSet<string> localImports = new HashSet<string>(localNamespaces);
foreach (AssemblyReference assemblyReference in localAssemblies)
{
if (assemblyReference.Assembly != null)
{
// directly add the Assembly to the list
// so that we don't have to go through
// the assembly resolution process
if (helper.referencedAssemblies == null)
{
helper.referencedAssemblies = new HashSet<Assembly>();
}
helper.referencedAssemblies.Add(assemblyReference.Assembly);
}
else if (assemblyReference.AssemblyName != null)
{
localReferenceAssemblies.Add(assemblyReference.AssemblyName);
}
}
helper.Initialize(localReferenceAssemblies, localImports);
return helper.Compile<T>(publicAccessor, isLocationExpression);
}
[Fx.Tag.SecurityNote(Critical = "Critical because it invokes a HostedCompiler, which requires FullTrust and also accesses RawTreeCache, which is SecurityCritical.",
Safe = "Safe because we are demanding FullTrust.")]
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public LambdaExpression CompileNonGeneric(LocationReferenceEnvironment environment)
{
bool abort;
Expression finalBody;
Microsoft.Compiler.VisualBasic.CompilerResults results;
this.environment = environment;
if (this.referencedAssemblies == null)
{
this.referencedAssemblies = new HashSet<Assembly>();
}
this.referencedAssemblies.UnionWith(DefaultReferencedAssemblies);
List<Import> importList = new List<Import>();
foreach (string namespaceImport in this.namespaceImports)
{
if (!String.IsNullOrEmpty(namespaceImport))
{
importList.Add(new Import(namespaceImport));
}
}
RawTreeCacheKey rawTreeKey = new RawTreeCacheKey(
this.textToCompile,
null,
this.referencedAssemblies,
this.namespaceImports);
RawTreeCacheValueWrapper rawTreeHolder = RawTreeCache.GetValue(rawTreeCacheLock, rawTreeKey) as RawTreeCacheValueWrapper;
if (rawTreeHolder != null)
{
// try short-cut
// if variable resolution fails at Rewrite, rewind and perform normal compile steps
LambdaExpression rawTree = rawTreeHolder.Value;
this.isShortCutRewrite = true;
finalBody = Rewrite(rawTree.Body, null, false, out abort);
this.isShortCutRewrite = false;
if (!abort)
{
return Expression.Lambda(rawTree.Type, finalBody, rawTree.Parameters);
}
// if we are here, then that means the shortcut Rewrite failed.
// we don't want to see too many of vb expressions in this pass since we just wasted Rewrite time for no good.
}
VisualBasicScriptAndTypeScope scriptAndTypeScope = new VisualBasicScriptAndTypeScope(
this.environment,
this.referencedAssemblies.ToList<Assembly>());
IImportScope importScope = new VisualBasicImportScope(importList);
CompilerOptions options = new CompilerOptions();
options.OptionStrict = OptionStrictSetting.On;
CompilerContext context = new CompilerContext(scriptAndTypeScope, scriptAndTypeScope, importScope, options);
HostedCompilerWrapper compilerWrapper = GetCachedHostedCompiler(this.referencedAssemblies);
HostedCompiler compiler = compilerWrapper.Compiler;
try
{
lock (compiler)
{
try
{
results = compiler.CompileExpression(this.textToCompile, context);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
FxTrace.Exception.TraceUnhandledException(e);
throw;
}
}
}
finally
{
compilerWrapper.Release();
}
if (scriptAndTypeScope.ErrorMessage != null)
{
throw FxTrace.Exception.AsError(new SourceExpressionException(SR.CompilerErrorSpecificExpression(textToCompile, scriptAndTypeScope.ErrorMessage)));
}
if (results.Errors != null && results.Errors.Count > 0)
{
// this expression has problems, so report them
StringBuilder errorString = new StringBuilder();
errorString.AppendLine();
foreach (Error error in results.Errors)
{
errorString.AppendLine(error.Description);
}
throw FxTrace.Exception.AsError(new SourceExpressionException(SR.CompilerErrorSpecificExpression(textToCompile, errorString.ToString())));
}
// replace the field references with variable references to our dummy variables
// and rewrite lambda.body.Type to equal the lambda return type T
LambdaExpression lambda = results.CodeBlock;
if (lambda == null)
{
// ExpressionText was either an empty string or Null
// we return null which eventually evaluates to default(TResult) at execution time.
return null;
}
// add the pre-rewrite lambda to RawTreeCache
AddToRawTreeCache(rawTreeKey, rawTreeHolder, lambda);
finalBody = Rewrite(lambda.Body, null, false, out abort);
Fx.Assert(abort == false, "this non-shortcut Rewrite must always return abort == false");
return Expression.Lambda(lambda.Type, finalBody, lambda.Parameters);
}
public Expression<Func<ActivityContext, T>> Compile<T>(CodeActivityPublicEnvironmentAccessor publicAccessor, bool isLocationReference = false)
{
this.publicAccessor = publicAccessor;
return Compile<T>(publicAccessor.ActivityMetadata.Environment, isLocationReference);
}
// Soft-Link: This method is called through reflection by VisualBasicDesignerHelper.
public Expression<Func<ActivityContext, T>> Compile<T>(LocationReferenceEnvironment environment)
{
Fx.Assert(this.publicAccessor == null, "No public accessor so the value for isLocationReference doesn't matter");
return Compile<T>(environment, false);
}
[Fx.Tag.SecurityNote(Critical = "Critical because it invokes a HostedCompiler, which requires FullTrust and also accesses RawTreeCache, which is SecurityCritical.",
Safe = "Safe because we are demanding FullTrust.")]
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public Expression<Func<ActivityContext, T>> Compile<T>(LocationReferenceEnvironment environment, bool isLocationReference)
{
bool abort;
Expression finalBody;
Microsoft.Compiler.VisualBasic.CompilerResults results;
Type lambdaReturnType = typeof(T);
this.environment = environment;
if (this.referencedAssemblies == null)
{
this.referencedAssemblies = new HashSet<Assembly>();
}
this.referencedAssemblies.UnionWith(DefaultReferencedAssemblies);
List<Import> importList = new List<Import>();
foreach (string namespaceImport in this.namespaceImports)
{
if (!String.IsNullOrEmpty(namespaceImport))
{
importList.Add(new Import(namespaceImport));
}
}
RawTreeCacheKey rawTreeKey = new RawTreeCacheKey(
this.textToCompile,
lambdaReturnType,
this.referencedAssemblies,
this.namespaceImports);
RawTreeCacheValueWrapper rawTreeHolder = RawTreeCache.GetValue(rawTreeCacheLock, rawTreeKey) as RawTreeCacheValueWrapper;
if (rawTreeHolder != null)
{
// try short-cut
// if variable resolution fails at Rewrite, rewind and perform normal compile steps
LambdaExpression rawTree = rawTreeHolder.Value;
this.isShortCutRewrite = true;
finalBody = Rewrite(rawTree.Body, null, isLocationReference, out abort);
this.isShortCutRewrite = false;
if (!abort)
{
Fx.Assert(finalBody.Type == lambdaReturnType, "Compiler generated ExpressionTree return type doesn't match the target return type");
// convert it into the our expected lambda format (context => ...)
return Expression.Lambda<Func<ActivityContext, T>>(finalBody,
FindParameter(finalBody) ?? ExpressionUtilities.RuntimeContextParameter);
}
// if we are here, then that means the shortcut Rewrite failed.
// we don't want to see too many of vb expressions in this pass since we just wasted Rewrite time for no good.
if (this.publicAccessor != null)
{
// from the preceding shortcut rewrite, we probably have generated tempAutoGeneratedArguments
// they are not valid anymore since we just aborted the shortcut rewrite.
// clean up, and start again.
this.publicAccessor.Value.ActivityMetadata.CurrentActivity.ResetTempAutoGeneratedArguments();
}
}
// ensure the return type's assembly is added to ref assembly list
HashSet<Type> allBaseTypes = null;
EnsureTypeReferenced(lambdaReturnType, ref allBaseTypes);
foreach (Type baseType in allBaseTypes)
{
// allBaseTypes list always contains lambdaReturnType
this.referencedAssemblies.Add(baseType.Assembly);
}
VisualBasicScriptAndTypeScope scriptAndTypeScope = new VisualBasicScriptAndTypeScope(
this.environment,
this.referencedAssemblies.ToList<Assembly>());
IImportScope importScope = new VisualBasicImportScope(importList);
CompilerOptions options = new CompilerOptions();
options.OptionStrict = OptionStrictSetting.On;
CompilerContext context = new CompilerContext(scriptAndTypeScope, scriptAndTypeScope, importScope, options);
HostedCompilerWrapper compilerWrapper = GetCachedHostedCompiler(this.referencedAssemblies);
HostedCompiler compiler = compilerWrapper.Compiler;
if (TD.CompileVbExpressionStartIsEnabled())
{
TD.CompileVbExpressionStart(this.textToCompile);
}
try
{
lock (compiler)
{
try
{
results = compiler.CompileExpression(this.textToCompile, context, lambdaReturnType);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
// We never want to end up here, Compiler bugs needs to be fixed.
FxTrace.Exception.TraceUnhandledException(e);
throw;
}
}
}
finally
{
compilerWrapper.Release();
}
if (TD.CompileVbExpressionStopIsEnabled())
{
TD.CompileVbExpressionStop();
}
if (scriptAndTypeScope.ErrorMessage != null)
{
throw FxTrace.Exception.AsError(new SourceExpressionException(SR.CompilerErrorSpecificExpression(textToCompile, scriptAndTypeScope.ErrorMessage)));
}
if (results.Errors != null && results.Errors.Count > 0)
{
// this expression has problems, so report them
StringBuilder errorString = new StringBuilder();
errorString.AppendLine();
foreach (Error error in results.Errors)
{
errorString.AppendLine(error.Description);
}
throw FxTrace.Exception.AsError(new SourceExpressionException(SR.CompilerErrorSpecificExpression(textToCompile, errorString.ToString())));
}
// replace the field references with variable references to our dummy variables
// and rewrite lambda.body.Type to equal the lambda return type T
LambdaExpression lambda = results.CodeBlock;
if (lambda == null)
{
// ExpressionText was either an empty string or Null
// we return null which eventually evaluates to default(TResult) at execution time.
return null;
}
// add the pre-rewrite lambda to RawTreeCache
AddToRawTreeCache(rawTreeKey, rawTreeHolder, lambda);
finalBody = Rewrite(lambda.Body, null, isLocationReference, out abort);
Fx.Assert(abort == false, "this non-shortcut Rewrite must always return abort == false");
Fx.Assert(finalBody.Type == lambdaReturnType, "Compiler generated ExpressionTree return type doesn't match the target return type");
// convert it into the our expected lambda format (context => ...)
return Expression.Lambda<Func<ActivityContext, T>>(finalBody,
FindParameter(finalBody) ?? ExpressionUtilities.RuntimeContextParameter);
}
[Fx.Tag.SecurityNote(Critical = "Critical because it access SecurityCritical member RawTreeCache, thus requiring FullTrust.",
Safe = "Safe because we are demanding FullTrust.")]
[SecuritySafeCritical]
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
static void AddToRawTreeCache(RawTreeCacheKey rawTreeKey, RawTreeCacheValueWrapper rawTreeHolder, LambdaExpression lambda)
{
if (rawTreeHolder != null)
{
// this indicates that the key had been found in RawTreeCache,
// but the value Expression Tree failed the short-cut Rewrite.
// ---- is really not an issue here, because
// any one of possibly many raw Expression Trees that are all
// represented by the same key can be written here.
rawTreeHolder.Value = lambda;
}
else
{
// we never hit RawTreeCache with the given key
lock (rawTreeCacheLock)
{
// ensure we don't add the same key with two differnt RawTreeValueWrappers
if (RawTreeCache.GetValue(rawTreeCacheLock, rawTreeKey) == null)
{
// do we need defense against alternating miss of the shortcut Rewrite?
RawTreeCache.Add(rawTreeKey, new RawTreeCacheValueWrapper() { Value = lambda });
}
}
}
}
delegate bool FindMatch(LocationReference reference, string targetName, Type targetType, out bool terminateSearch);
static FindMatch delegateFindLocationReferenceMatchShortcut = new FindMatch(FindLocationReferenceMatchShortcut);
static FindMatch delegateFindFirstLocationReferenceMatch = new FindMatch(FindFirstLocationReferenceMatch);
static FindMatch delegateFindAllLocationReferenceMatch = new FindMatch(FindAllLocationReferenceMatch);
static bool FindLocationReferenceMatchShortcut(LocationReference reference, string targetName, Type targetType, out bool terminateSearch)
{
terminateSearch = false;
if (string.Equals(reference.Name, targetName, StringComparison.OrdinalIgnoreCase))
{
if (targetType != reference.Type)
{
terminateSearch = true;
return false;
}
return true;
}
return false;
}
static bool FindFirstLocationReferenceMatch(LocationReference reference, string targetName, Type targetType, out bool terminateSearch)
{
terminateSearch = false;
if (string.Equals(reference.Name, targetName, StringComparison.OrdinalIgnoreCase))
{
terminateSearch = true;
return true;
}
return false;
}
static bool FindAllLocationReferenceMatch(LocationReference reference, string targetName, Type targetType, out bool terminateSearch)
{
terminateSearch = false;
if (string.Equals(reference.Name, targetName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
// Returning null indicates the cached LambdaExpression used here doesn't coincide with current LocationReferenceEnvironment.
// Null return value causes the process to rewind and start from HostedCompiler.CompileExpression().
Expression Rewrite(Expression expression, ReadOnlyCollection<ParameterExpression> lambdaParameters, out bool abort)
{
return Rewrite(expression, lambdaParameters, false, out abort);
}
Expression Rewrite(Expression expression, ReadOnlyCollection<ParameterExpression> lambdaParameters, bool isLocationExpression, out bool abort)
{
int i;
int j;
Expression expr1;
Expression expr2;
Expression expr3;
List<Expression> arguments;
NewExpression newExpression;
ReadOnlyCollection<Expression> tmpArguments;
abort = false;
if (expression == null)
{
return null;
}
switch (expression.NodeType)
{
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Coalesce:
case ExpressionType.Divide:
case ExpressionType.Equal:
case ExpressionType.ExclusiveOr:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LeftShift:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.Modulo:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.NotEqual:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.Power:
case ExpressionType.RightShift:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
BinaryExpression binaryExpression = (BinaryExpression)expression;
expr1 = Rewrite(binaryExpression.Left, lambdaParameters, out abort);
if (abort)
{
return null;
}
expr2 = Rewrite(binaryExpression.Right, lambdaParameters, out abort);
if (abort)
{
return null;
}
LambdaExpression conversion = (LambdaExpression)Rewrite(binaryExpression.Conversion, lambdaParameters, out abort);
if (abort)
{
return null;
}
return Expression.MakeBinary(
binaryExpression.NodeType,
expr1,
expr2,
binaryExpression.IsLiftedToNull,
binaryExpression.Method,
conversion);
case ExpressionType.Conditional:
ConditionalExpression conditional = (ConditionalExpression)expression;
expr1 = Rewrite(conditional.Test, lambdaParameters, out abort);
if (abort)
{
return null;
}
expr2 = Rewrite(conditional.IfTrue, lambdaParameters, out abort);
if (abort)
{
return null;
}
expr3 = Rewrite(conditional.IfFalse, lambdaParameters, out abort);
if (abort)
{
return null;
}
return Expression.Condition(expr1, expr2, expr3);
case ExpressionType.Constant:
return expression;
case ExpressionType.Invoke:
InvocationExpression invocation = (InvocationExpression)expression;
expr1 = Rewrite(invocation.Expression, lambdaParameters, out abort);
if (abort)
{
return null;
}
arguments = null;
tmpArguments = invocation.Arguments;
Fx.Assert(tmpArguments != null, "InvocationExpression.Arguments must not be null");
if (tmpArguments.Count > 0)
{
arguments = new List<Expression>(tmpArguments.Count);
for (i = 0; i < tmpArguments.Count; i++)
{
expr2 = Rewrite(tmpArguments[i], lambdaParameters, out abort);
if (abort)
{
return null;
}
arguments.Add(expr2);
}
}
return Expression.Invoke(expr1, arguments);
case ExpressionType.Lambda:
LambdaExpression lambda = (LambdaExpression)expression;
expr1 = Rewrite(lambda.Body, lambda.Parameters, isLocationExpression, out abort);
if (abort)
{
return null;
}
return Expression.Lambda(lambda.Type, expr1, lambda.Parameters);
case ExpressionType.ListInit:
ListInitExpression listInit = (ListInitExpression)expression;
newExpression = (NewExpression)Rewrite(listInit.NewExpression, lambdaParameters, out abort);
if (abort)
{
return null;
}
ReadOnlyCollection<ElementInit> tmpInitializers = listInit.Initializers;
Fx.Assert(tmpInitializers != null, "ListInitExpression.Initializers must not be null");
List<ElementInit> initializers = new List<ElementInit>(tmpInitializers.Count);
for (i = 0; i < tmpInitializers.Count; i++)
{
tmpArguments = tmpInitializers[i].Arguments;
Fx.Assert(tmpArguments != null, "ElementInit.Arguments must not be null");
arguments = new List<Expression>(tmpArguments.Count);
for (j = 0; j < tmpArguments.Count; j++)
{
expr1 = Rewrite(tmpArguments[j], lambdaParameters, out abort);
if (abort)
{
return null;
}
arguments.Add(expr1);
}
initializers.Add(Expression.ElementInit(tmpInitializers[i].AddMethod, arguments));
}
return Expression.ListInit(newExpression, initializers);
case ExpressionType.Parameter:
ParameterExpression variableExpression = (ParameterExpression)expression;
{
if (lambdaParameters != null && lambdaParameters.Contains(variableExpression))
{
return variableExpression;
}
FindMatch findMatch;
if (this.isShortCutRewrite)
{
//
// this is the opportunity to inspect whether the cached LambdaExpression(raw expression tree)
// does coincide with the current LocationReferenceEnvironment.
// If any mismatch discovered, it immediately returns NULL, indicating cache lookup failure.
//
findMatch = delegateFindLocationReferenceMatchShortcut;
}
else
{
//
// variable(LocationReference) resolution process
// Note that the non-shortcut compilation pass always gaurantees successful variable resolution here.
//
findMatch = delegateFindFirstLocationReferenceMatch;
}
bool foundMultiple;
LocationReference finalReference = FindLocationReferencesFromEnvironment(
this.environment,
findMatch,
variableExpression.Name,
variableExpression.Type,
out foundMultiple);
if (finalReference != null && !foundMultiple)
{
if (this.publicAccessor != null)
{
CodeActivityPublicEnvironmentAccessor localPublicAccessor = this.publicAccessor.Value;
LocationReference inlinedReference;
if (ExpressionUtilities.TryGetInlinedReference(localPublicAccessor,
finalReference, isLocationExpression, out inlinedReference))
{
finalReference = inlinedReference;
}
}
return ExpressionUtilities.CreateIdentifierExpression(finalReference);
}
if (this.isShortCutRewrite)
{
// cached LambdaExpression doesn't match this LocationReferenceEnvironment!!
// no matching LocationReference found.
// fail immeditely.
abort = true;
return null;
}
// if we are here, this variableExpression is a temp variable
// generated by the compiler.
return variableExpression;
}
case ExpressionType.MemberAccess:
MemberExpression memberExpression = (MemberExpression)expression;
// When creating a location for a member on a struct, we also need a location
// for the struct (so we don't just set the member on a copy of the struct)
bool subTreeIsLocationExpression = isLocationExpression && memberExpression.Member.DeclaringType.IsValueType;
expr1 = Rewrite(memberExpression.Expression, lambdaParameters, subTreeIsLocationExpression, out abort);
if (abort)
{
return null;
}
return Expression.MakeMemberAccess(expr1, memberExpression.Member);
case ExpressionType.MemberInit:
MemberInitExpression memberInit = (MemberInitExpression)expression;
newExpression = (NewExpression)Rewrite(memberInit.NewExpression, lambdaParameters, out abort);
if (abort)
{
return null;
}
ReadOnlyCollection<MemberBinding> tmpMemberBindings = memberInit.Bindings;
Fx.Assert(tmpMemberBindings != null, "MemberInitExpression.Bindings must not be null");
List<MemberBinding> bindings = new List<MemberBinding>(tmpMemberBindings.Count);
for (i = 0; i < tmpMemberBindings.Count; i++)
{
MemberBinding binding = Rewrite(tmpMemberBindings[i], lambdaParameters, out abort);
if (abort)
{
return null;
}
bindings.Add(binding);
}
return Expression.MemberInit(newExpression, bindings);
case ExpressionType.ArrayIndex:
// ArrayIndex can be a MethodCallExpression or a BinaryExpression
MethodCallExpression arrayIndex = expression as MethodCallExpression;
if (arrayIndex != null)
{
expr1 = Rewrite(arrayIndex.Object, lambdaParameters, out abort);
if (abort)
{
return null;
}
tmpArguments = arrayIndex.Arguments;
Fx.Assert(tmpArguments != null, "MethodCallExpression.Arguments must not be null");
List<Expression> indexes = new List<Expression>(tmpArguments.Count);
for (i = 0; i < tmpArguments.Count; i++)
{
expr2 = Rewrite(tmpArguments[i], lambdaParameters, out abort);
if (abort)
{
return null;
}
indexes.Add(expr2);
}
return Expression.ArrayIndex(expr1, indexes);
}
BinaryExpression alternateIndex = (BinaryExpression)expression;
expr1 = Rewrite(alternateIndex.Left, lambdaParameters, out abort);
if (abort)
{
return null;
}
expr2 = Rewrite(alternateIndex.Right, lambdaParameters, out abort);
if (abort)
{
return null;
}
return Expression.ArrayIndex(expr1, expr2);
case ExpressionType.Call:
MethodCallExpression methodCall = (MethodCallExpression)expression;
expr1 = Rewrite(methodCall.Object, lambdaParameters, out abort);
if (abort)
{
return null;
}
arguments = null;
tmpArguments = methodCall.Arguments;
Fx.Assert(tmpArguments != null, "MethodCallExpression.Arguments must not be null");
if (tmpArguments.Count > 0)
{
arguments = new List<Expression>(tmpArguments.Count);
for (i = 0; i < tmpArguments.Count; i++)
{
expr2 = Rewrite(tmpArguments[i], lambdaParameters, out abort);
if (abort)
{
return null;
}
arguments.Add(expr2);
}
}
return Expression.Call(expr1, methodCall.Method, arguments);
case ExpressionType.NewArrayInit:
NewArrayExpression newArray = (NewArrayExpression)expression;
ReadOnlyCollection<Expression> tmpExpressions = newArray.Expressions;
Fx.Assert(tmpExpressions != null, "NewArrayExpression.Expressions must not be null");
List<Expression> arrayInitializers = new List<Expression>(tmpExpressions.Count);
for (i = 0; i < tmpExpressions.Count; i++)
{
expr1 = Rewrite(tmpExpressions[i], lambdaParameters, out abort);
if (abort)
{
return null;
}
arrayInitializers.Add(expr1);