This repository was archived by the owner on Jul 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathCodeProvider.cs
More file actions
11823 lines (10059 loc) · 384 KB
/
CodeProvider.cs
File metadata and controls
11823 lines (10059 loc) · 384 KB
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
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#undef Enable_Csharp2CCI
using Microsoft.Cci;
using System.IO;
using Microsoft.Research.CodeAnalysis;
using Microsoft.Research.DataStructures;
using System;
using System.Collections.Generic;
using Microsoft.Cci.Contracts;
using System.Diagnostics;
using Unit = Microsoft.Research.DataStructures.Unit;
using System.Linq;
using Microsoft.Cci.MutableContracts;
using System.Diagnostics.Contracts;
using Microsoft.Cci.Immutable;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Cci.Analysis
{
internal class ThisSubstituter : MutableCodeModel.Contracts.CodeAndContractRewriter
{
private readonly IParameterDefinition thisParameter;
internal ThisSubstituter(IMetadataHost host, IParameterDefinition thisParam)
: base(host, true)
{
this.thisParameter = thisParam;
}
public override IExpression Rewrite(IThisReference thisReference)
{
var b = new MutableCodeModel.BoundExpression();
b.Definition = this.thisParameter;
b.Locations = new List<ILocation>(thisReference.Locations);
b.Type = this.thisParameter.Type;
return b;
}
}
// REVIEW: This is really *not* the way to do this. For all contracts, we don't necessarily know that they came from IL. When we get them from
// the contract provider, all we know is that they are in the object model. So we either need to lower the object model back to IL, or else
// modify the provider's interface so that we can get the IL from which the contracts came from. (Or have that logic not visible, but we just
// can get the IL from a contract.)
public class CciContractDecoder : IDecodeContracts<LocalDefAdaptor, IParameterTypeInformation, MethodReferenceAdaptor, FieldReferenceAdaptor, TypeReferenceAdaptor>
{
private readonly CciILCodeProvider parent;
internal readonly CciMetadataDecoder mdDecoder;
private readonly IContractAwareHost host;
internal CciContractDecoder(CciILCodeProvider parent, IContractAwareHost host, CciMetadataDecoder mdDecoder)
{
this.parent = parent;
this.host = host;
this.mdDecoder = mdDecoder;
}
#region IDecodeContracts<IMethodReference,IFieldReference,TypeReferenceAdaptor> Members
public bool IsContractVerificationAttributeTrue(MethodReferenceAdaptor method)
{
return VerifyMethod(method, false, false, false, false);
}
public bool VerifyMethod(MethodReferenceAdaptor methodAdaptor, bool analyzeNonUserCode, bool namespaceSelected, bool typeSelected, bool memberSelected)
{
return VerifyMethod(methodAdaptor, analyzeNonUserCode, namespaceSelected, typeSelected, memberSelected, true);
}
private bool VerifyMethod(MethodReferenceAdaptor methodAdaptor, bool analyzeNonUserCode, bool namespaceSelected, bool typeSelected, bool memberSelected, bool defaultValue)
{
if (methodAdaptor.reference is DummyArrayMethodReference) return false;
IMethodReference method = methodAdaptor.reference;
if (!analyzeNonUserCode && NonUserCode(method.ResolvedMethod.Attributes)) return false;
if (memberSelected) return true;
ThreeValued tv = CheckIfVerify(method.ResolvedMethod.Attributes);
if (tv.IsDetermined) return tv.Truth;
if (typeSelected) return true;
var declaringType = method.ContainingType;
do
{
tv = CheckIfVerify(declaringType.ResolvedType.Attributes);
if (tv.IsDetermined) return tv.Truth;
if (!analyzeNonUserCode && NonUserCode(declaringType.ResolvedType.Attributes)) return false;
var nested = declaringType as INestedTypeReference;
if (nested == null) break;
declaringType = nested.ContainingType;
}
while (true);
if (namespaceSelected) return true;
var toplevel = (INamespaceTypeDefinition)declaringType.ResolvedType;
var unit = TypeHelper.GetDefiningUnit(toplevel) as IAssembly;
if (unit == null) return true; //default
tv = CheckIfVerify(unit.Attributes);
if (tv.IsFalse) return false;
return defaultValue; // default
}
[Pure]
private ThreeValued CheckIfVerify(IEnumerable<ICustomAttribute> attributes)
{
Contract.Requires(attributes != null);
foreach (var ca in attributes)
{
INamespaceTypeReference nstr = ca.Type as INamespaceTypeReference;
if (nstr != null && nstr.Name.Value == "ContractVerificationAttribute")
{
foreach (var arg in ca.Arguments)
{
object obj = CciMetadataDecoder.TranslateToObject(arg);
if (obj is bool)
{
bool value = (bool)obj;
return new ThreeValued(value);
}
}
}
}
return new ThreeValued();
}
public bool HasOptionForClousot(MethodReferenceAdaptor methodAdaptor, string optionName, out string optionValue)
{
// TODO TODO: the code is not doing what the CCI1 implementation is doing
optionValue = null;
if (methodAdaptor.reference is DummyArrayMethodReference) return false;
IMethodReference method = methodAdaptor.reference;
ThreeValued tv = CheckIfClousotOption(method.ResolvedMethod.Attributes);
var declaringType = method.ContainingType;
do
{
tv = CheckIfClousotOption(declaringType.ResolvedType.Attributes);
if (tv.IsDetermined) return tv.Truth;
var nested = declaringType as INestedTypeReference;
if (nested == null) break;
declaringType = nested.ContainingType;
}
while (true);
var toplevel = (INamespaceTypeDefinition)declaringType.ResolvedType;
var unit = TypeHelper.GetDefiningUnit(toplevel) as IAssembly;
if (unit == null) return false;
tv = CheckIfClousotOption(unit.Attributes);
if (tv.IsFalse) return false;
return false;
}
[Pure]
[ContractVerification(false)]
private ThreeValued CheckIfClousotOption(IEnumerable<ICustomAttribute> attributes)
{
Contract.Requires(attributes != null);
foreach (var ca in attributes)
{
INamespaceTypeReference nstr = ca.Type as INamespaceTypeReference;
if (nstr != null && nstr.Name.Value == "ContractOptionAttribute")
{
var args = new string[3];
var i = 0;
foreach (var arg in ca.Arguments)
{
var obj = CciMetadataDecoder.TranslateToObject(arg);
if(obj is string )
{
if(i >= args.Length)
{
return new ThreeValued(false);
}
args[i++] = obj as string;
}
}
if(i == 3)
{
var toolName = args[0];
var optionName = args[1];
var optionValue = args[2];
if (toolName != null && optionName != null && optionValue != null)
{
toolName = toolName.ToLower();
if (toolName.Contains("cccheck") || toolName.Contains("clousot"))
{
if (optionName.ToLower() == "inherit")
{
return new ThreeValued(true);
}
}
}
}
}
}
return new ThreeValued();
}
[Pure]
public static ThreeValued IsContractOptionAttribute(ICustomAttribute ca, string category, string setting)
{
string tmpcategory, tmpsetting;
var result = IsContractOptionAttribute(ca, out tmpcategory, out tmpsetting);
if (result.IsDetermined)
{
if (string.Compare(category, tmpcategory, true) == 0 && string.Compare(setting, tmpsetting, true) == 0)
{
return result;
}
return new ThreeValued();
}
return result;
}
[Pure]
public static ThreeValued IsContractOptionAttribute(ICustomAttribute ca, out string category, out string setting)
{
category = null; setting = null;
var result = new ThreeValued();
if (ca == null)
{
return result;
}
INamespaceTypeReference nstr = ca.Type as INamespaceTypeReference;
if (nstr == null) return result;
if (nstr.Name.Value != "ContractOptionAttribute") return result;
int index = 0;
foreach (var arg in ca.Arguments)
{
object obj = CciMetadataDecoder.TranslateToObject(arg);
if (index < 2)
{
string lit = obj as string;
if (lit == null) return result;
if (index == 0) category = lit;
if (index == 1) setting = lit;
}
if (index == 2)
{
if (obj is bool)
{
var toggle = (bool)obj;
result = new ThreeValued(toggle);
}
}
}
return result;
}
private static ThreeValued IsMutableHeapIndependent(IEnumerable<ICustomAttribute> attributes)
{
Contract.Requires(attributes != null);
foreach (var ca in attributes)
{
var attributeValue = IsContractOptionAttribute(ca, "reads", "mutable");
if (attributeValue.IsDetermined)
{
if (attributeValue.IsFalse) return new ThreeValued(true);
else return new ThreeValued(false);
}
}
return new ThreeValued(false);
}
private static ThreeValued CanInheritContracts(IEnumerable<ICustomAttribute> attributes)
{
Contract.Requires(attributes != null);
foreach (var ca in attributes)
{
INamespaceTypeReference nstr = ca.Type as INamespaceTypeReference;
if (nstr != null && nstr.Name.Value == "ContractOptionAttribute")
{
int index = 0;
foreach (var arg in ca.Arguments)
{
object obj = CciMetadataDecoder.TranslateToObject(arg);
if (index < 2)
{
string lit = obj as string;
if (lit == null) return new ThreeValued();
if (index == 0 && string.Compare(lit, "Contract", true) != 0) return new ThreeValued();
if (index == 1 && string.Compare(lit, "Inheritance", true) != 0) return new ThreeValued();
}
if (index == 2)
{
if (obj is bool)
{
bool value = (bool)obj;
return new ThreeValued(value);
}
else return new ThreeValued();
}
}
}
}
return new ThreeValued();
}
public static bool CanInheritContractsInternal(IMethodReference method)
{
Contract.Requires(method != null);
ThreeValued tv = CanInheritContracts(method.ResolvedMethod.Attributes);
if (tv.IsDetermined) return tv.Truth;
var declaringType = method.ContainingType;
return CanInheritContracts(declaringType);
}
public bool CanInheritContracts(MethodReferenceAdaptor method)
{
return CanInheritContractsInternal(method.reference);
}
public bool CanInheritContracts(TypeReferenceAdaptor declaringType)
{
return CanInheritContracts(declaringType.reference);
}
public static bool CanInheritContracts(ITypeReference type)
{
type = CciMetadataDecoder.Unspecialized(type);
Contract.Assume(type != null);
var rt = type.ResolvedType;
var tv = CanInheritContracts(rt.Attributes);
if (tv.IsDetermined) return tv.Truth;
var nested = rt as INestedTypeReference;
if (nested != null) { return CanInheritContracts(nested.ContainingType); }
var toplevel = (INamespaceTypeDefinition)rt;
var unit = TypeHelper.GetDefiningUnit(toplevel) as IAssembly;
if (unit == null) return true; //default
tv = CanInheritContracts(unit.Attributes);
if (tv.IsFalse) return false;
return true; // default
}
public static bool IsMutableHeapIndependent(IMethodReference method)
{
Contract.Requires(method != null);
var unspec = MemberHelper.UninstantiateAndUnspecialize(method);
ThreeValued tv = IsMutableHeapIndependent(unspec.ResolvedMethod.Attributes);
// ThreeValued tv = IsMutableHeapIndependent(method.ResolvedMethod.Attributes);
if (tv.IsDetermined) return tv.Truth;
var declaringType = method.ContainingType;
return IsMutableHeapIndependent(declaringType);
}
public bool IsMutableHeapIndependent(MethodReferenceAdaptor method)
{
return IsMutableHeapIndependent(method.reference);
}
public bool IsMutableHeapIndependent(TypeReferenceAdaptor declaringType)
{
return IsMutableHeapIndependent(declaringType.reference);
}
public static bool IsMutableHeapIndependent(ITypeReference type)
{
type = CciMetadataDecoder.Unspecialized(type);
Contract.Assume(type != null);
var rt = type.ResolvedType;
var tv = IsMutableHeapIndependent(rt.Attributes);
if (tv.IsDetermined) return tv.Truth;
var nested = rt as INestedTypeReference;
if (nested != null) { return IsMutableHeapIndependent(nested.ContainingType); }
var toplevel = (INamespaceTypeDefinition)rt;
var unit = TypeHelper.GetDefiningUnit(toplevel) as IAssembly;
if (unit == null) return true; //default
tv = IsMutableHeapIndependent(unit.Attributes);
if (tv.IsFalse) return false;
return true; // default
}
[SuppressMessage("Microsoft.Contracts", "TestAlwaysEvaluatingToAConstant")]
private bool NonUserCode(IEnumerable<ICustomAttribute> attributes)
{
Contract.Requires(attributes != null);
foreach (var ca in attributes)
{
INamespaceTypeReference nstr = ca.Type as INamespaceTypeReference;
if (nstr != null)
{
switch (nstr.Name.Value)
{
case "DebuggerNonUserCodeAttribute":
case "CompilerGeneratedAttribute":
case "GeneratedCodeAttribute":
return true;
}
}
}
return false;
}
public bool IsPure(MethodReferenceAdaptor methodAdaptor)
{
if (IsPure(methodAdaptor.reference)) return true;
var method = CciMetadataDecoder.Unspecialized(methodAdaptor.reference.ResolvedMethod);
if (IsPure(method)) return true;
var unspecializedAdapter = MethodReferenceAdaptor.AdaptorOf(method);
// getters are pure
if (this.mdDecoder.IsPropertyGetter(unspecializedAdapter)) return true;
// all operators are considered heap independent
if (this.mdDecoder.IsStatic(method))
{
if (method.Name.Value.StartsWith("op_"))
return true;
}
// if containing type is pure all methods are pure except constructors
if (!method.IsConstructor)
{
var type = method.ContainingType as ITypeDefinition;
if (type != null)
{
if (IsPure(type)) return true;
}
}
foreach (var baseMethod in mdDecoder.OverriddenAndImplementedMethods(unspecializedAdapter))
{
if (IsPure(baseMethod)) return true;
}
return false;
}
public bool IsPure(IReference reference)
{
var meth = reference as IMethodReference;
if (meth != null)
{
var imc = this.GetMethodContract(meth);
if (imc != null && imc.IsPure) return true;
}
if (HasAttributeWithName(reference.Attributes, "PureAttribute")) return true;
return false;
}
public static bool IsContractAbbreviator(IMethodDefinition method)
{
Contract.Requires(method != null);
return HasAttributeWithName(method.Attributes, "ContractAbbreviatorAttribute");
}
static string TypeName(ITypeReference type)
{
INamespaceTypeReference nstr = type as INamespaceTypeReference;
if (nstr != null) return nstr.Name.Value;
return null;
}
static bool HasAttributeWithName(IEnumerable<ICustomAttribute> attributes, string expected)
{
Contract.Requires(attributes != null);
foreach (var attr in attributes)
{
string name = TypeName(attr.Type);
if (name == expected) return true;
}
return false;
}
public bool IsFreshResult(MethodReferenceAdaptor methodAdaptor)
{
var method = CciMetadataDecoder.Unspecialized(methodAdaptor.reference.ResolvedMethod);
Contract.Assume(method != null);
if (HasAttributeWithName(method.Attributes, "FreshAttribute")) return true;
foreach (var baseMethod in mdDecoder.OverriddenAndImplementedMethods(MethodReferenceAdaptor.AdaptorOf(method)))
{
if (IsFreshResult(baseMethod)) return true;
}
return false;
}
/// <summary>
/// Some model method references cannot be resolved since they may not actually be members of the type
/// they claim to be their containing type. (This is the case for ones defined in reference assemblies.)
/// That means that any attempt to resolve them ends up in a dummy method definition.
/// So check the model methods list stored in the type contract of the method's containing type.
/// If that fails, then sure, go ahead and search for the attribute (and for property getters, search
/// the property).
/// </summary>
public bool IsModel(MethodReferenceAdaptor methodAdaptor)
{
bool isModel = false;
var method = methodAdaptor.reference;
var tc = this.GetTypeContract(method.ContainingType);
if (tc != null) {
foreach (var mm in tc.ContractMethods) {
if (mm.InternedKey == method.InternedKey) { isModel = true; goto Ret; }
}
}
method = CciMetadataDecoder.Unspecialized(method.ResolvedMethod);
Contract.Assume(method != null);
if (HasAttributeWithName(method.Attributes, "ContractModelAttribute")) { isModel = true; goto Ret; }
if (this.mdDecoder.IsPropertyGetter(methodAdaptor))
{
var prop = this.mdDecoder.GetPropertyFromAccessor(methodAdaptor);
isModel = prop != null && HasAttributeWithName(prop.Attributes, "ContractModelAttribute");
goto Ret;
}
Ret:
//var name = MemberHelper.GetMethodSignature(method, NameFormattingOptions.DocumentationId);
//Console.WriteLine("{0}: {1}", name, isModel ? "true" : "false");
return isModel;
}
public IEnumerable<FieldReferenceAdaptor> ModelFields(TypeReferenceAdaptor typeAdaptor)
{
var typeReference = typeAdaptor.reference;
if (typeReference == null) return Enumerable<FieldReferenceAdaptor>.Empty;
ITypeContract/*?*/ typeContract = this.GetTypeContract(typeReference);
if (typeContract == null || IteratorHelper.EnumerableIsEmpty(typeContract.ContractFields)) return Enumerable<FieldReferenceAdaptor>.Empty;
return IteratorHelper.GetConversionEnumerable<IFieldReference, FieldReferenceAdaptor>(typeContract.ContractFields, FieldReferenceAdaptor.AdaptorOf);
}
public IEnumerable<MethodReferenceAdaptor> ModelMethods(TypeReferenceAdaptor typeAdaptor)
{
var typeReference = typeAdaptor.reference;
if (typeReference == null) return Enumerable<MethodReferenceAdaptor>.Empty;
ITypeContract/*?*/ typeContract = this.GetTypeContract(typeReference);
if (typeContract == null || IteratorHelper.EnumerableIsEmpty(typeContract.ContractMethods)) return Enumerable<MethodReferenceAdaptor>.Empty;
return IteratorHelper.GetConversionEnumerable<IMethodDefinition, MethodReferenceAdaptor>(typeContract.ContractMethods, MethodReferenceAdaptor.AdaptorOf);
}
public bool HasInvariant(MethodReferenceAdaptor methodAdaptor)
{
IMethodReference method = methodAdaptor.reference;
var type = method.ContainingType;
ITypeContract/*?*/ typeContract = this.GetTypeContract(type);
if (typeContract == null) return false;
var invs = new List<ITypeInvariant>(typeContract.Invariants);
return 0 < invs.Count;
}
public bool HasInvariant(ITypeReference type)
{
Contract.Requires(type != null);
ITypeContract/*?*/ typeContract = this.GetTypeContract(type);
if (typeContract == null) return false;
var invs = new List<ITypeInvariant>(typeContract.Invariants);
return 0 < invs.Count;
}
public bool HasInvariant(TypeReferenceAdaptor typeAdaptor)
{
ITypeReference type = typeAdaptor.reference;
ITypeContract/*?*/ typeContract = this.GetTypeContract(type);
if (typeContract == null) return false;
var invs = new List<ITypeInvariant>(typeContract.Invariants);
return 0 < invs.Count;
}
#endregion
#region IDecodeContracts<IMethodReference,IFieldReference,TypeReferenceAdaptor> Members
public bool HasRequires(MethodReferenceAdaptor methodAdaptor)
{
IMethodReference method = methodAdaptor.reference;
IMethodContract methodContract = this.GetMethodContract(methodAdaptor);
if (methodContract == null) return false;
// TODO: handle contract initializer block!
return IteratorHelper.Any(methodContract.Preconditions, p => !p.IsModel);
}
public bool HasEnsures(MethodReferenceAdaptor methodAdaptor)
{
IMethodReference method = methodAdaptor.reference;
IMethodContract methodContract = this.GetMethodContract(methodAdaptor);
if (methodContract == null) return false;
return IteratorHelper.Any(methodContract.Postconditions, p => !p.IsModel);
}
public bool HasModelEnsures(MethodReferenceAdaptor methodAdaptor)
{
IMethodReference method = methodAdaptor.reference;
IMethodContract methodContract = this.GetMethodContract(methodAdaptor);
if (methodContract == null) return false;
return IteratorHelper.Any(methodContract.Postconditions, p => p.IsModel);
}
#endregion
#region IDecodeContracts<LocalVariableAdaptor,IParameterTypeInformation,IMethodReference,IFieldReference,TypeReferenceAdaptor> Members
public Result AccessRequires<Data, Result>(MethodReferenceAdaptor methodAdaptor, ICodeConsumer<LocalDefAdaptor, IParameterTypeInformation, MethodReferenceAdaptor, FieldReferenceAdaptor, TypeReferenceAdaptor, Data, Result> consumer, Data data)
{
Contract.Assume(consumer != null);
IMethodReference method = methodAdaptor.reference;
IMethodContract methodContract = this.GetMethodContract(methodAdaptor);
Contract.Assume(methodContract != null);
var thisRef = this.mdDecoder.This(methodAdaptor);
IParameterDefinition pDef = thisRef as IParameterDefinition;
// BUGBUG? What to do if pDef is null?
ThisSubstituter ts = new ThisSubstituter(this.host, pDef);
var requires = new List<IPrecondition>();
foreach (var p in methodContract.Preconditions)
{
if (!p.IsModel)
{
requires.Add(ts.Rewrite(p));
}
}
return consumer.Accept(this.parent.ContractProvider, new CciContractPC(requires), data);
}
public Result AccessEnsures<Data, Result>(MethodReferenceAdaptor methodAdaptor, ICodeConsumer<LocalDefAdaptor, IParameterTypeInformation, MethodReferenceAdaptor, FieldReferenceAdaptor, TypeReferenceAdaptor, Data, Result> consumer, Data data)
{
Contract.Assume(consumer != null);
IMethodReference method = methodAdaptor.reference;
IMethodContract methodContract = this.GetMethodContract(methodAdaptor);
// Contract.Assume(methodContract != null && methodContract.Postconditions != null && 0 < methodContract.Postconditions.Count);
Contract.Assume(methodContract != null);
var thisRef = this.mdDecoder.This(methodAdaptor);
IParameterDefinition pDef = thisRef as IParameterDefinition;
// BUGBUG? What to do if pDef is null?
ThisSubstituter ts = new ThisSubstituter(this.host, pDef);
var ensures = new List<IPostcondition>();
foreach (var p in methodContract.Postconditions)
{
if (!p.IsModel)
{
ensures.Add(ts.Rewrite(p));
}
}
return consumer.Accept(this.parent.ContractProvider, new CciContractPC(ensures), data);
}
public Result AccessModelEnsures<Data, Result>(MethodReferenceAdaptor methodAdaptor, ICodeConsumer<LocalDefAdaptor, IParameterTypeInformation, MethodReferenceAdaptor, FieldReferenceAdaptor, TypeReferenceAdaptor, Data, Result> consumer, Data data)
{
Contract.Assume(consumer != null);
IMethodReference method = methodAdaptor.reference;
IMethodContract methodContract = this.GetMethodContract(methodAdaptor);
Contract.Assume(methodContract != null);
var thisRef = this.mdDecoder.This(methodAdaptor);
IParameterDefinition pDef = thisRef as IParameterDefinition;
// BUGBUG? What to do if pDef is null?
ThisSubstituter ts = new ThisSubstituter(this.host, pDef);
var modelEnsures = new List<IPostcondition>();
foreach (var p in methodContract.Postconditions)
{
if (p.IsModel)
{
modelEnsures.Add(ts.Rewrite(p));
}
}
return consumer.Accept(this.parent.ContractProvider, new CciContractPC(modelEnsures), data);
}
private readonly Dictionary<TypeReferenceAdaptor, IParameterTypeInformation> thisParameterFor = new Dictionary<TypeReferenceAdaptor, IParameterTypeInformation>();
public Result AccessInvariant<Data, Result>(TypeReferenceAdaptor typeAdaptor, ICodeConsumer<LocalDefAdaptor, IParameterTypeInformation, MethodReferenceAdaptor, FieldReferenceAdaptor, TypeReferenceAdaptor, Data, Result> consumer, Data data)
{
ITypeReference type = typeAdaptor.reference;
ITypeContract/*?*/ typeContract = this.GetTypeContract(type);
Contract.Assume(typeContract != null, "why?");
var invariants = new List<ITypeInvariant>(typeContract.Invariants);
IParameterTypeInformation/*?*/ thisPar = null;
if (!this.thisParameterFor.TryGetValue(typeAdaptor, out thisPar))
{
Microsoft.Cci.MutableCodeModel.ParameterDefinition par = new Microsoft.Cci.MutableCodeModel.ParameterDefinition();
par.Name = this.host.NameTable.GetNameFor("this");
par.Index = ushort.MaxValue; // used to communicate with ArgumentIndex and ArgumentStackIndex
if (typeAdaptor.IsValueType)
{
par.Type = Microsoft.Cci.Immutable.ManagedPointerType.GetManagedPointerType(typeAdaptor.reference, host.InternFactory);
}
else
{
par.Type = typeAdaptor.reference;
}
//par.IsByReference = method.ContainingType.IsValueType;
this.thisParameterFor[typeAdaptor] = par;
thisPar = par;
}
IParameterDefinition pDef = thisPar as IParameterDefinition;
// BUGBUG? What to do if pDef is null?
ThisSubstituter ts = new ThisSubstituter(this.host, pDef);
invariants = ts.Rewrite(invariants);
return consumer.Accept(this.parent.ContractProvider, new CciContractPC(invariants), data);
}
#endregion
/// <summary>
/// Gets the contract associated with the method. If needed, the decompiler will be used
/// to extract any contracts.
/// </summary>
/// <param name="method">The method for which the contract is attached.</param>
/// <returns>
/// Null if there is no direct contract (no preconditions, postconditions, or modifies clauses)
/// on the method. That is, it does *not* do contract inheritance!
/// </returns>
private IMethodContract/*?*/ GetMethodContract(MethodReferenceAdaptor methodAdaptor)
{
Contract.Requires(methodAdaptor.reference != null);
return GetMethodContract(methodAdaptor.reference);
}
[SuppressMessage("Microsoft.Contracts", "TestAlwaysEvaluatingToAConstant")]
public IMethodContract/*?*/ GetMethodContract(IMethodReference method)
{
Contract.Requires(method != null);
#region Special hack to not extract from iterator MoveNext for now
if (method.Name.Value == "MoveNext" && this.mdDecoder.IsCompilerGenerated(method.ContainingType))
{
return null;
}
#endregion
if (this.mdDecoder.IsSpecialized(method))
{
method = CciMetadataDecoder.Unspecialized(method);
Contract.Assume(method != null);
}
IUnitReference unit = TypeHelper.GetDefiningUnitReference(method.ContainingType);
if (unit == null) return null; // But this shouldn't ever happen!! Flag an error somehow?
var mc = ContractHelper.GetMethodContractFor(host, method.ResolvedMethod);
if (mc != null) {
var wr = new WeakReference(method);
if (!this.mdDecoder.lambdaNames.ContainsKey(wr)) {
var lambdaNumberer = new LambdaNumberer(null, MemberHelper.GetMethodSignature(method), this.mdDecoder.lambdaNames);
lambdaNumberer.Traverse(mc);
this.mdDecoder.lambdaNames[wr] = "foo"; // just a flag so it doesn't get done more than once
}
}
return mc;
}
private class LambdaNumberer : CodeAndContractTraverser {
readonly private string methodName;
private int number = 0;
readonly Dictionary<WeakReference, string> table;
public LambdaNumberer(IContractProvider contractProvider, string methodName, Dictionary<WeakReference, string> table) : base(contractProvider) {
this.methodName = methodName;
this.table = table;
}
public override void TraverseChildren(IAnonymousDelegate anonymousDelegate) {
this.number++;
var name = this.methodName + this.number.ToString();
this.table[new WeakReference(anonymousDelegate)] = name;
base.TraverseChildren(anonymousDelegate);
}
}
[SuppressMessage("Microsoft.Contracts", "TestAlwaysEvaluatingToAConstant")]
internal CciILPC GetContextForMethodBody(MethodReferenceAdaptor methodAdaptor)
{
IMethodReference method = methodAdaptor.reference;
// If this method is an anonymous delegate, then it was decompiled (as part of a contract)
// and there is no IL. Just return a contract PC to walk it.
var anonymousDelegateWrapper = method as LambdaMethodReference;
if (anonymousDelegateWrapper != null)
{
return new CciILPC(new CciILPCLambdaContext(anonymousDelegateWrapper), 0);
}
// Need to first see if there is a contract in the method body's IL
IMethodContract methodContract = GetMethodContract(methodAdaptor);
IMethodDefinition methodDef = method.ResolvedMethod;
if (methodDef == null) methodDef = Dummy.Method;
CciILPCContext context;
var ops = new List<IOperation>(methodDef.Body.Operations);
if (methodContract == null || NoContracts(methodContract))
{
context = new CciILPCMethodBodyContext(method, ops);
return new CciILPC(context, 0);
}
IBlockStatement bs = null;
if (!this.mdDecoder.methodBodyCallback.extractedMethods.TryGetValue(methodDef, out bs))
{
context = new CciILPCMethodBodyContext(method, ops);
return new CciILPC(context, 0);
}
if (this.mdDecoder.IsAutoPropertyMember(methodAdaptor))
{
// auto-property getters and setters have no contracts other than preconditions and
// postconditions that are generated from any object invariants. in any case, their
// operations have no contracts in them.
context = new CciILPCMethodBodyContext(method, ops);
return new CciILPC(context, 0);
}
// First, find the primary source context for the contract.
var unit = TypeHelper.GetDefiningUnitReference(methodDef.ContainingType);
var contractLocations = new List<ILocation>(methodContract.Locations);
if (contractLocations.Count == 0)
{
throw new InvalidOperationException("Contract found, but no locations.");
}
// Find the operation whose location corresponds to the first location of the method contract
var startIndex = 0;
var count = ops.Count;
var contractLocation0 = contractLocations[0];
IILLocation ilLocation = contractLocation0 as IILLocation;
if (ilLocation != null)
{
while (startIndex < count)
{
var currentLocation = ops[startIndex].Location as IILLocation;
if (currentLocation == null)
{
throw new InvalidOperationException("Couldn't find first operation that corresponds to first location in method contract.");
}
if (currentLocation.Offset == ilLocation.Offset) break;
startIndex++;
}
}
else
{
// Depends on object identity, which is not always guaranteed.
while (startIndex < count && ops[startIndex].Location != contractLocation0) startIndex++;
}
if (startIndex == count)
{
context = new CciILPCMethodBodyContext(method, ops);
return new CciILPC(context, 0);
//throw new InvalidOperationException("Couldn't find first operation that corresponds to first location in method contract.");
}
// But that is not necessarily the first operation that is part of the contract: the location
// is, e.g., on the call to Requires, not the first operation of the code that is part of the
// method call.
int firstContractIndex;
var firstContractLocations = this.mdDecoder.GetPrimarySourceLocationsFor(unit, ops, startIndex, false, out firstContractIndex);
// Now find the last operation that is part of the method contract. Assume for now that is exactly the operation whose
// location is the same as the last location of the method contract.
var lastContractLocation = contractLocations.FindLast(l => { var ilLocation2 = l as IILLocation; return ilLocation2 == null || ilLocation2.MethodDefinition == methodDef; });
ilLocation = lastContractLocation as IILLocation;
if (ilLocation != null)
{
while (startIndex < count)
{
var currentLocation = ops[startIndex].Location as IILLocation;
if (currentLocation == null)
{
throw new InvalidOperationException("Couldn't find first operation that corresponds to first location in method contract.");
}
if (currentLocation.Offset == ilLocation.Offset) break;
startIndex++;
}
}
else
{
// Depends on object identity, which is not always guaranteed.
while (startIndex < count && ops[startIndex].Location != lastContractLocation) startIndex++;
}
var lastContractIndex = startIndex;
context = new CciILPCMethodBodyWithContractContext(method, ops, firstContractIndex, lastContractIndex);
int firstIndex = 0 < firstContractIndex ? 0 : lastContractIndex + 1;
return new CciILPC(context, firstIndex);
}
/// <summary>
/// A method contract might not have any preconditions, postconditions, or exceptional
/// postconditions because it might just have "IsPure" set to true. Or maybe for some
/// other reason.
/// </summary>
private bool NoContracts(IMethodContract methodContract)
{
return (methodContract == null
|| (IteratorHelper.EnumerableIsEmpty(methodContract.Preconditions) &&
IteratorHelper.EnumerableIsEmpty(methodContract.Postconditions) &&
IteratorHelper.EnumerableIsEmpty(methodContract.ThrownExceptions)
)
);
}
[SuppressMessage("Microsoft.Contracts", "TestAlwaysEvaluatingToAConstant")]
public ITypeContract/*?*/ GetTypeContract(ITypeReference typeReference)
{
Contract.Requires(typeReference != null);
IUnitReference unit = TypeHelper.GetDefiningUnitReference(typeReference);
if (unit == null) return null; // But this shouldn't ever happen!! Flag an error somehow?
IContractProvider lcp = this.host.GetContractExtractor(unit.UnitIdentity);
if (lcp == null) return null; // Again, isn't this an error?
var contract = lcp.GetTypeContractFor(typeReference);
if (contract != null) {
var wr = new WeakReference(typeReference);
if (!this.mdDecoder.lambdaNames.ContainsKey(wr)) {
var lambdaNumberer = new LambdaNumberer(null, TypeHelper.GetTypeName(typeReference), this.mdDecoder.lambdaNames);
lambdaNumberer.Traverse(contract);
this.mdDecoder.lambdaNames[wr] = "foo"; // just a flag so it doesn't get done more than once
}
}
return contract;
}
}
public class CciContractProvider :
IMethodCodeProvider<CciContractPC, LocalDefAdaptor, IParameterTypeInformation, MethodReferenceAdaptor, FieldReferenceAdaptor, TypeReferenceAdaptor, CciExceptionHandlerInfo>
{
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.host != null);
}
internal readonly IContractAwareHost host;
internal readonly CciMetadataDecoder mdDecoder;
internal readonly CciContractDecoder contractDecoder;
/// <summary>
/// Used just for its double-dispatch to avoid type tests and get a value that can be used in a switch-case.
/// </summary>
private object contractProviderVisitor;
internal CciContractProvider(IContractAwareHost host, CciMetadataDecoder mdDecoder, CciContractDecoder contractDecoder)
{
Contract.Requires(host != null);
this.host = host;
this.mdDecoder = mdDecoder;
this.contractDecoder = contractDecoder;
}
#region ICodeProvider<CciContractPC,IMethodReference,TypeReferenceAdaptor> Members
#if false
public R Decode<T, R>(T data, CciContractPC label, ICodeQuery<CciContractPC, TypeReferenceAdaptor, MethodReferenceAdaptor, T, R> query) {
object nestedAggregate;
object finalOperation = DecodeInternal(label, out nestedAggregate);
if (IsAtomicNested(nestedAggregate)) {
return query.Atomic(data, label);
}
if (nestedAggregate != null) {
return query.Aggregate(data, label, new CciContractPC(nestedAggregate), (nestedAggregate is ILabeledStatement || nestedAggregate is IBlockStatement));
}
if (finalOperation == null) {
// special encodings
IConditional conditional = label.Node as IConditional;
if (conditional != null) {
switch (label.Index) {
case 1:
return query.BranchCond(data, label, new CciContractPC(conditional, 4), false, true, new CciContractPC());
case 3:
return query.Branch(data, label, new CciContractPC(conditional, 6));
}
}
IConditionalStatement conditionalStatement = label.Node as IConditionalStatement;