Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMarek Safar <marek.safar@gmail.com>2016-12-14 17:04:32 +0300
committerMarek Safar <marek.safar@gmail.com>2016-12-19 16:19:30 +0300
commit9d5de96b0f21b3602e7489c8d63c8db3034228fe (patch)
treedaf3f8b835641dab06e7173b7bf47111ff503ead /mcs/class/dlr
parent79219ca718a07c3d4fe82d69b2a94dd1366e0314 (diff)
[System.Core] SLE from CoreFX including interpreter
Diffstat (limited to 'mcs/class/dlr')
-rw-r--r--mcs/class/dlr/Makefile6
-rw-r--r--mcs/class/dlr/README8
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Actions/Dummy.cs5
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/BinaryExpression.cs133
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/ConstantExpression.cs235
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/EmptyStatements.cs45
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/LightLambdaExpression.cs149
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/UnaryExpression.cs82
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/Utils.cs111
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/CompilerHelpers.cs911
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/ConstantCheck.cs128
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/DelegateHelpers.Generated.cs110
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/DelegateHelpers.cs87
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/BranchLabel.cs108
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/ILightCallSiteBinder.cs34
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/AddInstruction.cs191
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/AndInstruction.cs176
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ArithmeticInstruction.cs50
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ArrayOperations.cs134
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/CallInstruction.Generated.cs905
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/CallInstruction.cs300
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ComparisonInstruction.cs50
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ConstantInstruction.cs58
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ControlFlowInstructions.cs623
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DivInstruction.cs132
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicInstructionN.cs76
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicInstructions.Generated.cs509
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicSplatInstruction.cs55
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/EqualInstruction.cs201
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/FieldOperations.cs94
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/GreaterThanInstruction.cs171
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/GreaterThanOrEqualInstruction.cs171
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/Instruction.cs61
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionFactory.cs123
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionList.cs1074
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LabelInfo.cs309
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LessThanInstruction.cs171
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LessThanOrEqualInstruction.cs171
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LocalAccess.cs374
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ModInstruction.cs118
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/MulInstruction.cs204
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NegateInstruction.cs368
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NotEqualInstruction.cs202
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NotInstruction.cs191
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NumericConvertInstruction.cs254
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/OrInstruction.cs176
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ShlInstruction.cs160
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ShrInstruction.cs160
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/StackOperations.cs118
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/SubInstruction.cs204
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/TypeOperations.cs193
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/XorInstruction.cs176
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/InterpretedFrame.cs297
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Interpreter.cs262
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightCompiler.cs1736
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs198
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.Generated.cs756
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.cs280
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambdaClosureVisitor.cs260
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LocalVariables.cs266
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LoopCompiler.cs323
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/RuntimeVariables.cs46
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Math/BigIntegerV4.cs614
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Math/Complex64.cs280
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Properties/AssemblyInfo.cs71
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Properties/GlobalSuppressions.cs17
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ArgumentArray.cs76
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/DynamicNull.cs27
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ExceptionHelpers.cs79
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ScriptingRuntimeHelpers.cs261
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ArrayUtils.cs354
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/Assert.cs78
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CacheDict.cs114
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CollectionExtensions.cs156
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CollectionUtils.cs322
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ContractUtils.cs233
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/DynamicUtils.cs297
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ExceptionFactory.Generated.cs1050
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ExceptionUtils.cs111
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/HybridReferenceDictionary.cs170
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ListEqualityComparer.cs34
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/MathUtils.cs1230
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ReferenceEqualityComparer.cs48
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ReflectionUtils.cs1951
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/StringUtils.cs269
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/TypeUtils.cs375
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/BinaryOperationBinder.cs148
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/BindingRestrictions.cs366
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallInfo.cs109
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSite.cs734
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteBinder.cs232
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteHelpers.cs52
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteOps.cs161
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/ConvertBinder.cs101
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CreateInstanceBinder.cs87
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DeleteIndexBinder.cs87
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DeleteMemberBinder.cs102
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicMetaObject.cs332
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicMetaObjectBinder.cs287
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicObject.cs803
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/ExpandoClass.cs183
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/ExpandoObject.cs1097
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/GetIndexBinder.cs88
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/GetMemberBinder.cs100
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/IDynamicMetaObjectProvider.cs38
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/IInvokeOnGetBinder.cs36
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeBinder.cs88
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeMemberBinder.cs129
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/RuleCache.cs116
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/SetIndexBinder.cs97
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/SetMemberBinder.cs106
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/UnaryOperationBinder.cs129
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/UpdateDelegates.Generated.cs2658
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/BinaryExpression.cs2652
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/BlockExpression.cs813
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/CatchBlock.cs172
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ConditionalExpression.cs226
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ConstantExpression.cs136
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DebugInfoExpression.cs243
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DebugViewWriter.cs1179
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DefaultExpression.cs87
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DynamicExpression.cs848
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ElementInit.cs135
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/Expression.DebuggerProxy.cs455
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/Expression.cs402
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionStringBuilder.cs759
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionType.cs377
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionVisitor.cs679
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/GotoExpression.cs371
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/IArgumentProvider.cs77
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/IndexExpression.cs451
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/InvocationExpression.cs199
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LabelExpression.cs115
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LabelTarget.cs102
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LambdaExpression.cs666
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ListArgumentProvider.cs143
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ListInitExpression.cs231
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LoopExpression.cs135
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberAssignment.cs107
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberBinding.cs82
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberExpression.cs362
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberInitExpression.cs178
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberListBinding.cs137
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberMemberBinding.cs151
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MethodCallExpression.cs1041
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/NewArrayExpression.cs234
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/NewExpression.cs326
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ParameterExpression.cs222
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/RuntimeVariablesExpression.cs117
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/SwitchCase.cs105
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/SwitchExpression.cs298
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/SymbolDocumentInfo.cs153
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/TryExpression.cs228
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/TypeBinaryExpression.cs211
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/TypeUtils.cs715
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/UnaryExpression.cs995
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/AnalyzedTree.cs37
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/AssemblyGen.cs177
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/BoundConstants.cs191
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/Closure.cs51
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/CompilerScope.Storage.cs186
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/CompilerScope.cs465
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ConstantCheck.cs106
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DebugInfoGenerator.cs74
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.Generated.cs293
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.cs50
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ExpressionQuoter.cs247
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/HoistedLocals.cs101
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ILGen.cs1051
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/KeyedQueue.cs88
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LabelInfo.cs357
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Address.cs334
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Binary.cs707
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.ControlFlow.cs257
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Expressions.cs1085
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Generated.cs282
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Lambda.cs199
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Logical.cs645
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Statements.cs821
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Unary.cs344
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.cs327
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/OffsetTrackingILGenerator.cs366
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/RuntimeVariableList.cs123
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/Set.cs94
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Bindings.cs228
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Generated.cs272
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Temps.cs308
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.cs982
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/SymbolDocumentGenerator.cs72
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/SymbolGuids.cs12
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/VariableBinder.cs244
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/GlobalSuppressions.cs20
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Microsoft.Scripting.Core.csproj163
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Microsoft.Scripting.ExtensionAttribute.csproj104
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Properties/AssemblyInfo.cs65
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Properties/ExtensionAssemblyInfo.cs62
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Stubs.cs48
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/System.Core.csproj245
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Action.cs609
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/CacheDict.cs113
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/CollectionExtensions.cs202
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ContractUtils.cs97
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ExceptionFactory.Generated.cs2729
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Extension.cs10
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Function.cs649
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Helpers.cs53
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/IRuntimeVariables.cs33
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReadOnlyCollectionBuilder.cs523
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReadOnlyDictionary.cs203
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReferenceEqualityComparer.cs34
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReflectionUtils.cs7
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/StrongBox.cs63
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/TrueReadOnlyCollection.cs30
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/TypeExtensions.cs114
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting/ArgumentTypeException.cs38
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting/InvalidImplementationException.cs38
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting/PlatformAdaptationLayer.cs476
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting/Runtime/NotNullAttribute.cs40
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting/Runtime/ParamDictionaryAttribute.cs55
-rw-r--r--mcs/class/dlr/Runtime/Microsoft.Scripting/Stubs.cs116
-rwxr-xr-xmcs/class/dlr/sync.sh5
221 files changed, 1 insertions, 67396 deletions
diff --git a/mcs/class/dlr/Makefile b/mcs/class/dlr/Makefile
index 2a701832e6d..bb352b71fb4 100644
--- a/mcs/class/dlr/Makefile
+++ b/mcs/class/dlr/Makefile
@@ -4,11 +4,7 @@ SUBDIRS =
include ../../build/rules.make
DISTFILES = \
- Runtime/Microsoft.Dynamic/*.cs \
- Runtime/Microsoft.Scripting.Core/Actions/*.cs \
- Runtime/Microsoft.Scripting.Core/Ast/*.cs \
- Runtime/Microsoft.Scripting.Core/Compiler/*.cs \
- Runtime/Microsoft.Scripting.Core/Utils/*.cs
+ Runtime/Microsoft.Dynamic/*.cs
all-local install-local clean-local test-local run-test-local run-test-ondotnet-local uninstall-local doc-update-local csproj-local:
diff --git a/mcs/class/dlr/README b/mcs/class/dlr/README
deleted file mode 100644
index 7ec5bea3410..00000000000
--- a/mcs/class/dlr/README
+++ /dev/null
@@ -1,8 +0,0 @@
-This is fork of Microsoft DLR source code. The original code was published at
-http://dlr.codeplex.com/ which had the code used for .NET 4.0
-System.Linq.Expression public API. Since them the code was migrated to
-https://github.com/IronLanguages/main but it no longer has the goal to offer
-compatible System.Linq.Expression API and we cannot use some part of it.
-
-We want to have minimum local changes. Importatant changes need to be marked
-using easily recognizable marker (like MONO_INTERPRETER) for easier merging. \ No newline at end of file
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Actions/Dummy.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Actions/Dummy.cs
deleted file mode 100644
index 880a99a8e2a..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Actions/Dummy.cs
+++ /dev/null
@@ -1,5 +0,0 @@
-namespace Microsoft.Scripting.Actions {
- class Dummy
- {
- }
-} \ No newline at end of file
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/BinaryExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/BinaryExpression.cs
deleted file mode 100644
index 10f8a9658c9..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/BinaryExpression.cs
+++ /dev/null
@@ -1,133 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Reflection;
-using System.Dynamic;
-using Microsoft.Scripting.Utils;
-using AstUtils = Microsoft.Scripting.Ast.Utils;
-
-namespace Microsoft.Scripting.Ast {
- public static partial class Utils {
-#if !MONO_INTERPRETER
- /// <summary>
- /// Null coalescing expression
- /// {result} ::= ((tmp = {_left}) == null) ? {right} : tmp
- /// '??' operator in C#.
- /// </summary>
- public static Expression Coalesce(Expression left, Expression right, out ParameterExpression temp) {
- return CoalesceInternal(left, right, null, false, out temp);
- }
-
- /// <summary>
- /// True coalescing expression.
- /// {result} ::= IsTrue(tmp = {left}) ? {right} : tmp
- /// Generalized AND semantics.
- /// </summary>
- public static Expression CoalesceTrue(Expression left, Expression right, MethodInfo isTrue, out ParameterExpression temp) {
- ContractUtils.RequiresNotNull(isTrue, "isTrue");
- return CoalesceInternal(left, right, isTrue, false, out temp);
- }
-
- /// <summary>
- /// False coalescing expression.
- /// {result} ::= IsTrue(tmp = {left}) ? tmp : {right}
- /// Generalized OR semantics.
- /// </summary>
- public static Expression CoalesceFalse(Expression left, Expression right, MethodInfo isTrue, out ParameterExpression temp) {
- ContractUtils.RequiresNotNull(isTrue, "isTrue");
- return CoalesceInternal(left, right, isTrue, true, out temp);
- }
-
- private static Expression CoalesceInternal(Expression left, Expression right, MethodInfo isTrue, bool isReverse, out ParameterExpression temp) {
- ContractUtils.RequiresNotNull(left, "left");
- ContractUtils.RequiresNotNull(right, "right");
-
- // A bit too strict, but on a safe side.
- ContractUtils.Requires(left.Type == right.Type, "Expression types must match");
-
- temp = Expression.Variable(left.Type, "tmp_left");
-
- Expression condition;
- if (isTrue != null) {
- ContractUtils.Requires(isTrue.ReturnType == typeof(bool), "isTrue", "Predicate must return bool.");
- ParameterInfo[] parameters = isTrue.GetParameters();
- ContractUtils.Requires(parameters.Length == 1, "isTrue", "Predicate must take one parameter.");
- ContractUtils.Requires(isTrue.IsStatic && isTrue.IsPublic, "isTrue", "Predicate must be public and static.");
-
- Type pt = parameters[0].ParameterType;
- ContractUtils.Requires(TypeUtils.CanAssign(pt, left.Type), "left", "Incorrect left expression type");
- condition = Expression.Call(isTrue, Expression.Assign(temp, left));
- } else {
- ContractUtils.Requires(TypeUtils.CanCompareToNull(left.Type), "left", "Incorrect left expression type");
- condition = Expression.Equal(Expression.Assign(temp, left), AstUtils.Constant(null, left.Type));
- }
-
- Expression t, f;
- if (isReverse) {
- t = temp;
- f = right;
- } else {
- t = right;
- f = temp;
- }
-
- return Expression.Condition(condition, t, f);
- }
-
- public static Expression Coalesce(LambdaBuilder builder, Expression left, Expression right) {
- ParameterExpression temp;
- Expression result = Coalesce(left, right, out temp);
- builder.AddHiddenVariable(temp);
- return result;
- }
-
- /// <summary>
- /// True coalescing expression.
- /// {result} ::= IsTrue(tmp = {left}) ? {right} : tmp
- /// Generalized AND semantics.
- /// </summary>
- public static Expression CoalesceTrue(LambdaBuilder builder, Expression left, Expression right, MethodInfo isTrue) {
- ContractUtils.RequiresNotNull(isTrue, "isTrue");
- ParameterExpression temp;
- Expression result = CoalesceTrue(left, right, isTrue, out temp);
- builder.AddHiddenVariable(temp);
- return result;
- }
-
- /// <summary>
- /// False coalescing expression.
- /// {result} ::= IsTrue(tmp = {left}) ? tmp : {right}
- /// Generalized OR semantics.
- /// </summary>
- public static Expression CoalesceFalse(LambdaBuilder builder, Expression left, Expression right, MethodInfo isTrue) {
- ContractUtils.RequiresNotNull(isTrue, "isTrue");
- ParameterExpression temp;
- Expression result = CoalesceFalse(left, right, isTrue, out temp);
- builder.AddHiddenVariable(temp);
- return result;
- }
-#endif
- public static BinaryExpression Update(this BinaryExpression expression, Expression left, Expression right) {
- return expression.Update(left, expression.Conversion, right);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/ConstantExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/ConstantExpression.cs
deleted file mode 100644
index 881f0a3351c..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/ConstantExpression.cs
+++ /dev/null
@@ -1,235 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-#if FEATURE_NUMERICS
-using BigInt = System.Numerics.BigInteger;
-using Complex = System.Numerics.Complex;
-#endif
-
-using System;
-using System.Reflection;
-using Microsoft.Scripting.Generation;
-using Microsoft.Scripting.Math;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Ast {
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
- public static partial class Utils {
- private static readonly ConstantExpression TrueLiteral = Expression.Constant(true, typeof(bool));
- private static readonly ConstantExpression FalseLiteral = Expression.Constant(false, typeof(bool));
- private static readonly ConstantExpression NullLiteral = Expression.Constant(null, typeof(object));
- private static readonly ConstantExpression EmptyStringLiteral = Expression.Constant(String.Empty, typeof(string));
- private static readonly ConstantExpression[] IntCache = new ConstantExpression[100];
-
- /// <summary>
- /// Wraps the given value in a WeakReference and returns a tree that will retrieve
- /// the value from the WeakReference.
- /// </summary>
- public static MemberExpression WeakConstant(object value) {
- System.Diagnostics.Debug.Assert(!(value is Expression));
- return Expression.Property(
- Constant(new WeakReference(value)),
- typeof(WeakReference).GetDeclaredProperty("Target")
- );
- }
-
- public static ConstantExpression Constant(object value, Type type) {
- return Expression.Constant(value, type);
- }
-
- // The helper API should return ConstantExpression after SymbolConstantExpression goes away
- public static Expression Constant(object value) {
- if (value == null) {
- return NullLiteral;
- }
-
-#if !MONO_INTERPRETER
- BigInteger bi = value as BigInteger;
- if ((object)bi != null) {
- return BigIntegerConstant(bi);
-#endif
-
-#if FEATURE_NUMERICS
- if (value is BigInt)
- return BigIntConstant((BigInt)value);
- if (value is Complex)
- return ComplexConstant((Complex)value);
-#endif
-
-#if !MONO_INTERPRETER
- if (value is Complex64)
- return Complex64Constant((Complex64)value);
-#endif
- if (value is Type) {
- return Expression.Constant(value, typeof(Type));
- } else if (value is ConstructorInfo) {
- return Expression.Constant(value, typeof(ConstructorInfo));
- } else if (value is EventInfo) {
- return Expression.Constant(value, typeof(EventInfo));
- } else if (value is FieldInfo) {
- return Expression.Constant(value, typeof(FieldInfo));
- } else if (value is MethodInfo) {
- return Expression.Constant(value, typeof(MethodInfo));
- } else if (value is PropertyInfo) {
- return Expression.Constant(value, typeof(PropertyInfo));
- } else {
- Type t = value.GetType();
- if (!t.GetTypeInfo().IsEnum) {
- switch (t.GetTypeCode()) {
- case TypeCode.Boolean:
- return (bool)value ? TrueLiteral : FalseLiteral;
- case TypeCode.Int32:
- int x = (int)value;
- int cacheIndex = x + 2;
- if (cacheIndex >= 0 && cacheIndex < IntCache.Length) {
- ConstantExpression res;
- if ((res = IntCache[cacheIndex]) == null) {
- IntCache[cacheIndex] = res = Constant(x, typeof(int));
- }
- return res;
- }
- break;
- case TypeCode.String:
- if (String.IsNullOrEmpty((string)value)) {
- return EmptyStringLiteral;
- }
- break;
- }
- }
- return Expression.Constant(value);
- }
- }
-
-#if !MONO_INTERPRETER
- private static Expression BigIntegerConstant(BigInteger value) {
- int ival;
- if (value.AsInt32(out ival)) {
- return Expression.Call(
- new Func<int, BigInteger>(BigInteger.Create).GetMethodInfo(),
- Constant(ival)
- );
- }
-
- long lval;
- if (value.AsInt64(out lval)) {
- return Expression.Call(
- new Func<long, BigInteger>(BigInteger.Create).GetMethodInfo(),
- Constant(lval)
- );
- }
-
-#if !FEATURE_NUMERICS
- return Expression.Call(
- new Func<int, uint[], BigInteger>(CompilerHelpers.CreateBigInteger).Method,
- Constant((int)value.Sign),
- CreateArray<uint>(value.GetWords())
- );
-#else
- return Expression.Call(
- new Func<bool, byte[], BigInteger>(CompilerHelpers.CreateBigInteger).GetMethodInfo(),
- Constant(value.Sign < 0),
- CreateArray<byte>(value.Abs().ToByteArray())
- );
- }
-
- private static Expression BigIntConstant(BigInt value) {
- int ival;
- if (value.AsInt32(out ival)) {
- return Expression.Call(
- new Func<int, BigInt>(CompilerHelpers.CreateBigInt).GetMethodInfo(),
- Constant(ival)
- );
- }
-
- long lval;
- if (value.AsInt64(out lval)) {
- return Expression.Call(
- new Func<long, BigInt>(CompilerHelpers.CreateBigInt).GetMethodInfo(),
- Constant(lval)
- );
- }
-
- return Expression.Call(
- new Func<bool, byte[], BigInt>(CompilerHelpers.CreateBigInt).GetMethodInfo(),
- Constant(value.Sign < 0),
- CreateArray<byte>(value.Abs().ToByteArray())
- );
-#endif
- }
-#endif
- private static Expression CreateArray<T>(T[] array) {
- // TODO: could we use blobs?
- Expression[] init = new Expression[array.Length];
- for (int i = 0; i < init.Length; i++) {
- init[i] = Constant(array[i]);
- }
- return Expression.NewArrayInit(typeof(T), init);
- }
-
-#if FEATURE_NUMERICS
- private static Expression ComplexConstant(Complex value) {
- if (value.Real != 0.0) {
- if (value.Imaginary() != 0.0) {
- return Expression.Call(
- new Func<double, double, Complex>(MathUtils.MakeComplex).GetMethodInfo(),
- Constant(value.Real),
- Constant(value.Imaginary())
- );
- } else {
- return Expression.Call(
- new Func<double, Complex>(MathUtils.MakeReal).GetMethodInfo(),
- Constant(value.Real)
- );
- }
- } else {
- return Expression.Call(
- new Func<double, Complex>(MathUtils.MakeImaginary).GetMethodInfo(),
- Constant(value.Imaginary())
- );
- }
- }
-#endif
-
-#if !MONO_INTERPRETER
- private static Expression Complex64Constant(Complex64 value) {
- if (value.Real != 0.0) {
- if (value.Imag != 0.0) {
- return Expression.Call(
- new Func<double, double, Complex64>(Complex64.Make).GetMethodInfo(),
- Constant(value.Real),
- Constant(value.Imag)
- );
- } else {
- return Expression.Call(
- new Func<double, Complex64>(Complex64.MakeReal).GetMethodInfo(),
- Constant(value.Real)
- );
- }
- } else {
- return Expression.Call(
- new Func<double, Complex64>(Complex64.MakeImaginary).GetMethodInfo(),
- Constant(value.Imag)
- );
- }
- }
-#endif
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/EmptyStatements.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/EmptyStatements.cs
deleted file mode 100644
index 0968a2ca616..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/EmptyStatements.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Dynamic;
-
-namespace Microsoft.Scripting.Ast {
- public static partial class Utils {
- private static readonly DefaultExpression VoidInstance = Expression.Empty();
-
- public static DefaultExpression Empty() {
- return VoidInstance;
- }
-
- public static DefaultExpression Default(Type type) {
- if (type == typeof(void)) {
- return Empty();
- }
- return Expression.Default(type);
- }
- }
-}
-
-
-
-
-
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/LightLambdaExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/LightLambdaExpression.cs
deleted file mode 100644
index 6b2a08e3443..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/LightLambdaExpression.cs
+++ /dev/null
@@ -1,149 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using Microsoft.Scripting.Interpreter;
-using Microsoft.Scripting.Generation;
-
-namespace Microsoft.Scripting.Ast {
- public class LightLambdaExpression : Expression {
- private readonly Expression _body;
- private readonly Type _retType;
- private readonly string _name;
- private readonly IList<ParameterExpression> _args;
-
- internal LightLambdaExpression(Type retType, Expression body, string name, IList<ParameterExpression> args) {
- _body = body;
- _name = name;
- _args = args;
- _retType = retType;
- }
-
- public Expression Body {
- get {
- return _body;
- }
- }
-
- public string Name {
- get {
- return _name;
- }
- }
-
- public IList<ParameterExpression> Parameters {
- get {
- return _args;
- }
- }
-
- internal virtual LambdaExpression ReduceToLambdaWorker() {
- throw new InvalidOperationException();
- }
-
- public Delegate Compile() {
- return Compile(-1);
- }
-
- public Delegate Compile(int compilationThreshold) {
- return new LightCompiler(compilationThreshold).CompileTop(this).CreateDelegate();
- }
-
- public override ExpressionType NodeType {
- get { return ExpressionType.Extension; }
- }
-
- public override bool CanReduce {
- get { return true; }
- }
-
- public override Expression Reduce() {
- return ReduceToLambdaWorker();
- }
-
- public Type ReturnType {
- get {
- return _retType;
- }
- }
- }
-
- internal class TypedLightLambdaExpression : LightLambdaExpression {
- private readonly Type _delegateType;
-
- internal TypedLightLambdaExpression(Type retType, Type delegateType, Expression body, string name, IList<ParameterExpression> args)
- : base(retType, body, name, args) {
- _delegateType = delegateType;
- }
-
- internal override LambdaExpression ReduceToLambdaWorker() {
- return Expression.Lambda(
- _delegateType,
- Body,
- Name,
- Parameters
- );
- }
-
- public override Type Type {
- get { return _delegateType; }
- }
- }
-
- public class LightExpression<T> : LightLambdaExpression {
- internal LightExpression(Type retType, Expression body, string name, IList<ParameterExpression> args)
- : base(retType, body, name, args) {
- }
-
- public Expression<T> ReduceToLambda() {
- return Expression.Lambda<T>(Body, Name, Parameters);
- }
-
- public override Type Type {
- get { return typeof(T); }
- }
-
- public new T Compile() {
- return Compile(-1);
- }
-
- public new T Compile(int compilationThreshold) {
- return (T)(object)new LightCompiler(compilationThreshold).CompileTop(this).CreateDelegate();
- }
-
- internal override LambdaExpression ReduceToLambdaWorker() {
- return ReduceToLambda();
- }
- }
-
- public static partial class Utils {
- public static LightExpression<T> LightLambda<T>(Type retType, Expression body, string name, IList<ParameterExpression> args) {
- return new LightExpression<T>(retType, body, name, args);
- }
-
- public static LightLambdaExpression LightLambda(Type retType, Type delegateType, Expression body, string name, IList<ParameterExpression> args) {
- return new TypedLightLambdaExpression(retType, delegateType, body, name, args);
- }
- }
-
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/UnaryExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/UnaryExpression.cs
deleted file mode 100644
index 19477b2320e..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/UnaryExpression.cs
+++ /dev/null
@@ -1,82 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-using System.Reflection;
-
-namespace Microsoft.Scripting.Ast {
- public static partial class Utils {
- /// <summary>
- /// Converts an expression to a void type.
- /// </summary>
- /// <param name="expression">An <see cref="Expression"/> to convert to void. </param>
- /// <returns>An <see cref="Expression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.ConvertChecked" /> and the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> and <see cref="P:System.Linq.Expressions.Expression.Type" /> property set to void.</returns>
- public static Expression Void(Expression expression) {
- ContractUtils.RequiresNotNull(expression, "expression");
- if (expression.Type == typeof(void)) {
- return expression;
- }
- return Expression.Block(expression, Utils.Empty());
- }
-
- public static Expression Convert(Expression expression, Type type) {
- ContractUtils.RequiresNotNull(expression, "expression");
-
- if (expression.Type == type) {
- return expression;
- }
-
- if (expression.Type == typeof(void)) {
- return Expression.Block(expression, Utils.Default(type));
- }
-
- if (type == typeof(void)) {
- return Void(expression);
- }
-
- // TODO: this is not the right level for this to be at. It should
- // be pushed into languages if they really want this behavior.
- if (type == typeof(object)) {
- return Box(expression);
- }
-
- return Expression.Convert(expression, type);
- }
-
- /// <summary>
- /// Returns an expression that boxes a given value. Uses boxed objects cache for Int32 and Boolean types.
- /// </summary>
- public static Expression Box(Expression expression) {
- MethodInfo m;
- if (expression.Type == typeof(int)) {
- m = ScriptingRuntimeHelpers.Int32ToObjectMethod;
- } else if (expression.Type == typeof(bool)) {
- m = ScriptingRuntimeHelpers.BooleanToObjectMethod;
- } else {
- m = null;
- }
-
- return Expression.Convert(expression, typeof(object), m);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/Utils.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/Utils.cs
deleted file mode 100644
index 165a42458e8..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/Utils.cs
+++ /dev/null
@@ -1,111 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Reflection;
-using System.Dynamic;
-using Microsoft.Scripting.Utils;
-using AstUtils = Microsoft.Scripting.Ast.Utils;
-
-namespace Microsoft.Scripting.Ast {
- [Flags]
- public enum ExpressionAccess {
- None = 0,
- Read = 1,
- Write = 2,
- ReadWrite = Read | Write,
- }
-
- public static partial class Utils {
- /// <summary>
- /// Determines whether specified expression type represents an assignment.
- /// </summary>
- /// <returns>
- /// True if the expression type represents an assignment.
- /// </returns>
- /// <remarks>
- /// Note that some other nodes can also assign to variables, members or array items:
- /// MemberInit, NewArrayInit, Call with ref params, New with ref params, Dynamic with ref params.
- /// </remarks>
- public static bool IsAssignment(this ExpressionType type) {
- return IsWriteOnlyAssignment(type) || IsReadWriteAssignment(type);
- }
-
- public static bool IsWriteOnlyAssignment(this ExpressionType type) {
- return type == ExpressionType.Assign;
- }
-
- public static bool IsReadWriteAssignment(this ExpressionType type) {
- switch (type) {
- // unary:
- case ExpressionType.PostDecrementAssign:
- case ExpressionType.PostIncrementAssign:
- case ExpressionType.PreDecrementAssign:
- case ExpressionType.PreIncrementAssign:
-
- // binary - compound:
- case ExpressionType.AddAssign:
- case ExpressionType.AddAssignChecked:
- case ExpressionType.AndAssign:
- case ExpressionType.DivideAssign:
- case ExpressionType.ExclusiveOrAssign:
- case ExpressionType.LeftShiftAssign:
- case ExpressionType.ModuloAssign:
- case ExpressionType.MultiplyAssign:
- case ExpressionType.MultiplyAssignChecked:
- case ExpressionType.OrAssign:
- case ExpressionType.PowerAssign:
- case ExpressionType.RightShiftAssign:
- case ExpressionType.SubtractAssign:
- case ExpressionType.SubtractAssignChecked:
- return true;
- }
- return false;
- }
-
- /// <summary>
- /// Determines if the left child of the given expression is read or written to or both.
- /// </summary>
- public static ExpressionAccess GetLValueAccess(this ExpressionType type) {
- if (type.IsReadWriteAssignment()) {
- return ExpressionAccess.ReadWrite;
- }
-
- if (type.IsWriteOnlyAssignment()) {
- return ExpressionAccess.Write;
- }
-
- return ExpressionAccess.Read;
- }
-
- public static bool IsLValue(this ExpressionType type) {
- // see Expression.RequiresCanWrite
- switch (type) {
- case ExpressionType.Index:
- case ExpressionType.MemberAccess:
- case ExpressionType.Parameter:
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/CompilerHelpers.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/CompilerHelpers.cs
deleted file mode 100644
index 5f3cba2ff6e..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/CompilerHelpers.cs
+++ /dev/null
@@ -1,911 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_NUMERICS
-using BigInt = System.Numerics.BigInteger;
-#endif
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#endif
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Dynamic;
-using System.Linq;
-using System.Reflection;
-using System.Threading;
-#if FEATURE_REFEMIT
-using System.Reflection.Emit;
-#endif
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Actions;
-using Microsoft.Scripting.Ast;
-using Microsoft.Scripting.Interpreter;
-using Microsoft.Scripting.Math;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-using AstUtils = Microsoft.Scripting.Ast.Utils;
-
-namespace Microsoft.Scripting.Generation {
- // TODO: keep this?
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
- public delegate void ActionRef<T0, T1>(ref T0 arg0, ref T1 arg1);
-
- public static class CompilerHelpers {
- public const MethodAttributes PublicStatic = MethodAttributes.Public | MethodAttributes.Static;
- private static MethodInfo _CreateInstanceMethod;
-
- private static int _Counter; // for generating unique names for lambda methods
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- public static object GetMissingValue(Type type) {
- ContractUtils.RequiresNotNull(type, "type");
-
- if (type.IsByRef) type = type.GetElementType();
- if (type.IsEnum()) return Activator.CreateInstance(type);
-
- switch (type.GetTypeCode()) {
- default:
- case TypeCode.Object:
- // struct
- if (type.IsSealed() && type.IsValueType()) {
- return Activator.CreateInstance(type);
- } else if (type == typeof(object)) {
- // parameter of type object receives the actual Missing value
- return Missing.Value;
- } else if (!type.IsValueType()) {
- return null;
- } else {
- throw Error.CantCreateDefaultTypeFor(type);
- }
- case TypeCode.Empty:
- case TypeCode.DBNull:
- case TypeCode.String:
- return null;
-
- case TypeCode.Boolean: return false;
- case TypeCode.Char: return '\0';
- case TypeCode.SByte: return (sbyte)0;
- case TypeCode.Byte: return (byte)0;
- case TypeCode.Int16: return (short)0;
- case TypeCode.UInt16: return (ushort)0;
- case TypeCode.Int32: return (int)0;
- case TypeCode.UInt32: return (uint)0;
- case TypeCode.Int64: return 0L;
- case TypeCode.UInt64: return 0UL;
- case TypeCode.Single: return 0.0f;
- case TypeCode.Double: return 0.0D;
- case TypeCode.Decimal: return (decimal)0;
- case TypeCode.DateTime: return DateTime.MinValue;
- }
- }
-
- public static bool IsStatic(MethodBase mi) {
- return mi.IsConstructor || mi.IsStatic;
- }
-
- /// <summary>
- /// True if the MethodBase is method which is going to construct an object
- /// </summary>
- public static bool IsConstructor(MethodBase mb) {
- if (mb.IsConstructor) {
- return true;
- }
-
- if (mb.IsGenericMethod) {
- MethodInfo mi = mb as MethodInfo;
-
- if (_CreateInstanceMethod == null)
- Interlocked.CompareExchange (ref _CreateInstanceMethod, typeof(ScriptingRuntimeHelpers).GetMethod ("CreateInstance"), null);
-
- if (mi.GetGenericMethodDefinition() == _CreateInstanceMethod) {
- return true;
- }
- }
-
- return false;
- }
-
- public static T[] MakeRepeatedArray<T>(T item, int count) {
- T[] ret = new T[count];
- for (int i = 0; i < count; i++) ret[i] = item;
- return ret;
- }
-
- public static bool IsComparisonOperator(ExpressionType op) {
- switch (op) {
- case ExpressionType.LessThan: return true;
- case ExpressionType.LessThanOrEqual: return true;
- case ExpressionType.GreaterThan: return true;
- case ExpressionType.GreaterThanOrEqual: return true;
- case ExpressionType.Equal: return true;
- case ExpressionType.NotEqual: return true;
- }
- return false;
- }
-
- /// <summary>
- /// Returns the System.Type for any object, including null. The type of null
- /// is represented by None.Type and all other objects just return the
- /// result of Object.GetType
- /// </summary>
- public static Type GetType(object obj) {
- if (obj == null) {
- return typeof(DynamicNull);
- }
-
- return obj.GetType();
- }
-
- /// <summary>
- /// Simply returns a Type[] from calling GetType on each element of args.
- /// </summary>
- public static Type[] GetTypes(object[] args) {
- Type[] types = new Type[args.Length];
- for (int i = 0; i < args.Length; i++) {
- types[i] = GetType(args[i]);
- }
- return types;
- }
-
- /// <summary>
- /// EMITTED
- /// Used by default method binder to check types of splatted arguments.
- /// </summary>
- public static bool TypesEqual(IList args, int start, Type[] types) {
- for (int i = 0; i < types.Length; i++) {
- object arg = args[start + i];
- if (types[i] != (arg != null ? arg.GetType() : null)) {
- return false;
- }
- }
- return true;
- }
-
- public static bool CanOptimizeMethod(MethodBase method) {
- if (method.ContainsGenericParameters ||
- method.IsProtected() ||
- method.IsPrivate ||
- !method.DeclaringType.IsVisible()) {
- return false;
- }
- return true;
- }
-
- /// <summary>
- /// Given a MethodInfo which may be declared on a non-public type this attempts to
- /// return a MethodInfo which will dispatch to the original MethodInfo but is declared
- /// on a public type.
- ///
- /// Returns the original method if the method if a public version cannot be found.
- /// </summary>
- public static MethodInfo TryGetCallableMethod(Type targetType, MethodInfo method) {
- if (method.DeclaringType == null || method.DeclaringType.IsVisible()) {
- return method;
- }
-
- // first try and get it from the base type we're overriding...
- MethodInfo baseMethod = method.GetRuntimeBaseDefinition();
-
- if (baseMethod.DeclaringType.IsVisible() || baseMethod.DeclaringType.IsInterface()) {
- // We need to instantiate the method as GetBaseDefinition might return a generic definition of the base method:
- if (baseMethod.IsGenericMethodDefinition) {
- baseMethod = baseMethod.MakeGenericMethod(method.GetGenericArguments());
- }
- return baseMethod;
- }
-
-#if WIN8 // TODO: interface map, method handle
- foreach (Type iface in targetType.GetImplementedInterfaces()) {
- dynamic mapping = ((dynamic)targetType).GetInterfaceMap(iface);
- for (int i = 0; i < mapping.TargetMethods.Length; i++) {
- MethodInfo targetMethod = mapping.TargetMethods[i];
- if (targetMethod != null && ((dynamic)targetMethod).MethodHandle == ((dynamic)method).MethodHandle) {
- return mapping.InterfaceMethods[i];
- }
- }
- }
-#else
- // maybe we can get it from an interface on the type this
- // method came from...
- foreach (Type iface in targetType.GetImplementedInterfaces()) {
- if (iface.IsPublic()) {
- InterfaceMapping mapping = targetType.GetInterfaceMap(iface);
- for (int i = 0; i < mapping.TargetMethods.Length; i++) {
- MethodInfo targetMethod = mapping.TargetMethods[i];
- if (targetMethod != null && targetMethod.MethodHandle == method.MethodHandle) {
- return mapping.InterfaceMethods[i];
- }
- }
- }
- }
-#endif
- return method;
- }
-
- /// <summary>
- /// Non-public types can have public members that we find when calling type.GetMember(...). This
- /// filters out the non-visible members by attempting to resolve them to the correct visible type.
- ///
- /// If no correct visible type can be found then the member is not visible and we won't call it.
- /// </summary>
- public static IEnumerable<MemberInfo> FilterNonVisibleMembers(Type targetType, IEnumerable<MemberInfo> members) {
- if (targetType.IsVisible()) {
- return members;
- } else {
- return FilterNonVisibleMembersIterator(targetType, members);
- }
- }
-
- public static IEnumerable<MemberInfo> FilterNonVisibleMembersIterator(Type targetType, IEnumerable<MemberInfo> members) {
- foreach (var member in members) {
- MemberInfo visible = TryGetVisibleMember(targetType, member);
- if (visible != null) {
- yield return visible;
- }
- }
- }
-
- public static MemberInfo TryGetVisibleMember(Type targetType, MemberInfo member) {
- MethodInfo method;
- PropertyInfo property;
- EventInfo evnt;
-
- MethodInfo mi;
- MemberInfo visible = null;
-
- if ((method = member as MethodInfo) != null) {
- mi = TryGetCallableMethod(targetType, method);
- if (CompilerHelpers.IsVisible(mi)) {
- visible = mi;
- }
- } else if ((property = member as PropertyInfo) != null) {
- mi = TryGetCallableMethod(targetType, property.GetGetMethod() ?? property.GetSetMethod());
- if (CompilerHelpers.IsVisible(mi)) {
- visible = mi.DeclaringType.GetDeclaredProperty(property.Name);
- }
- } else if ((evnt = member as EventInfo) != null) {
- mi = TryGetCallableMethod(targetType, evnt.GetAddMethod() ?? evnt.GetRemoveMethod() ?? evnt.GetRaiseMethod());
- if (CompilerHelpers.IsVisible(mi)) {
- visible = mi.DeclaringType.GetDeclaredEvent(evnt.Name);
- }
- }
-
- // all others can't be exposed out this way
- return visible;
- }
-
-#if !WIN8
- /// <summary>
- /// Sees if two MemberInfos point to the same underlying construct in IL. This
- /// ignores the ReflectedType property which exists on MemberInfos which
- /// causes direct comparisons to be false even if they are the same member.
- /// </summary>
- public static bool MemberEquals(this MemberInfo self, MemberInfo other) {
- if ((self == null) != (other == null)) {
- // one null, the other isn't.
- return false;
- } else if (self == null) {
- // both null
- return true;
- }
-
- if (self.MemberType != other.MemberType) {
- return false;
- }
-
- switch (self.MemberType) {
- case MemberTypes.Field:
- return ((FieldInfo)self).FieldHandle.Equals(((FieldInfo)other).FieldHandle);
- case MemberTypes.Method:
- return ((MethodInfo)self).MethodHandle.Equals(((MethodInfo)other).MethodHandle);
- case MemberTypes.Constructor:
- return ((ConstructorInfo)self).MethodHandle.Equals(((ConstructorInfo)other).MethodHandle);
- case MemberTypes.NestedType:
- case MemberTypes.TypeInfo:
- return ((Type)self).TypeHandle.Equals(((Type)other).TypeHandle);
- case MemberTypes.Event:
- case MemberTypes.Property:
- default:
- return
- ((MemberInfo)self).Module == ((MemberInfo)other).Module &&
- ((MemberInfo)self).MetadataToken == ((MemberInfo)other).MetadataToken;
- }
- }
-#endif
-
- public static bool IsVisible(MethodBase info) {
- return info.IsPublic && (info.DeclaringType == null || info.DeclaringType.IsVisible());
- }
-
- public static bool IsVisible(FieldInfo info) {
- return info.IsPublic && (info.DeclaringType == null || info.DeclaringType.IsVisible());
- }
-
- public static bool IsProtected(this MethodBase info) {
- return info.IsFamily || info.IsFamilyOrAssembly;
- }
-
- public static bool IsProtected(this FieldInfo info) {
- return info.IsFamily || info.IsFamilyOrAssembly;
- }
-
- public static bool IsProtected(this Type type) {
- return type.GetTypeInfo().IsNestedFamily || type.GetTypeInfo().IsNestedFamORAssem;
- }
-
- public static Type GetVisibleType(object value) {
- return GetVisibleType(GetType(value));
- }
-
- public static Type GetVisibleType(Type t) {
- while (!t.IsVisible()) {
- t = t.GetBaseType();
- }
- return t;
- }
-
- public static MethodBase[] GetConstructors(Type t, bool privateBinding) {
- return GetConstructors(t, privateBinding, false);
- }
-
- public static MethodBase[] GetConstructors(Type t, bool privateBinding, bool includeProtected) {
- if (t.IsArray) {
- // The JIT verifier doesn't like new int[](3) even though it appears as a ctor.
- // We could do better and return newarr in the future.
- return new MethodBase[] { GetArrayCtor(t) };
- }
-
- BindingFlags bf = BindingFlags.Instance | BindingFlags.Public;
- if (privateBinding || includeProtected) {
- bf |= BindingFlags.NonPublic;
- }
-
- IEnumerable<ConstructorInfo> ctors = t.GetDeclaredConstructors().WithBindingFlags(bf);
-
- // leave in protected ctors, even if we're not in private binding mode.
- if (!privateBinding && includeProtected) {
- ctors = FilterConstructorsToPublicAndProtected(ctors);
- }
-
- if (t.IsValueType()
-#if !SILVERLIGHT && !WIN8 && !WP75
- && t != typeof(ArgIterator)
-#endif
-) {
- // structs don't define a parameterless ctor, add a generic method for that.
- List<MethodBase> result = new List<MethodBase>();
- result.Add(GetStructDefaultCtor(t));
- result.AddRange(ctors.Cast<ConstructorInfo, MethodBase>());
- return result.ToArray();
- } else {
- return ctors.ToArray();
- }
- }
-
- public static IEnumerable<ConstructorInfo> FilterConstructorsToPublicAndProtected(IEnumerable<ConstructorInfo> ctors) {
- foreach (var ctor in ctors) {
- if (ctor.IsPublic || ctor.IsProtected()) {
- yield return ctor;
- }
- }
- }
-
- private static MethodBase GetStructDefaultCtor(Type t) {
- return typeof(ScriptingRuntimeHelpers).GetDeclaredMethods("CreateInstance").Single().MakeGenericMethod(t);
- }
-
- private static MethodBase GetArrayCtor(Type t) {
- return typeof(ScriptingRuntimeHelpers).GetDeclaredMethods("CreateArray").Single().MakeGenericMethod(t.GetElementType());
- }
-
- #region Type Conversions
-
- public static MethodInfo GetImplicitConverter(Type fromType, Type toType) {
- return GetConverter(fromType, fromType, toType, "op_Implicit") ?? GetConverter(toType, fromType, toType, "op_Implicit");
- }
-
- public static MethodInfo GetExplicitConverter(Type fromType, Type toType) {
- return GetConverter(fromType, fromType, toType, "op_Explicit") ?? GetConverter(toType, fromType, toType, "op_Explicit");
- }
-
- private static MethodInfo GetConverter(Type type, Type fromType, Type toType, string opMethodName) {
- foreach (MethodInfo mi in type.GetInheritedMembers(opMethodName).WithBindingFlags(BindingFlags.Public | BindingFlags.Static)) {
- if ((mi.DeclaringType == null || mi.DeclaringType.IsVisible()) && mi.IsPublic &&
- mi.ReturnType == toType && mi.GetParameters()[0].ParameterType.IsAssignableFrom(fromType)) {
- return mi;
- }
- }
- return null;
- }
-
- public static bool TryImplicitConversion(Object value, Type to, out object result) {
- if (CompilerHelpers.TryImplicitConvert(value, to, to.GetInheritedMethods("op_Implicit").WithBindingFlags(BindingFlags.Public | BindingFlags.Static), out result)) {
- return true;
- }
-
- Type curType = CompilerHelpers.GetType(value);
- do {
- if (CompilerHelpers.TryImplicitConvert(value, to, curType.GetInheritedMethods("op_Implicit").WithBindingFlags(BindingFlags.Public | BindingFlags.Static), out result)) {
- return true;
- }
- curType = curType.GetBaseType();
- } while (curType != null);
-
- return false;
- }
-
- private static bool TryImplicitConvert(Object value, Type to, IEnumerable<MethodInfo> implicitConv, out object result) {
- foreach (MethodInfo mi in implicitConv) {
- if (to.IsValueType() == mi.ReturnType.IsValueType() && to.IsAssignableFrom(mi.ReturnType)) {
- if (mi.IsStatic) {
- result = mi.Invoke(null, new object[] { value });
- } else {
- result = mi.Invoke(value, ArrayUtils.EmptyObjects);
- }
- return true;
- }
- }
-
- result = null;
- return false;
- }
-
- public static bool IsStrongBox(object target) {
- Type t = CompilerHelpers.GetType(target);
-
- return IsStrongBox(t);
- }
-
- public static bool IsStrongBox(Type t) {
- return t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(StrongBox<>);
- }
-
- /// <summary>
- /// Returns a value which indicates failure when a OldConvertToAction of ImplicitTry or
- /// ExplicitTry.
- /// </summary>
- public static Expression GetTryConvertReturnValue(Type type) {
- Expression res;
- var info = type.GetTypeInfo();
- if (info.IsInterface || info.IsClass || (info.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))) {
- res = AstUtils.Constant(null, type);
- } else {
- res = AstUtils.Constant(Activator.CreateInstance(type));
- }
-
- return res;
- }
-
- public static bool HasTypeConverter(Type fromType, Type toType) {
-#if FEATURE_TYPECONVERTER
- TypeConverter _;
- return TryGetTypeConverter(fromType, toType, out _);
-#else
- return false;
-#endif
- }
-
- public static bool TryApplyTypeConverter(object value, Type toType, out object result) {
-#if FEATURE_TYPECONVERTER
- TypeConverter converter;
- if (value != null && CompilerHelpers.TryGetTypeConverter(value.GetType(), toType, out converter)) {
- result = converter.ConvertFrom(value);
- return true;
- } else {
- result = value;
- return false;
- }
-#else
- result = value;
- return false;
-#endif
- }
-
-#if FEATURE_TYPECONVERTER
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
- public static bool TryGetTypeConverter(Type fromType, Type toType, out TypeConverter converter) {
- ContractUtils.RequiresNotNull(fromType, "fromType");
- ContractUtils.RequiresNotNull(toType, "toType");
-
- // try available type conversions...
- foreach (TypeConverterAttribute tca in toType.GetCustomAttributes(typeof(TypeConverterAttribute), true)) {
- try {
- converter = Activator.CreateInstance(Type.GetType(tca.ConverterTypeName)) as TypeConverter;
- } catch (Exception) {
- converter = null;
- }
-
- if (converter != null && converter.CanConvertFrom(fromType)) {
- return true;
- }
- }
-
- converter = null;
- return false;
- }
-#endif
-
- #endregion
-
-#if !MONO_INTERPRETER
- public static MethodBase[] GetMethodTargets(object obj) {
- Type t = CompilerHelpers.GetType(obj);
-
- if (typeof(Delegate).IsAssignableFrom(t)) {
- MethodInfo mi = t.GetMethod("Invoke");
- return new MethodBase[] { mi };
- } else if (typeof(BoundMemberTracker).IsAssignableFrom(t)) {
- BoundMemberTracker bmt = obj as BoundMemberTracker;
- if (bmt.BoundTo.MemberType == TrackerTypes.Method) {
- }
- } else if (typeof(MethodGroup).IsAssignableFrom(t)) {
- } else if (typeof(MemberGroup).IsAssignableFrom(t)) {
- } else {
- return MakeCallSignatureForCallableObject(t);
- }
-
- return null;
- }
-#endif
-
- private static MethodBase[] MakeCallSignatureForCallableObject(Type t) {
- List<MethodBase> res = new List<MethodBase>();
- foreach (MethodInfo method in t.GetInheritedMethods("Call")) {
- if (method.IsSpecialName) {
- res.Add(method);
- }
- }
- return res.ToArray();
- }
-
- public static Type[] GetSiteTypes(IList<Expression> arguments, Type returnType) {
- int count = arguments.Count;
-
- Type[] ret = new Type[count + 1];
-
- for (int i = 0; i < count; i++) {
- ret[i] = arguments[i].Type;
- }
-
- ret[count] = returnType;
- return ret;
- }
-
- public static Type[] GetExpressionTypes(Expression[] expressions) {
- ContractUtils.RequiresNotNull(expressions, "expressions");
-
- Type[] res = new Type[expressions.Length];
- for (int i = 0; i < res.Length; i++) {
- ContractUtils.RequiresNotNull(expressions[i], "expressions[i]");
-
- res[i] = expressions[i].Type;
- }
-
- return res;
- }
-
- public static Type MakeCallSiteType(params Type[] types) {
- return typeof(CallSite<>).MakeGenericType(DelegateHelpers.MakeDelegate(types));
- }
-
- public static Type MakeCallSiteDelegateType(Type[] types) {
- return DelegateHelpers.MakeDelegate(types);
- }
-
- /// <summary>
- /// Creates an interpreted delegate for the lambda.
- /// </summary>
- /// <param name="lambda">The lambda to compile.</param>
- /// <returns>A delegate which can interpret the lambda.</returns>
- public static Delegate LightCompile(this LambdaExpression lambda) {
- return new LightCompiler(-1).CompileTop(lambda).CreateDelegate();
- }
-
- /// <summary>
- /// Creates an interpreted delegate for the lambda.
- /// </summary>
- /// <param name="lambda">The lambda to compile.</param>
- /// <param name="compilationThreshold">The number of iterations before the interpreter starts compiling</param>
- /// <returns>A delegate which can interpret the lambda.</returns>
- public static Delegate LightCompile(this LambdaExpression lambda, int compilationThreshold) {
- return new LightCompiler(compilationThreshold).CompileTop(lambda).CreateDelegate();
- }
-
- /// <summary>
- /// Creates an interpreted delegate for the lambda.
- /// </summary>
- /// <typeparam name="T">The lambda's delegate type.</typeparam>
- /// <param name="lambda">The lambda to compile.</param>
- /// <returns>A delegate which can interpret the lambda.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
- public static T LightCompile<T>(this Expression<T> lambda) {
- return (T)(object)LightCompile((LambdaExpression)lambda);
- }
-
- /// <summary>
- /// Creates an interpreted delegate for the lambda.
- /// </summary>
- /// <param name="lambda">The lambda to compile.</param>
- /// <param name="compilationThreshold">The number of iterations before the interpreter starts compiling</param>
- /// <returns>A delegate which can interpret the lambda.</returns>
- public static T LightCompile<T>(this Expression<T> lambda, int compilationThreshold) {
- return (T)(object)LightCompile((LambdaExpression)lambda, compilationThreshold);
- }
-
-#if FEATURE_REFEMIT
- /// <summary>
- /// Compiles the lambda into a method definition.
- /// </summary>
- /// <param name="lambda">the lambda to compile</param>
- /// <param name="method">A <see cref="MethodBuilder"/> which will be used to hold the lambda's IL.</param>
- /// <param name="emitDebugSymbols">A parameter that indicates if debugging information should be emitted to a PDB symbol store.</param>
- public static void CompileToMethod(this LambdaExpression lambda, MethodBuilder method, bool emitDebugSymbols) {
-#if FEATURE_PDBEMIT
- if (emitDebugSymbols) {
- var module = method.Module as ModuleBuilder;
- ContractUtils.Requires(module != null, "method", "MethodBuilder does not have a valid ModuleBuilder");
- lambda.CompileToMethod(method, DebugInfoGenerator.CreatePdbGenerator());
- return;
- }
-#endif
-
-#if WIN8 // TODO
- ((dynamic)lambda).CompileToMethod(method);
-#else
- lambda.CompileToMethod(method);
-#endif
- }
-#endif
-
- /// <summary>
- /// Compiles the LambdaExpression.
- ///
- /// If the lambda is compiled with emitDebugSymbols, it will be
- /// generated into a TypeBuilder. Otherwise, this method is the same as
- /// calling LambdaExpression.Compile()
- ///
- /// This is a workaround for a CLR limitiation: DynamicMethods cannot
- /// have debugging information.
- /// </summary>
- /// <param name="lambda">the lambda to compile</param>
- /// <param name="emitDebugSymbols">true to generate a debuggable method, false otherwise</param>
- /// <returns>the compiled delegate</returns>
- public static T Compile<T>(this Expression<T> lambda, bool emitDebugSymbols) {
-#if FEATURE_PDBEMIT && FEATURE_REFEMIT
- if (emitDebugSymbols) {
- return CompileToMethod(lambda, DebugInfoGenerator.CreatePdbGenerator(), true);
- }
-#endif
- return lambda.Compile();
- }
-
-#if FEATURE_REFEMIT
- /// <summary>
- /// Compiles the LambdaExpression, emitting it into a new type, and
- /// optionally making it debuggable.
- ///
- /// This is a workaround for a CLR limitiation: DynamicMethods cannot
- /// have debugging information.
- /// </summary>
- /// <param name="lambda">the lambda to compile</param>
- /// <param name="debugInfoGenerator">Debugging information generator used by the compiler to mark sequence points and annotate local variables.</param>
- /// <param name="emitDebugSymbols">True if debug symbols (PDBs) are emitted by the <paramref name="debugInfoGenerator"/>.</param>
- /// <returns>the compiled delegate</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
- public static T CompileToMethod<T>(Expression<T> lambda, DebugInfoGenerator debugInfoGenerator, bool emitDebugSymbols) {
- return (T)(object)CompileToMethod((LambdaExpression)lambda, debugInfoGenerator, emitDebugSymbols);
- }
-
- public static Delegate CompileToMethod(LambdaExpression lambda, DebugInfoGenerator debugInfoGenerator, bool emitDebugSymbols) {
- string methodName = String.IsNullOrEmpty(lambda.Name) ? GetUniqueMethodName() : lambda.Name;
-
- var type = Snippets.Shared.DefineType(methodName, typeof(object), false, emitDebugSymbols).TypeBuilder;
- var rewriter = new DebuggableCodeRewriter(type);
- lambda = (LambdaExpression)rewriter.Visit(lambda);
-
- //Create a unique method name when the lambda doesn't have a name or the name is empty.
- var method = type.DefineMethod(methodName, CompilerHelpers.PublicStatic);
-
- lambda.CompileToMethod(method, debugInfoGenerator);
- var finished = type.CreateType();
-
- rewriter.InitializeFields(finished);
-
- return finished.GetMethod(method.Name).CreateDelegate(lambda.Type);
- }
-
- /// <summary>
- /// Removes all live objects and places them in static fields of a type.
- /// </summary>
- private sealed class DebuggableCodeRewriter : DynamicExpressionVisitor {
- private readonly Dictionary<object, FieldBuilder> _fields = new Dictionary<object, FieldBuilder>(ReferenceEqualityComparer<object>.Instance);
- private readonly TypeBuilder _type;
- private readonly HashSet<string> _methodNames = new HashSet<string>();
-
- internal DebuggableCodeRewriter(TypeBuilder type) {
- _type = type;
- }
-
- internal void InitializeFields(Type type) {
- foreach (var pair in _fields) {
- type.GetInheritedFields(pair.Value.Name).First().SetValue(null, pair.Key);
- }
- }
-
- protected override Expression VisitLambda<T>(Expression<T> node) {
- if (_methodNames.Contains(node.Name)) {
- int count = _methodNames.Count;
-
- string newName;
- do {
- newName = node.Name + "$" + count++;
- } while (_methodNames.Contains(newName));
-
- _methodNames.Add(newName);
- return Expression.Lambda<T>(
- base.Visit(node.Body),
- newName,
- node.TailCall,
- node.Parameters
- );
- } else {
- _methodNames.Add(node.Name);
- return base.VisitLambda<T>(node);
- }
- }
-
- protected override Expression VisitExtension(Expression node) {
- // LightDynamicExpressions override Visit but we want to really reduce them
- // because they reduce to DynamicExpressions.
- LightDynamicExpression lightDyn = node as LightDynamicExpression;
- if (lightDyn != null) {
- return Visit(lightDyn.Reduce());
- }
-
- return Visit(node.Reduce());
- }
-
- protected override Expression VisitConstant(ConstantExpression node) {
- if (CanEmitConstant(node.Value, node.Type)) {
- return node;
- }
-
- FieldBuilder field;
- if (!_fields.TryGetValue(node.Value, out field)) {
- field = _type.DefineField(
- "$constant" + _fields.Count,
- GetVisibleType(node.Value.GetType()),
- FieldAttributes.Public | FieldAttributes.Static
- );
- _fields.Add(node.Value, field);
- }
-
- Expression result = Expression.Field(null, field);
- if (result.Type != node.Type) {
- result = Expression.Convert(result, node.Type);
- }
- return result;
- }
-
- protected override Expression VisitDynamic(DynamicExpression node) {
- return Visit(Reduce(node));
- }
- }
-#endif
-
- public static string GetUniqueMethodName() {
- return "lambda_method" + "$" + System.Threading.Interlocked.Increment(ref _Counter);
- }
-
-#if FEATURE_LCG
- // Matches ILGen.TryEmitConstant
- public static bool CanEmitConstant(object value, Type type) {
- if (value == null || CanEmitILConstant(type)) {
- return true;
- }
-
- Type t = value as Type;
- if (t != null && ILGen.ShouldLdtoken(t)) {
- return true;
- }
-
- MethodBase mb = value as MethodBase;
- if (mb != null && ILGen.ShouldLdtoken(mb)) {
- return true;
- }
-
- return false;
- }
-
- // Matches ILGen.TryEmitILConstant
- internal static bool CanEmitILConstant(Type type) {
- switch (type.GetTypeCode()) {
- case TypeCode.Boolean:
- case TypeCode.SByte:
- case TypeCode.Int16:
- case TypeCode.Int32:
- case TypeCode.Int64:
- case TypeCode.Single:
- case TypeCode.Double:
- case TypeCode.Char:
- case TypeCode.Byte:
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- case TypeCode.Decimal:
- case TypeCode.String:
- return true;
- }
- return false;
- }
-#endif
-
- /// <summary>
- /// Reduces the provided DynamicExpression into site.Target(site, *args).
- /// </summary>
- public static Expression Reduce(DynamicExpression node) {
- // Store the callsite as a constant
- var siteConstant = AstUtils.Constant(CallSite.Create(node.DelegateType, node.Binder));
-
- // ($site = siteExpr).Target.Invoke($site, *args)
- var site = Expression.Variable(siteConstant.Type, "$site");
- return Expression.Block(
- new[] { site },
- Expression.Call(
- Expression.Field(
- Expression.Assign(site, siteConstant),
- siteConstant.Type.GetDeclaredField("Target")
- ),
- node.DelegateType.GetMethod("Invoke"),
- ArrayUtils.Insert(site, node.Arguments)
- )
- );
- }
-#if !MONO_INTERPRETER
- #region Factories
-#if !FEATURE_NUMERICS
- [CLSCompliant(false)]
- public static BigInteger CreateBigInteger(int sign, uint[] data) {
- return new BigInteger(sign, data);
- }
-#else
- public static BigInteger CreateBigInteger(bool isNegative, byte[] data) {
- return new BigInteger(CreateBigInt(isNegative, data));
- }
-
- public static BigInt CreateBigInt(int value) {
- return (BigInt)value;
- }
-
- public static BigInt CreateBigInt(long value) {
- return (BigInt)value;
- }
-
- public static BigInt CreateBigInt(bool isNegative, byte[] data) {
- BigInt res = new BigInt(data);
- return isNegative ? -res : res;
- }
-
-#endif
- #endregion
-#endif
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/ConstantCheck.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/ConstantCheck.cs
deleted file mode 100644
index 89cbbfe91cc..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/ConstantCheck.cs
+++ /dev/null
@@ -1,128 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System.Diagnostics;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Generation {
-
- public static class ConstantCheck {
-
- /// <summary>
- /// Tests to see if the expression is a constant with the given value.
- /// </summary>
- /// <param name="expression">The expression to examine</param>
- /// <param name="value">The constant value to check for.</param>
- /// <returns>true/false</returns>
- public static bool Check(Expression expression, object value) {
- ContractUtils.RequiresNotNull(expression, "expression");
- return IsConstant(expression, value);
- }
-
-
- /// <summary>
- /// Tests to see if the expression is a constant with the given value.
- /// </summary>
- /// <param name="e">The expression to examine</param>
- /// <param name="value">The constant value to check for.</param>
- /// <returns>true/false</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
- internal static bool IsConstant(Expression e, object value) {
- switch (e.NodeType) {
- case ExpressionType.AndAlso:
- return CheckAndAlso((BinaryExpression)e, value);
-
- case ExpressionType.OrElse:
- return CheckOrElse((BinaryExpression)e, value);
-
- case ExpressionType.Constant:
- return CheckConstant((ConstantExpression)e, value);
-
- case ExpressionType.TypeIs:
- return Check((TypeBinaryExpression)e, value);
-
- default:
- return false;
- }
- }
-
- //CONFORMING
- internal static bool IsNull(Expression e) {
- return IsConstant(e, null);
- }
-
-
- private static bool CheckAndAlso(BinaryExpression node, object value) {
- Debug.Assert(node.NodeType == ExpressionType.AndAlso);
-
- if (node.Method != null) {
- return false;
- }
- //TODO: we can propagate through conversion, but it may not worth it.
- if (node.Conversion != null) {
- return false;
- }
-
- if (value is bool) {
- if ((bool)value) {
- return IsConstant(node.Left, true) && IsConstant(node.Right, true);
- } else {
- // if left isn't a constant it has to be evaluated
- return IsConstant(node.Left, false);
- }
- }
- return false;
- }
-
- private static bool CheckOrElse(BinaryExpression node, object value) {
- Debug.Assert(node.NodeType == ExpressionType.OrElse);
-
- if (node.Method != null) {
- return false;
- }
-
- if (value is bool) {
- if ((bool)value) {
- return IsConstant(node.Left, true);
- } else {
- return IsConstant(node.Left, false) && IsConstant(node.Right, false);
- }
- }
- return false;
- }
-
- private static bool CheckConstant(ConstantExpression node, object value) {
- if (value == null) {
- return node.Value == null;
- } else {
- return value.Equals(node.Value);
- }
- }
-
- private static bool Check(TypeBinaryExpression node, object value) {
- // allow constant TypeIs expressions to be optimized away
- if (value is bool && ((bool)value) == true) {
- return node.TypeOperand.IsAssignableFrom(node.Expression.Type);
- }
- return false;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/DelegateHelpers.Generated.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/DelegateHelpers.Generated.cs
deleted file mode 100644
index 2b5bd93d0fa..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/DelegateHelpers.Generated.cs
+++ /dev/null
@@ -1,110 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Linq;
-using System.Diagnostics;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Generation {
- internal static partial class DelegateHelpers {
-
- #region Generated Maximum Delegate Arity
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_max_delegate_arity from: generate_dynsites.py
-
- private const int MaximumArity = 17;
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
- internal static Type MakeDelegate(Type[] types) {
- Debug.Assert(types != null && types.Length > 0);
-
- // Can only used predefined delegates if we have no byref types and
- // the arity is small enough to fit in Func<...> or Action<...>
- if (types.Length > MaximumArity || types.Any(t => t.IsByRef)) {
- return MakeCustomDelegate(types);
- }
-
- Type returnType = types[types.Length - 1];
- if (returnType == typeof(void)) {
- types = types.RemoveLast();
- switch (types.Length) {
- case 0: return typeof(Action);
- #region Generated Delegate Action Types
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_delegate_action from: generate_dynsites.py
-
- case 1: return typeof(Action<>).MakeGenericType(types);
- case 2: return typeof(Action<,>).MakeGenericType(types);
- case 3: return typeof(Action<,,>).MakeGenericType(types);
- case 4: return typeof(Action<,,,>).MakeGenericType(types);
- case 5: return typeof(Action<,,,,>).MakeGenericType(types);
- case 6: return typeof(Action<,,,,,>).MakeGenericType(types);
- case 7: return typeof(Action<,,,,,,>).MakeGenericType(types);
- case 8: return typeof(Action<,,,,,,,>).MakeGenericType(types);
- case 9: return typeof(Action<,,,,,,,,>).MakeGenericType(types);
- case 10: return typeof(Action<,,,,,,,,,>).MakeGenericType(types);
- case 11: return typeof(Action<,,,,,,,,,,>).MakeGenericType(types);
- case 12: return typeof(Action<,,,,,,,,,,,>).MakeGenericType(types);
- case 13: return typeof(Action<,,,,,,,,,,,,>).MakeGenericType(types);
- case 14: return typeof(Action<,,,,,,,,,,,,,>).MakeGenericType(types);
- case 15: return typeof(Action<,,,,,,,,,,,,,,>).MakeGenericType(types);
- case 16: return typeof(Action<,,,,,,,,,,,,,,,>).MakeGenericType(types);
-
- // *** END GENERATED CODE ***
-
- #endregion
- }
- } else {
- switch (types.Length) {
- #region Generated Delegate Func Types
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_delegate_func from: generate_dynsites.py
-
- case 1: return typeof(Func<>).MakeGenericType(types);
- case 2: return typeof(Func<,>).MakeGenericType(types);
- case 3: return typeof(Func<,,>).MakeGenericType(types);
- case 4: return typeof(Func<,,,>).MakeGenericType(types);
- case 5: return typeof(Func<,,,,>).MakeGenericType(types);
- case 6: return typeof(Func<,,,,,>).MakeGenericType(types);
- case 7: return typeof(Func<,,,,,,>).MakeGenericType(types);
- case 8: return typeof(Func<,,,,,,,>).MakeGenericType(types);
- case 9: return typeof(Func<,,,,,,,,>).MakeGenericType(types);
- case 10: return typeof(Func<,,,,,,,,,>).MakeGenericType(types);
- case 11: return typeof(Func<,,,,,,,,,,>).MakeGenericType(types);
- case 12: return typeof(Func<,,,,,,,,,,,>).MakeGenericType(types);
- case 13: return typeof(Func<,,,,,,,,,,,,>).MakeGenericType(types);
- case 14: return typeof(Func<,,,,,,,,,,,,,>).MakeGenericType(types);
- case 15: return typeof(Func<,,,,,,,,,,,,,,>).MakeGenericType(types);
- case 16: return typeof(Func<,,,,,,,,,,,,,,,>).MakeGenericType(types);
- case 17: return typeof(Func<,,,,,,,,,,,,,,,,>).MakeGenericType(types);
-
- // *** END GENERATED CODE ***
-
- #endregion
- }
- }
- throw Assert.Unreachable;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/DelegateHelpers.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/DelegateHelpers.cs
deleted file mode 100644
index b2ef101c769..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/DelegateHelpers.cs
+++ /dev/null
@@ -1,87 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-#if FEATURE_REFEMIT
-using System.Reflection.Emit;
-#endif
-using System.Threading;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Generation {
- internal static partial class DelegateHelpers {
-
- private static Dictionary<ICollection<Type>, Type> _DelegateTypes;
-
- private static Type MakeCustomDelegate(Type[] types) {
- if (_DelegateTypes == null) {
- Interlocked.CompareExchange(
- ref _DelegateTypes,
- new Dictionary<ICollection<Type>, Type>(ListEqualityComparer<Type>.Instance),
- null
- );
- }
-
- bool found;
- Type type;
-
- //
- // LOCK to retrieve the delegate type, if any
- //
-
- lock (_DelegateTypes) {
- found = _DelegateTypes.TryGetValue(types, out type);
- }
-
- if (!found && type != null) {
- return type;
- }
-
- //
- // Create new delegate type
- //
-
- type = MakeNewCustomDelegate(types);
-
- //
- // LOCK to insert new delegate into the cache. If we already have one (racing threads), use the one from the cache
- //
-
- lock (_DelegateTypes) {
- Type conflict;
- if (_DelegateTypes.TryGetValue(types, out conflict) && conflict != null) {
- type = conflict;
- } else {
- _DelegateTypes[types] = type;
- }
- }
-
- return type;
- }
-
- private static Type MakeNewCustomDelegate(Type[] types) {
-#if FEATURE_REFEMIT
- Type returnType = types[types.Length - 1];
- Type[] parameters = types.RemoveLast();
-
- return Snippets.Shared.DefineDelegate("Delegate" + types.Length, returnType, parameters);
-#else
- throw new NotSupportedException("Signature not supported on this platform");
-#endif
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/BranchLabel.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/BranchLabel.cs
deleted file mode 100644
index de0b6db37c4..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/BranchLabel.cs
+++ /dev/null
@@ -1,108 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Collections.Generic;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal struct RuntimeLabel {
- public readonly int Index;
- public readonly int StackDepth;
- public readonly int ContinuationStackDepth;
-
- public RuntimeLabel(int index, int continuationStackDepth, int stackDepth) {
- Index = index;
- ContinuationStackDepth = continuationStackDepth;
- StackDepth = stackDepth;
- }
-
- public override string ToString() {
- return String.Format("->{0} C({1}) S({2})", Index, ContinuationStackDepth, StackDepth);
- }
- }
-
- public sealed class BranchLabel {
- internal const int UnknownIndex = Int32.MinValue;
- internal const int UnknownDepth = Int32.MinValue;
-
- internal int _labelIndex = UnknownIndex;
- internal int _targetIndex = UnknownIndex;
- internal int _stackDepth = UnknownDepth;
- internal int _continuationStackDepth = UnknownDepth;
-
- // Offsets of forward branching instructions targetting this label
- // that need to be updated after we emit the label.
- private List<int> _forwardBranchFixups;
-
- public BranchLabel() {
- }
-
- internal int LabelIndex {
- get { return _labelIndex; }
- set { _labelIndex = value; }
- }
-
- internal bool HasRuntimeLabel {
- get { return _labelIndex != UnknownIndex; }
- }
-
- internal int TargetIndex {
- get { return _targetIndex; }
- }
-
- internal RuntimeLabel ToRuntimeLabel() {
- Debug.Assert(_targetIndex != UnknownIndex && _stackDepth != UnknownDepth && _continuationStackDepth != UnknownDepth);
- return new RuntimeLabel(_targetIndex, _continuationStackDepth, _stackDepth);
- }
-
- internal void Mark(InstructionList instructions) {
- ContractUtils.Requires(_targetIndex == UnknownIndex && _stackDepth == UnknownDepth && _continuationStackDepth == UnknownDepth);
-
- _stackDepth = instructions.CurrentStackDepth;
- _continuationStackDepth = instructions.CurrentContinuationsDepth;
- _targetIndex = instructions.Count;
-
- if (_forwardBranchFixups != null) {
- foreach (var branchIndex in _forwardBranchFixups) {
- FixupBranch(instructions, branchIndex);
- }
- _forwardBranchFixups = null;
- }
- }
-
- internal void AddBranch(InstructionList instructions, int branchIndex) {
- Debug.Assert(((_targetIndex == UnknownIndex) == (_stackDepth == UnknownDepth)));
- Debug.Assert(((_targetIndex == UnknownIndex) == (_continuationStackDepth == UnknownDepth)));
-
- if (_targetIndex == UnknownIndex) {
- if (_forwardBranchFixups == null) {
- _forwardBranchFixups = new List<int>();
- }
- _forwardBranchFixups.Add(branchIndex);
- } else {
- FixupBranch(instructions, branchIndex);
- }
- }
-
- internal void FixupBranch(InstructionList instructions, int branchIndex) {
- Debug.Assert(_targetIndex != UnknownIndex);
- instructions.FixupBranch(branchIndex, _targetIndex - branchIndex);
- }
- }
-
-
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/ILightCallSiteBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/ILightCallSiteBinder.cs
deleted file mode 100644
index 8535961f86b..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/ILightCallSiteBinder.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-using System.Reflection;
-using Microsoft.Scripting.Interpreter;
-using System.Runtime.CompilerServices;
-using System.Collections.Generic;
-
-namespace Microsoft.Scripting.Interpreter {
- public interface ILightCallSiteBinder {
- bool AcceptsArgumentArray { get; }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/AddInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/AddInstruction.cs
deleted file mode 100644
index ee176510ec0..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/AddInstruction.cs
+++ /dev/null
@@ -1,191 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class AddInstruction : ArithmeticInstruction {
-
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double;
-
- private AddInstruction() {
- }
-
- internal sealed class AddInt32 : AddInstruction {
- protected override object Calculate (object l, object r)
- {
- return ScriptingRuntimeHelpers.Int32ToObject(unchecked((Int32)l + (Int32)r));
- }
- }
-
- internal sealed class AddInt16 : AddInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int16)unchecked((Int16)l + (Int16)r);
- }
- }
-
- internal sealed class AddInt64 : AddInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64)unchecked((Int64)l + (Int64)r);
- }
- }
-
- internal sealed class AddUInt16 : AddInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt16)unchecked((UInt16)l + (UInt16)r);
- }
- }
-
- internal sealed class AddUInt32 : AddInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32)unchecked((UInt32)l + (UInt32)r);
- }
- }
-
- internal sealed class AddUInt64 : AddInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64)unchecked((UInt64)l + (UInt64)r);
- }
- }
-
- internal sealed class AddSingle : AddInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Single)((Single)l + (Single)r);
- }
- }
-
- internal sealed class AddDouble : AddInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Double)l + (Double)r;
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new AddInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new AddInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new AddInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new AddUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new AddUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new AddUInt64());
- case TypeCode.Single: return _Single ?? (_Single = new AddSingle());
- case TypeCode.Double: return _Double ?? (_Double = new AddDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "Add()";
- }
- }
-
- internal abstract class AddOvfInstruction : ArithmeticInstruction {
-
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double;
-
- private AddOvfInstruction() {
- }
-
- internal sealed class AddOvfInt32 : AddOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return ScriptingRuntimeHelpers.Int32ToObject(checked((Int32)l + (Int32)r));
- }
- }
-
- internal sealed class AddOvfInt16 : AddOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((Int16)((Int16)l + (Int16)r));
- }
- }
-
- internal sealed class AddOvfInt64 : AddOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((Int64)((Int64)l + (Int64)r));
- }
- }
-
- internal sealed class AddOvfUInt16 : AddOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((UInt16)((UInt16)l + (UInt16)r));
- }
- }
-
- internal sealed class AddOvfUInt32 : AddOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((UInt32)((UInt32)l + (UInt32)r));
- }
- }
-
- internal sealed class AddOvfUInt64 : AddOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((UInt64)((UInt64)l + (UInt64)r));
- }
- }
-
- internal sealed class AddOvfSingle : AddOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Single)((Single)l + (Single)r);
- }
- }
-
- internal sealed class AddOvfDouble : AddOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Double)l + (Double)r;
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new AddOvfInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new AddOvfInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new AddOvfInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new AddOvfUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new AddOvfUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new AddOvfUInt64());
- case TypeCode.Single: return _Single ?? (_Single = new AddOvfSingle());
- case TypeCode.Double: return _Double ?? (_Double = new AddOvfDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "AddOvf()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/AndInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/AndInstruction.cs
deleted file mode 100644
index 8f33dc3357f..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/AndInstruction.cs
+++ /dev/null
@@ -1,176 +0,0 @@
-//
-// AndInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class AndInstruction : ArithmeticInstruction {
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Boolean;
- private static Instruction _Int16Lifted, _Int32Lifted, _Int64Lifted, _UInt16Lifted, _UInt32Lifted, _UInt64Lifted, _BooleanLifted;
-
- private AndInstruction() {
- }
-
- internal sealed class AndInt32 : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return ScriptingRuntimeHelpers.Int32ToObject((Int32)l & (Int32)r);
- }
- }
-
- internal sealed class AndInt16 : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int16)((Int16)l & (Int16)r);
- }
- }
-
- internal sealed class AndInt64 : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64)((Int64)l & (Int64)r);
- }
- }
-
- internal sealed class AndUInt16 : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt16)((UInt16)l & (UInt16)r);
- }
- }
-
- internal sealed class AndUInt32 : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32)((UInt32)l & (UInt32)r);
- }
- }
-
- internal sealed class AndUInt64 : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64)((UInt64)l & (UInt64)r);
- }
- }
-
- internal sealed class AndBoolean : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Boolean)((Boolean)l & (Boolean)r);
- }
- }
-
- internal sealed class AndInt32Lifted : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int32?)((Int32?)l & (Int32?)r);
- }
- }
-
- internal sealed class AndInt16Lifted : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int16?)((Int16?)l & (Int16?)r);
- }
- }
-
- internal sealed class AndInt64Lifted : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64?)((Int64?)l & (Int64?)r);
- }
- }
-
- internal sealed class AndUInt16Lifted : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt16?)((UInt16?)l & (UInt16?)r);
- }
- }
-
- internal sealed class AndUInt32Lifted : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32?)((UInt32?)l & (UInt32?)r);
- }
- }
-
- internal sealed class AndUInt64Lifted : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64?)((UInt64?)l & (UInt64?)r);
- }
- }
-
- internal sealed class AndBooleanLifted : AndInstruction {
- protected override object Calculate (object l, object r)
- {
- return ((Boolean?)l & (Boolean?)r);
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new AndInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new AndInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new AndInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new AndUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new AndUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new AndUInt64());
- case TypeCode.Boolean: return _Boolean ?? (_Boolean = new AndBoolean());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new AndInt16Lifted());
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new AndInt32Lifted());
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new AndInt64Lifted());
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new AndUInt16Lifted());
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new AndUInt32Lifted());
- case TypeCode.UInt64: return _UInt64Lifted ?? (_UInt64Lifted = new AndUInt64Lifted());
- case TypeCode.Boolean: return _BooleanLifted ?? (_BooleanLifted = new AndBooleanLifted());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "And()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ArithmeticInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ArithmeticInstruction.cs
deleted file mode 100644
index eb71f03e4f0..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ArithmeticInstruction.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-//
-// ArithmeticInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class ArithmeticInstruction : Instruction {
-
- public override int ConsumedStack { get { return 2; } }
- public override int ProducedStack { get { return 1; } }
-
- protected abstract object Calculate (object l, object r);
-
- public override int Run(InterpretedFrame frame) {
- object l = frame.Data[frame.StackIndex - 2];
- object r = frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 2] = Calculate (l, r);
- frame.StackIndex--;
- return +1;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ArrayOperations.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ArrayOperations.cs
deleted file mode 100644
index d8e0bc6c831..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ArrayOperations.cs
+++ /dev/null
@@ -1,134 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-
-namespace Microsoft.Scripting.Interpreter {
- public sealed class NewArrayInitInstruction<TElement> : Instruction {
- private readonly int _elementCount;
-
- internal NewArrayInitInstruction(int elementCount) {
- _elementCount = elementCount;
- }
-
- public override int ConsumedStack { get { return _elementCount; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- TElement[] array = new TElement[_elementCount];
- for (int i = _elementCount - 1; i >= 0; i--) {
- array[i] = (TElement)frame.Pop();
- }
- frame.Push(array);
- return +1;
- }
- }
-
- public sealed class NewArrayInstruction<TElement> : Instruction {
- internal NewArrayInstruction() { }
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- int length = (int)frame.Pop();
- frame.Push(new TElement[length]);
- return +1;
- }
- }
-
- public sealed class NewArrayBoundsInstruction : Instruction {
- private readonly Type _elementType;
- private readonly int _rank;
-
- internal NewArrayBoundsInstruction(Type elementType, int rank) {
- _elementType = elementType;
- _rank = rank;
- }
-
- public override int ConsumedStack { get { return _rank; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- var lengths = new int[_rank];
- for (int i = _rank - 1; i >= 0; i--) {
- lengths[i] = (int)frame.Pop();
- }
- var array = Array.CreateInstance(_elementType, lengths);
- frame.Push(array);
- return +1;
- }
- }
-
- public sealed class GetArrayItemInstruction<TElement> : Instruction {
- internal GetArrayItemInstruction() { }
-
- public override int ConsumedStack { get { return 2; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- int index = (int)frame.Pop();
- TElement[] array = (TElement[])frame.Pop();
- frame.Push(array[index]);
- return +1;
- }
-
- public override string InstructionName {
- get { return "GetArrayItem"; }
- }
- }
-
- public sealed class GetArrayLengthInstruction : Instruction {
- private static Instruction instance;
-
- private GetArrayLengthInstruction() { }
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- var array = (Array)frame.Pop();
- frame.Push(array.Length);
- return +1;
- }
-
- public static Instruction Create() {
- return instance ?? (instance = new GetArrayLengthInstruction());
- }
-
- public override string InstructionName {
- get { return "GetArrayLength"; }
- }
- }
-
- public sealed class SetArrayItemInstruction<TElement> : Instruction {
- internal SetArrayItemInstruction() { }
-
- public override int ConsumedStack { get { return 3; } }
- public override int ProducedStack { get { return 0; } }
-
- public override int Run(InterpretedFrame frame) {
- TElement value = (TElement)frame.Pop();
- int index = (int)frame.Pop();
- TElement[] array = (TElement[])frame.Pop();
- array[index] = value;
- return +1;
- }
-
- public override string InstructionName {
- get { return "SetArrayItem"; }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/CallInstruction.Generated.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/CallInstruction.Generated.cs
deleted file mode 100644
index 19163eedc6e..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/CallInstruction.Generated.cs
+++ /dev/null
@@ -1,905 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Threading;
-using Microsoft.Scripting.Utils;
-using Microsoft.Scripting.Generation;
-using Microsoft.Scripting.Runtime;
-
-using System.Dynamic;
-
-namespace Microsoft.Scripting.Interpreter {
- #region Generated Reflected Caller
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_all from: generate_reflected_calls.py
-
- public partial class CallInstruction {
- private const int MaxHelpers = 10;
- private const int MaxArgs = 3;
-
- public virtual object InvokeInstance(object instance, params object[] args) {
- switch(args.Length) {
- case 0: return Invoke(instance);
- case 1: return Invoke(instance, args[0]);
- case 2: return Invoke(instance, args[0], args[1]);
- case 3: return Invoke(instance, args[0], args[1], args[2]);
- case 4: return Invoke(instance, args[0], args[1], args[2], args[3]);
- case 5: return Invoke(instance, args[0], args[1], args[2], args[3], args[4]);
- case 6: return Invoke(instance, args[0], args[1], args[2], args[3], args[4], args[5]);
- case 7: return Invoke(instance, args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
- case 8: return Invoke(instance, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
- default: throw new InvalidOperationException();
- }
- }
-
- public virtual object Invoke(params object[] args) {
- switch(args.Length) {
- case 0: return Invoke();
- case 1: return Invoke(args[0]);
- case 2: return Invoke(args[0], args[1]);
- case 3: return Invoke(args[0], args[1], args[2]);
- case 4: return Invoke(args[0], args[1], args[2], args[3]);
- case 5: return Invoke(args[0], args[1], args[2], args[3], args[4]);
- case 6: return Invoke(args[0], args[1], args[2], args[3], args[4], args[5]);
- case 7: return Invoke(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
- case 8: return Invoke(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
- case 9: return Invoke(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
- default: throw new InvalidOperationException();
- }
- }
-
- public virtual object Invoke() { throw new InvalidOperationException(); }
- public virtual object Invoke(object arg0) { throw new InvalidOperationException(); }
- public virtual object Invoke(object arg0, object arg1) { throw new InvalidOperationException(); }
- public virtual object Invoke(object arg0, object arg1, object arg2) { throw new InvalidOperationException(); }
- public virtual object Invoke(object arg0, object arg1, object arg2, object arg3) { throw new InvalidOperationException(); }
- public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4) { throw new InvalidOperationException(); }
- public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) { throw new InvalidOperationException(); }
- public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { throw new InvalidOperationException(); }
- public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) { throw new InvalidOperationException(); }
- public virtual object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) { throw new InvalidOperationException(); }
-
- /// <summary>
- /// Fast creation works if we have a known primitive types for the entire
- /// method siganture. If we have any non-primitive types then FastCreate
- /// falls back to SlowCreate which works for all types.
- ///
- /// Fast creation is fast because it avoids using reflection (MakeGenericType
- /// and Activator.CreateInstance) to create the types. It does this through
- /// calling a series of generic methods picking up each strong type of the
- /// signature along the way. When it runs out of types it news up the
- /// appropriate CallInstruction with the strong-types that have been built up.
- ///
- /// One relaxation is that for return types which are non-primitive types
- /// we can fallback to object due to relaxed delegates.
- /// </summary>
- private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) {
- Type t = TryGetParameterOrReturnType(target, pi, 0);
- if (t == null) {
- return new ActionCallInstruction(target);
- }
-
- if (t.IsEnum()) return SlowCreate(target, pi);
- switch (t.GetTypeCode()) {
- case TypeCode.Object: {
- if (t != typeof(object) && (IndexIsNotReturnType(0, target, pi) || t.IsValueType())) {
- // if we're on the return type relaxed delegates makes it ok to use object
- goto default;
- }
- return FastCreate<Object>(target, pi);
- }
- case TypeCode.Int16: return FastCreate<Int16>(target, pi);
- case TypeCode.Int32: return FastCreate<Int32>(target, pi);
- case TypeCode.Int64: return FastCreate<Int64>(target, pi);
- case TypeCode.Boolean: return FastCreate<Boolean>(target, pi);
- case TypeCode.Char: return FastCreate<Char>(target, pi);
- case TypeCode.Byte: return FastCreate<Byte>(target, pi);
- case TypeCode.Decimal: return FastCreate<Decimal>(target, pi);
- case TypeCode.DateTime: return FastCreate<DateTime>(target, pi);
- case TypeCode.Double: return FastCreate<Double>(target, pi);
- case TypeCode.Single: return FastCreate<Single>(target, pi);
- case TypeCode.UInt16: return FastCreate<UInt16>(target, pi);
- case TypeCode.UInt32: return FastCreate<UInt32>(target, pi);
- case TypeCode.UInt64: return FastCreate<UInt64>(target, pi);
- case TypeCode.String: return FastCreate<String>(target, pi);
- case TypeCode.SByte: return FastCreate<SByte>(target, pi);
- default: return SlowCreate(target, pi);
- }
- }
-
- private static CallInstruction FastCreate<T0>(MethodInfo target, ParameterInfo[] pi) {
- Type t = TryGetParameterOrReturnType(target, pi, 1);
- if (t == null) {
- if (target.ReturnType == typeof(void)) {
- return new ActionCallInstruction<T0>(target);
- }
- return new FuncCallInstruction<T0>(target);
- }
-
- if (t.IsEnum()) return SlowCreate(target, pi);
- switch (t.GetTypeCode()) {
- case TypeCode.Object: {
- if (t != typeof(object) && (IndexIsNotReturnType(1, target, pi) || t.IsValueType())) {
- // if we're on the return type relaxed delegates makes it ok to use object
- goto default;
- }
- return FastCreate<T0, Object>(target, pi);
- }
- case TypeCode.Int16: return FastCreate<T0, Int16>(target, pi);
- case TypeCode.Int32: return FastCreate<T0, Int32>(target, pi);
- case TypeCode.Int64: return FastCreate<T0, Int64>(target, pi);
- case TypeCode.Boolean: return FastCreate<T0, Boolean>(target, pi);
- case TypeCode.Char: return FastCreate<T0, Char>(target, pi);
- case TypeCode.Byte: return FastCreate<T0, Byte>(target, pi);
- case TypeCode.Decimal: return FastCreate<T0, Decimal>(target, pi);
- case TypeCode.DateTime: return FastCreate<T0, DateTime>(target, pi);
- case TypeCode.Double: return FastCreate<T0, Double>(target, pi);
- case TypeCode.Single: return FastCreate<T0, Single>(target, pi);
- case TypeCode.UInt16: return FastCreate<T0, UInt16>(target, pi);
- case TypeCode.UInt32: return FastCreate<T0, UInt32>(target, pi);
- case TypeCode.UInt64: return FastCreate<T0, UInt64>(target, pi);
- case TypeCode.String: return FastCreate<T0, String>(target, pi);
- case TypeCode.SByte: return FastCreate<T0, SByte>(target, pi);
- default: return SlowCreate(target, pi);
- }
- }
-
- private static CallInstruction FastCreate<T0, T1>(MethodInfo target, ParameterInfo[] pi) {
- Type t = TryGetParameterOrReturnType(target, pi, 2);
- if (t == null) {
- if (target.ReturnType == typeof(void)) {
- return new ActionCallInstruction<T0, T1>(target);
- }
- return new FuncCallInstruction<T0, T1>(target);
- }
-
- if (t.IsEnum()) return SlowCreate(target, pi);
- switch (t.GetTypeCode()) {
- case TypeCode.Object: {
- Debug.Assert(pi.Length == 2);
- if (t.IsValueType()) goto default;
-
- return new FuncCallInstruction<T0, T1, Object>(target);
- }
- case TypeCode.Int16: return new FuncCallInstruction<T0, T1, Int16>(target);
- case TypeCode.Int32: return new FuncCallInstruction<T0, T1, Int32>(target);
- case TypeCode.Int64: return new FuncCallInstruction<T0, T1, Int64>(target);
- case TypeCode.Boolean: return new FuncCallInstruction<T0, T1, Boolean>(target);
- case TypeCode.Char: return new FuncCallInstruction<T0, T1, Char>(target);
- case TypeCode.Byte: return new FuncCallInstruction<T0, T1, Byte>(target);
- case TypeCode.Decimal: return new FuncCallInstruction<T0, T1, Decimal>(target);
- case TypeCode.DateTime: return new FuncCallInstruction<T0, T1, DateTime>(target);
- case TypeCode.Double: return new FuncCallInstruction<T0, T1, Double>(target);
- case TypeCode.Single: return new FuncCallInstruction<T0, T1, Single>(target);
- case TypeCode.UInt16: return new FuncCallInstruction<T0, T1, UInt16>(target);
- case TypeCode.UInt32: return new FuncCallInstruction<T0, T1, UInt32>(target);
- case TypeCode.UInt64: return new FuncCallInstruction<T0, T1, UInt64>(target);
- case TypeCode.String: return new FuncCallInstruction<T0, T1, String>(target);
- case TypeCode.SByte: return new FuncCallInstruction<T0, T1, SByte>(target);
- default: return SlowCreate(target, pi);
- }
- }
-
- private static Type GetHelperType(MethodInfo info, Type[] arrTypes) {
- Type t;
- if (info.ReturnType == typeof(void)) {
- switch (arrTypes.Length) {
- case 0: t = typeof(ActionCallInstruction); break;
- case 1: t = typeof(ActionCallInstruction<>).MakeGenericType(arrTypes); break;
- case 2: t = typeof(ActionCallInstruction<,>).MakeGenericType(arrTypes); break;
- case 3: t = typeof(ActionCallInstruction<,,>).MakeGenericType(arrTypes); break;
- case 4: t = typeof(ActionCallInstruction<,,,>).MakeGenericType(arrTypes); break;
- case 5: t = typeof(ActionCallInstruction<,,,,>).MakeGenericType(arrTypes); break;
- case 6: t = typeof(ActionCallInstruction<,,,,,>).MakeGenericType(arrTypes); break;
- case 7: t = typeof(ActionCallInstruction<,,,,,,>).MakeGenericType(arrTypes); break;
- case 8: t = typeof(ActionCallInstruction<,,,,,,,>).MakeGenericType(arrTypes); break;
- case 9: t = typeof(ActionCallInstruction<,,,,,,,,>).MakeGenericType(arrTypes); break;
- default: throw new InvalidOperationException();
- }
- } else {
- switch (arrTypes.Length) {
- case 1: t = typeof(FuncCallInstruction<>).MakeGenericType(arrTypes); break;
- case 2: t = typeof(FuncCallInstruction<,>).MakeGenericType(arrTypes); break;
- case 3: t = typeof(FuncCallInstruction<,,>).MakeGenericType(arrTypes); break;
- case 4: t = typeof(FuncCallInstruction<,,,>).MakeGenericType(arrTypes); break;
- case 5: t = typeof(FuncCallInstruction<,,,,>).MakeGenericType(arrTypes); break;
- case 6: t = typeof(FuncCallInstruction<,,,,,>).MakeGenericType(arrTypes); break;
- case 7: t = typeof(FuncCallInstruction<,,,,,,>).MakeGenericType(arrTypes); break;
- case 8: t = typeof(FuncCallInstruction<,,,,,,,>).MakeGenericType(arrTypes); break;
- case 9: t = typeof(FuncCallInstruction<,,,,,,,,>).MakeGenericType(arrTypes); break;
- case 10: t = typeof(FuncCallInstruction<,,,,,,,,,>).MakeGenericType(arrTypes); break;
- default: throw new InvalidOperationException();
- }
- }
- return t;
- }
- public static MethodInfo CacheFunc<TRet>(Func<TRet> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new FuncCallInstruction<TRet>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheFunc<T0, TRet>(Func<T0, TRet> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new FuncCallInstruction<T0, TRet>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheFunc<T0, T1, TRet>(Func<T0, T1, TRet> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new FuncCallInstruction<T0, T1, TRet>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheFunc<T0, T1, T2, TRet>(Func<T0, T1, T2, TRet> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new FuncCallInstruction<T0, T1, T2, TRet>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheFunc<T0, T1, T2, T3, TRet>(Func<T0, T1, T2, T3, TRet> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new FuncCallInstruction<T0, T1, T2, T3, TRet>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheFunc<T0, T1, T2, T3, T4, TRet>(Func<T0, T1, T2, T3, T4, TRet> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new FuncCallInstruction<T0, T1, T2, T3, T4, TRet>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheFunc<T0, T1, T2, T3, T4, T5, TRet>(Func<T0, T1, T2, T3, T4, T5, TRet> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new FuncCallInstruction<T0, T1, T2, T3, T4, T5, TRet>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheFunc<T0, T1, T2, T3, T4, T5, T6, TRet>(Func<T0, T1, T2, T3, T4, T5, T6, TRet> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new FuncCallInstruction<T0, T1, T2, T3, T4, T5, T6, TRet>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheFunc<T0, T1, T2, T3, T4, T5, T6, T7, TRet>(Func<T0, T1, T2, T3, T4, T5, T6, T7, TRet> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new FuncCallInstruction<T0, T1, T2, T3, T4, T5, T6, T7, TRet>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheFunc<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new FuncCallInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheAction(Action method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new ActionCallInstruction(method);
- }
- return info;
- }
-
- public static MethodInfo CacheAction<T0>(Action<T0> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new ActionCallInstruction<T0>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheAction<T0, T1>(Action<T0, T1> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new ActionCallInstruction<T0, T1>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheAction<T0, T1, T2>(Action<T0, T1, T2> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new ActionCallInstruction<T0, T1, T2>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheAction<T0, T1, T2, T3>(Action<T0, T1, T2, T3> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new ActionCallInstruction<T0, T1, T2, T3>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheAction<T0, T1, T2, T3, T4>(Action<T0, T1, T2, T3, T4> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new ActionCallInstruction<T0, T1, T2, T3, T4>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheAction<T0, T1, T2, T3, T4, T5>(Action<T0, T1, T2, T3, T4, T5> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new ActionCallInstruction<T0, T1, T2, T3, T4, T5>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheAction<T0, T1, T2, T3, T4, T5, T6>(Action<T0, T1, T2, T3, T4, T5, T6> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new ActionCallInstruction<T0, T1, T2, T3, T4, T5, T6>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheAction<T0, T1, T2, T3, T4, T5, T6, T7>(Action<T0, T1, T2, T3, T4, T5, T6, T7> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new ActionCallInstruction<T0, T1, T2, T3, T4, T5, T6, T7>(method);
- }
- return info;
- }
-
- public static MethodInfo CacheAction<T0, T1, T2, T3, T4, T5, T6, T7, T8>(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8> method) {
- var info = method.GetMethodInfo();
- lock (_cache) {
- _cache[info] = new ActionCallInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8>(method);
- }
- return info;
- }
-
- }
-
- internal sealed class ActionCallInstruction : CallInstruction {
- private readonly Action _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 0; } }
-
- public ActionCallInstruction(Action target) {
- _target = target;
- }
-
- public ActionCallInstruction(MethodInfo target) {
- _target = (Action)target.CreateDelegate(typeof(Action));
- }
-
- public override object Invoke() {
- _target();
- return null;
- }
-
- public override int Run(InterpretedFrame frame) {
- _target();
- frame.StackIndex -= 0;
- return 1;
- }
- }
-
- internal sealed class ActionCallInstruction<T0> : CallInstruction {
- private readonly Action<T0> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 1; } }
-
- public ActionCallInstruction(Action<T0> target) {
- _target = target;
- }
-
- public ActionCallInstruction(MethodInfo target) {
- _target = (Action<T0>)target.CreateDelegate(typeof(Action<T0>));
- }
-
- public override object Invoke(object arg0) {
- _target(arg0 != null ? (T0)arg0 : default(T0));
- return null;
- }
-
- public override int Run(InterpretedFrame frame) {
- _target((T0)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 1;
- return 1;
- }
- }
-
- internal sealed class ActionCallInstruction<T0, T1> : CallInstruction {
- private readonly Action<T0, T1> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 2; } }
-
- public ActionCallInstruction(Action<T0, T1> target) {
- _target = target;
- }
-
- public ActionCallInstruction(MethodInfo target) {
- _target = (Action<T0, T1>)target.CreateDelegate(typeof(Action<T0, T1>));
- }
-
- public override object Invoke(object arg0, object arg1) {
- _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1));
- return null;
- }
-
- public override int Run(InterpretedFrame frame) {
- _target((T0)frame.Data[frame.StackIndex - 2], (T1)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 2;
- return 1;
- }
- }
-
- internal sealed class ActionCallInstruction<T0, T1, T2> : CallInstruction {
- private readonly Action<T0, T1, T2> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 3; } }
-
- public ActionCallInstruction(Action<T0, T1, T2> target) {
- _target = target;
- }
-
- public ActionCallInstruction(MethodInfo target) {
- _target = (Action<T0, T1, T2>)target.CreateDelegate(typeof(Action<T0, T1, T2>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2) {
- _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2));
- return null;
- }
-
- public override int Run(InterpretedFrame frame) {
- _target((T0)frame.Data[frame.StackIndex - 3], (T1)frame.Data[frame.StackIndex - 2], (T2)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 3;
- return 1;
- }
- }
-
- internal sealed class ActionCallInstruction<T0, T1, T2, T3> : CallInstruction {
- private readonly Action<T0, T1, T2, T3> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 4; } }
-
- public ActionCallInstruction(Action<T0, T1, T2, T3> target) {
- _target = target;
- }
-
- public ActionCallInstruction(MethodInfo target) {
- _target = (Action<T0, T1, T2, T3>)target.CreateDelegate(typeof(Action<T0, T1, T2, T3>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2, object arg3) {
- _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3));
- return null;
- }
-
- public override int Run(InterpretedFrame frame) {
- _target((T0)frame.Data[frame.StackIndex - 4], (T1)frame.Data[frame.StackIndex - 3], (T2)frame.Data[frame.StackIndex - 2], (T3)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 4;
- return 1;
- }
- }
-
- internal sealed class ActionCallInstruction<T0, T1, T2, T3, T4> : CallInstruction {
- private readonly Action<T0, T1, T2, T3, T4> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 5; } }
-
- public ActionCallInstruction(Action<T0, T1, T2, T3, T4> target) {
- _target = target;
- }
-
- public ActionCallInstruction(MethodInfo target) {
- _target = (Action<T0, T1, T2, T3, T4>)target.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4) {
- _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4));
- return null;
- }
-
- public override int Run(InterpretedFrame frame) {
- _target((T0)frame.Data[frame.StackIndex - 5], (T1)frame.Data[frame.StackIndex - 4], (T2)frame.Data[frame.StackIndex - 3], (T3)frame.Data[frame.StackIndex - 2], (T4)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 5;
- return 1;
- }
- }
-
- internal sealed class ActionCallInstruction<T0, T1, T2, T3, T4, T5> : CallInstruction {
- private readonly Action<T0, T1, T2, T3, T4, T5> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 6; } }
-
- public ActionCallInstruction(Action<T0, T1, T2, T3, T4, T5> target) {
- _target = target;
- }
-
- public ActionCallInstruction(MethodInfo target) {
- _target = (Action<T0, T1, T2, T3, T4, T5>)target.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) {
- _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5));
- return null;
- }
-
- public override int Run(InterpretedFrame frame) {
- _target((T0)frame.Data[frame.StackIndex - 6], (T1)frame.Data[frame.StackIndex - 5], (T2)frame.Data[frame.StackIndex - 4], (T3)frame.Data[frame.StackIndex - 3], (T4)frame.Data[frame.StackIndex - 2], (T5)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 6;
- return 1;
- }
- }
-
- internal sealed class ActionCallInstruction<T0, T1, T2, T3, T4, T5, T6> : CallInstruction {
- private readonly Action<T0, T1, T2, T3, T4, T5, T6> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 7; } }
-
- public ActionCallInstruction(Action<T0, T1, T2, T3, T4, T5, T6> target) {
- _target = target;
- }
-
- public ActionCallInstruction(MethodInfo target) {
- _target = (Action<T0, T1, T2, T3, T4, T5, T6>)target.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) {
- _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5), arg6 != null ? (T6)arg6 : default(T6));
- return null;
- }
-
- public override int Run(InterpretedFrame frame) {
- _target((T0)frame.Data[frame.StackIndex - 7], (T1)frame.Data[frame.StackIndex - 6], (T2)frame.Data[frame.StackIndex - 5], (T3)frame.Data[frame.StackIndex - 4], (T4)frame.Data[frame.StackIndex - 3], (T5)frame.Data[frame.StackIndex - 2], (T6)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 7;
- return 1;
- }
- }
-
- internal sealed class ActionCallInstruction<T0, T1, T2, T3, T4, T5, T6, T7> : CallInstruction {
- private readonly Action<T0, T1, T2, T3, T4, T5, T6, T7> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 8; } }
-
- public ActionCallInstruction(Action<T0, T1, T2, T3, T4, T5, T6, T7> target) {
- _target = target;
- }
-
- public ActionCallInstruction(MethodInfo target) {
- _target = (Action<T0, T1, T2, T3, T4, T5, T6, T7>)target.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) {
- _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5), arg6 != null ? (T6)arg6 : default(T6), arg7 != null ? (T7)arg7 : default(T7));
- return null;
- }
-
- public override int Run(InterpretedFrame frame) {
- _target((T0)frame.Data[frame.StackIndex - 8], (T1)frame.Data[frame.StackIndex - 7], (T2)frame.Data[frame.StackIndex - 6], (T3)frame.Data[frame.StackIndex - 5], (T4)frame.Data[frame.StackIndex - 4], (T5)frame.Data[frame.StackIndex - 3], (T6)frame.Data[frame.StackIndex - 2], (T7)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 8;
- return 1;
- }
- }
-
- internal sealed class ActionCallInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8> : CallInstruction {
- private readonly Action<T0, T1, T2, T3, T4, T5, T6, T7, T8> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 9; } }
-
- public ActionCallInstruction(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8> target) {
- _target = target;
- }
-
- public ActionCallInstruction(MethodInfo target) {
- _target = (Action<T0, T1, T2, T3, T4, T5, T6, T7, T8>)target.CreateDelegate(typeof(Action<T0, T1, T2, T3, T4, T5, T6, T7, T8>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) {
- _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5), arg6 != null ? (T6)arg6 : default(T6), arg7 != null ? (T7)arg7 : default(T7), arg8 != null ? (T8)arg8 : default(T8));
- return null;
- }
-
- public override int Run(InterpretedFrame frame) {
- _target((T0)frame.Data[frame.StackIndex - 9], (T1)frame.Data[frame.StackIndex - 8], (T2)frame.Data[frame.StackIndex - 7], (T3)frame.Data[frame.StackIndex - 6], (T4)frame.Data[frame.StackIndex - 5], (T5)frame.Data[frame.StackIndex - 4], (T6)frame.Data[frame.StackIndex - 3], (T7)frame.Data[frame.StackIndex - 2], (T8)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 9;
- return 1;
- }
- }
-
- internal sealed class FuncCallInstruction<TRet> : CallInstruction {
- private readonly Func<TRet> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 0; } }
-
- public FuncCallInstruction(Func<TRet> target) {
- _target = target;
- }
-
- public FuncCallInstruction(MethodInfo target) {
- _target = (Func<TRet>)target.CreateDelegate(typeof(Func<TRet>));
- }
-
- public override object Invoke() {
- return _target();
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 0] = _target();
- frame.StackIndex -= -1;
- return 1;
- }
- }
-
- internal sealed class FuncCallInstruction<T0, TRet> : CallInstruction {
- private readonly Func<T0, TRet> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 1; } }
-
- public FuncCallInstruction(Func<T0, TRet> target) {
- _target = target;
- }
-
- public FuncCallInstruction(MethodInfo target) {
- _target = (Func<T0, TRet>)target.CreateDelegate(typeof(Func<T0, TRet>));
- }
-
- public override object Invoke(object arg0) {
- return _target(arg0 != null ? (T0)arg0 : default(T0));
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 1] = _target((T0)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 0;
- return 1;
- }
- }
-
- internal sealed class FuncCallInstruction<T0, T1, TRet> : CallInstruction {
- private readonly Func<T0, T1, TRet> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 2; } }
-
- public FuncCallInstruction(Func<T0, T1, TRet> target) {
- _target = target;
- }
-
- public FuncCallInstruction(MethodInfo target) {
- _target = (Func<T0, T1, TRet>)target.CreateDelegate(typeof(Func<T0, T1, TRet>));
- }
-
- public override object Invoke(object arg0, object arg1) {
- return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1));
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 2] = _target((T0)frame.Data[frame.StackIndex - 2], (T1)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 1;
- return 1;
- }
- }
-
- internal sealed class FuncCallInstruction<T0, T1, T2, TRet> : CallInstruction {
- private readonly Func<T0, T1, T2, TRet> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 3; } }
-
- public FuncCallInstruction(Func<T0, T1, T2, TRet> target) {
- _target = target;
- }
-
- public FuncCallInstruction(MethodInfo target) {
- _target = (Func<T0, T1, T2, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, TRet>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2) {
- return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2));
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 3] = _target((T0)frame.Data[frame.StackIndex - 3], (T1)frame.Data[frame.StackIndex - 2], (T2)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 2;
- return 1;
- }
- }
-
- internal sealed class FuncCallInstruction<T0, T1, T2, T3, TRet> : CallInstruction {
- private readonly Func<T0, T1, T2, T3, TRet> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 4; } }
-
- public FuncCallInstruction(Func<T0, T1, T2, T3, TRet> target) {
- _target = target;
- }
-
- public FuncCallInstruction(MethodInfo target) {
- _target = (Func<T0, T1, T2, T3, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, T3, TRet>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2, object arg3) {
- return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3));
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 4] = _target((T0)frame.Data[frame.StackIndex - 4], (T1)frame.Data[frame.StackIndex - 3], (T2)frame.Data[frame.StackIndex - 2], (T3)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 3;
- return 1;
- }
- }
-
- internal sealed class FuncCallInstruction<T0, T1, T2, T3, T4, TRet> : CallInstruction {
- private readonly Func<T0, T1, T2, T3, T4, TRet> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 5; } }
-
- public FuncCallInstruction(Func<T0, T1, T2, T3, T4, TRet> target) {
- _target = target;
- }
-
- public FuncCallInstruction(MethodInfo target) {
- _target = (Func<T0, T1, T2, T3, T4, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, TRet>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4) {
- return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4));
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 5] = _target((T0)frame.Data[frame.StackIndex - 5], (T1)frame.Data[frame.StackIndex - 4], (T2)frame.Data[frame.StackIndex - 3], (T3)frame.Data[frame.StackIndex - 2], (T4)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 4;
- return 1;
- }
- }
-
- internal sealed class FuncCallInstruction<T0, T1, T2, T3, T4, T5, TRet> : CallInstruction {
- private readonly Func<T0, T1, T2, T3, T4, T5, TRet> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 6; } }
-
- public FuncCallInstruction(Func<T0, T1, T2, T3, T4, T5, TRet> target) {
- _target = target;
- }
-
- public FuncCallInstruction(MethodInfo target) {
- _target = (Func<T0, T1, T2, T3, T4, T5, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, TRet>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) {
- return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5));
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 6] = _target((T0)frame.Data[frame.StackIndex - 6], (T1)frame.Data[frame.StackIndex - 5], (T2)frame.Data[frame.StackIndex - 4], (T3)frame.Data[frame.StackIndex - 3], (T4)frame.Data[frame.StackIndex - 2], (T5)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 5;
- return 1;
- }
- }
-
- internal sealed class FuncCallInstruction<T0, T1, T2, T3, T4, T5, T6, TRet> : CallInstruction {
- private readonly Func<T0, T1, T2, T3, T4, T5, T6, TRet> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 7; } }
-
- public FuncCallInstruction(Func<T0, T1, T2, T3, T4, T5, T6, TRet> target) {
- _target = target;
- }
-
- public FuncCallInstruction(MethodInfo target) {
- _target = (Func<T0, T1, T2, T3, T4, T5, T6, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, TRet>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) {
- return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5), arg6 != null ? (T6)arg6 : default(T6));
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 7] = _target((T0)frame.Data[frame.StackIndex - 7], (T1)frame.Data[frame.StackIndex - 6], (T2)frame.Data[frame.StackIndex - 5], (T3)frame.Data[frame.StackIndex - 4], (T4)frame.Data[frame.StackIndex - 3], (T5)frame.Data[frame.StackIndex - 2], (T6)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 6;
- return 1;
- }
- }
-
- internal sealed class FuncCallInstruction<T0, T1, T2, T3, T4, T5, T6, T7, TRet> : CallInstruction {
- private readonly Func<T0, T1, T2, T3, T4, T5, T6, T7, TRet> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 8; } }
-
- public FuncCallInstruction(Func<T0, T1, T2, T3, T4, T5, T6, T7, TRet> target) {
- _target = target;
- }
-
- public FuncCallInstruction(MethodInfo target) {
- _target = (Func<T0, T1, T2, T3, T4, T5, T6, T7, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, TRet>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) {
- return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5), arg6 != null ? (T6)arg6 : default(T6), arg7 != null ? (T7)arg7 : default(T7));
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 8] = _target((T0)frame.Data[frame.StackIndex - 8], (T1)frame.Data[frame.StackIndex - 7], (T2)frame.Data[frame.StackIndex - 6], (T3)frame.Data[frame.StackIndex - 5], (T4)frame.Data[frame.StackIndex - 4], (T5)frame.Data[frame.StackIndex - 3], (T6)frame.Data[frame.StackIndex - 2], (T7)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 7;
- return 1;
- }
- }
-
- internal sealed class FuncCallInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet> : CallInstruction {
- private readonly Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet> _target;
- public override MethodInfo Info { get { return _target.GetMethodInfo(); } }
- public override int ArgumentCount { get { return 9; } }
-
- public FuncCallInstruction(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet> target) {
- _target = target;
- }
-
- public FuncCallInstruction(MethodInfo target) {
- _target = (Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>));
- }
-
- public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) {
- return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5), arg6 != null ? (T6)arg6 : default(T6), arg7 != null ? (T7)arg7 : default(T7), arg8 != null ? (T8)arg8 : default(T8));
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 9] = _target((T0)frame.Data[frame.StackIndex - 9], (T1)frame.Data[frame.StackIndex - 8], (T2)frame.Data[frame.StackIndex - 7], (T3)frame.Data[frame.StackIndex - 6], (T4)frame.Data[frame.StackIndex - 5], (T5)frame.Data[frame.StackIndex - 4], (T6)frame.Data[frame.StackIndex - 3], (T7)frame.Data[frame.StackIndex - 2], (T8)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 8;
- return 1;
- }
- }
-
- internal sealed partial class MethodInfoCallInstruction : CallInstruction {
- public override object Invoke() {
- return InvokeWorker();
- }
- public override object Invoke(object arg0) {
- return InvokeWorker(arg0);
- }
- public override object Invoke(object arg0, object arg1) {
- return InvokeWorker(arg0, arg1);
- }
- }
-
- // *** END GENERATED CODE ***
-
- #endregion
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/CallInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/CallInstruction.cs
deleted file mode 100644
index 3875af308b9..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/CallInstruction.cs
+++ /dev/null
@@ -1,300 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-#if FEATURE_REFEMIT
-using System.Reflection.Emit;
-#endif
-using System.Security;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- public abstract partial class CallInstruction : Instruction {
- public abstract MethodInfo Info { get; }
-
- /// <summary>
- /// The number of arguments including "this" for instance methods.
- /// </summary>
- public abstract int ArgumentCount { get; }
-
- #region Construction
-
- internal CallInstruction() { }
-
- private static readonly Dictionary<MethodInfo, CallInstruction> _cache = new Dictionary<MethodInfo, CallInstruction>();
-
- /// <exception cref="SecurityException">Instruction can't be created due to insufficient privileges.</exception>
- public static CallInstruction Create(MethodInfo info) {
- return Create(info, info.GetParameters());
- }
-
- /// <exception cref="SecurityException">Instruction can't be created due to insufficient privileges.</exception>
- public static CallInstruction Create(MethodInfo info, ParameterInfo[] parameters) {
- int argumentCount = parameters.Length;
- if (!info.IsStatic) {
- argumentCount++;
- }
-
- // A workaround for CLR bug #796414 (Unable to create delegates for Array.Get/Set):
- // T[]::Address - not supported by ETs due to T& return value
- if (info.DeclaringType != null && info.DeclaringType.IsArray && (info.Name == "Get" || info.Name == "Set")) {
- return GetArrayAccessor(info, argumentCount);
- }
-
-#if FULL_AOT_RUNTIME
- return new MethodInfoCallInstruction(info, argumentCount);
-#else
- if (ReflectionUtils.IsDynamicMethod(info) || !info.IsStatic && info.DeclaringType.IsValueType()) {
- return new MethodInfoCallInstruction(info, argumentCount);
- }
-
- if (argumentCount >= MaxHelpers) {
- // no delegate for this size, fallback to reflection invoke
- return new MethodInfoCallInstruction(info, argumentCount);
- }
-
- foreach (ParameterInfo pi in parameters) {
- if (pi.ParameterType.IsByRef) {
- // we don't support ref args via generics.
- return new MethodInfoCallInstruction(info, argumentCount);
- }
- }
-
- // see if we've created one w/ a delegate
- CallInstruction res;
- if (ShouldCache(info)) {
- lock (_cache) {
- if (_cache.TryGetValue(info, out res)) {
- return res;
- }
- }
- }
-
- // create it
- try {
- if (argumentCount < MaxArgs) {
- res = FastCreate(info, parameters);
- } else {
- res = SlowCreate(info, parameters);
- }
- } catch (TargetInvocationException tie) {
- if (!(tie.InnerException is NotSupportedException)) {
- throw tie.InnerException;
- }
-
- res = new MethodInfoCallInstruction(info, argumentCount);
- } catch (NotSupportedException) {
- // if Delegate.CreateDelegate can't handle the method fallback to
- // the slow reflection version. For example this can happen w/
- // a generic method defined on an interface and implemented on a class or
- // a virtual generic method.
- res = new MethodInfoCallInstruction(info, argumentCount);
- }
-
- // cache it for future users if it's a reasonable method to cache
- if (ShouldCache(info)) {
- lock (_cache) {
- _cache[info] = res;
- }
- }
-
- return res;
-#endif
- }
-
- private static CallInstruction GetArrayAccessor(MethodInfo info, int argumentCount) {
- Type arrayType = info.DeclaringType;
- bool isGetter = info.Name == "Get";
- switch (arrayType.GetArrayRank()) {
- case 1:
- return Create(isGetter ?
- arrayType.GetMethod("GetValue", new[] { typeof(int)}) :
- new Action<Array, int, object>(ArrayItemSetter1).GetMethodInfo()
- );
-
- case 2:
- return Create(isGetter ?
- arrayType.GetMethod("GetValue", new[] { typeof(int), typeof(int) }) :
- new Action<Array, int, int, object>(ArrayItemSetter2).GetMethodInfo()
- );
-
- case 3:
- return Create(isGetter ?
- arrayType.GetMethod("GetValue", new[] { typeof(int), typeof(int), typeof(int) }) :
- new Action<Array, int, int, int, object>(ArrayItemSetter3).GetMethodInfo()
- );
-
- default:
- return new MethodInfoCallInstruction(info, argumentCount);
- }
- }
-
- public static void ArrayItemSetter1(Array array, int index0, object value) {
- array.SetValue(value, index0);
- }
-
- public static void ArrayItemSetter2(Array array, int index0, int index1, object value) {
- array.SetValue(value, index0, index1);
- }
-
- public static void ArrayItemSetter3(Array array, int index0, int index1, int index2, object value) {
- array.SetValue(value, index0, index1, index2);
- }
-
- private static bool ShouldCache(MethodInfo info) {
- return !ReflectionUtils.IsDynamicMethod(info);
- }
-
- /// <summary>
- /// Gets the next type or null if no more types are available.
- /// </summary>
- private static Type TryGetParameterOrReturnType(MethodInfo target, ParameterInfo[] pi, int index) {
- if (!target.IsStatic) {
- index--;
- if (index < 0) {
- return target.DeclaringType;
- }
- }
-
- if (index < pi.Length) {
- // next in signature
- return pi[index].ParameterType;
- }
-
- if (target.ReturnType == typeof(void) || index > pi.Length) {
- // no more parameters
- return null;
- }
-
- // last parameter on Invoke is return type
- return target.ReturnType;
- }
-
- private static bool IndexIsNotReturnType(int index, MethodInfo target, ParameterInfo[] pi) {
- return pi.Length != index || (pi.Length == index && !target.IsStatic);
- }
-
- /// <summary>
- /// Uses reflection to create new instance of the appropriate ReflectedCaller
- /// </summary>
- private static CallInstruction SlowCreate(MethodInfo info, ParameterInfo[] pis) {
- List<Type> types = new List<Type>();
- if (!info.IsStatic) types.Add(info.DeclaringType);
- foreach (ParameterInfo pi in pis) {
- types.Add(pi.ParameterType);
- }
- if (info.ReturnType != typeof(void)) {
- types.Add(info.ReturnType);
- }
- Type[] arrTypes = types.ToArray();
-
- return (CallInstruction)Activator.CreateInstance(GetHelperType(info, arrTypes), info);
- }
-
- #endregion
-
- #region Instruction
-
- public sealed override int ProducedStack { get { return Info.ReturnType == typeof(void) ? 0 : 1; } }
- public sealed override int ConsumedStack { get { return ArgumentCount; } }
-
- public sealed override string InstructionName {
- get { return "Call"; }
- }
-
- public override string ToString() {
- return "Call(" + Info + ")";
- }
-
- #endregion
- }
-
- internal sealed partial class MethodInfoCallInstruction : CallInstruction {
- private readonly MethodInfo _target;
- private readonly int _argumentCount;
-
- public override MethodInfo Info { get { return _target; } }
- public override int ArgumentCount { get { return _argumentCount; } }
-
- internal MethodInfoCallInstruction(MethodInfo target, int argumentCount) {
- _target = target;
- _argumentCount = argumentCount;
- }
-
- public override object Invoke(params object[] args) {
- return InvokeWorker(args);
- }
-
- public override object InvokeInstance(object instance, params object[] args) {
- if (_target.IsStatic) {
- try {
- return _target.Invoke(null, args);
- } catch (TargetInvocationException e) {
- throw ExceptionHelpers.UpdateForRethrow(e.InnerException);
- }
- }
-
- try {
- return _target.Invoke(instance, args);
- } catch (TargetInvocationException e) {
- throw ExceptionHelpers.UpdateForRethrow(e.InnerException);
- }
- }
-
- private object InvokeWorker(params object[] args) {
- if (_target.IsStatic) {
- try {
- return _target.Invoke(null, args);
- } catch (TargetInvocationException e) {
- throw ExceptionHelpers.UpdateForRethrow(e.InnerException);
- }
- }
-
- try {
- return _target.Invoke(args[0], GetNonStaticArgs(args));
- } catch (TargetInvocationException e) {
- throw ExceptionHelpers.UpdateForRethrow(e.InnerException);
- }
- }
-
- private static object[] GetNonStaticArgs(object[] args) {
- object[] newArgs = new object[args.Length - 1];
- for (int i = 0; i < newArgs.Length; i++) {
- newArgs[i] = args[i + 1];
- }
- return newArgs;
- }
-
- public sealed override int Run(InterpretedFrame frame) {
- int first = frame.StackIndex - _argumentCount;
- object[] args = new object[_argumentCount];
- for (int i = 0; i < args.Length; i++) {
- args[i] = frame.Data[first + i];
- }
-
- object ret = Invoke(args);
- if (_target.ReturnType != typeof(void)) {
- frame.Data[first] = ret;
- frame.StackIndex = first + 1;
- } else {
- frame.StackIndex = first;
- }
- return 1;
- }
- }
-
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ComparisonInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ComparisonInstruction.cs
deleted file mode 100644
index 95fe9e67838..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ComparisonInstruction.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-//
-// ArithmeticInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class ComparisonInstruction : ArithmeticInstruction {
-
- protected bool LiftedToNull { get; set; }
-
- protected override object Calculate (object l, object r)
- {
- if (l == null || r == null)
- return DoNullComparison (l, r);
-
- return DoCalculate (l, r);
- }
-
- protected abstract object DoNullComparison (object l, object r);
- protected abstract object DoCalculate (object l, object r);
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ConstantInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ConstantInstruction.cs
deleted file mode 100644
index 1ef324c25db..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ConstantInstruction.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-//
-// ConstantInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- sealed class PushValueInstruction : Instruction {
- object value;
-
- public override int ConsumedStack { get { return 0; } }
- public override int ProducedStack { get { return 1; } }
-
- public PushValueInstruction (object value)
- {
- this.value = value;
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Push (value);
- return +1;
- }
-
- public override string ToString() {
- return "Push(" + value + ")";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ControlFlowInstructions.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ControlFlowInstructions.cs
deleted file mode 100644
index b7549ee4b77..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ControlFlowInstructions.cs
+++ /dev/null
@@ -1,623 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_TASKS
-using System.Threading.Tasks;
-#endif
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using Microsoft.Scripting.Ast;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- using LoopFunc = Func<object[], StrongBox<object>[], InterpretedFrame, int>;
-
- internal abstract class OffsetInstruction : Instruction {
- internal const int Unknown = Int32.MinValue;
- internal const int CacheSize = 32;
-
- // the offset to jump to (relative to this instruction):
- protected int _offset = Unknown;
-
- public int Offset { get { return _offset; } }
- public abstract Instruction[] Cache { get; }
-
- public Instruction Fixup(int offset) {
- Debug.Assert(_offset == Unknown && offset != Unknown);
- _offset = offset;
-
- var cache = Cache;
- if (cache != null && offset >= 0 && offset < cache.Length) {
- return cache[offset] ?? (cache[offset] = this);
- }
-
- return this;
- }
-
- public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects) {
- return ToString() + (_offset != Unknown ? " -> " + (instructionIndex + _offset).ToString() : "");
- }
-
- public override string ToString() {
- return InstructionName + (_offset == Unknown ? "(?)" : "(" + _offset + ")");
- }
- }
-
- internal sealed class BranchFalseInstruction : OffsetInstruction {
- private static Instruction[] _cache;
-
- public override Instruction[] Cache {
- get {
- if (_cache == null) {
- _cache = new Instruction[CacheSize];
- }
- return _cache;
- }
- }
-
- internal BranchFalseInstruction() {
- }
-
- public override int ConsumedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- Debug.Assert(_offset != Unknown);
-
- if (!(bool)frame.Pop()) {
- return _offset;
- }
-
- return +1;
- }
- }
-
- internal sealed class BranchTrueInstruction : OffsetInstruction {
- private static Instruction[] _cache;
-
- public override Instruction[] Cache {
- get {
- if (_cache == null) {
- _cache = new Instruction[CacheSize];
- }
- return _cache;
- }
- }
-
- internal BranchTrueInstruction() {
- }
-
- public override int ConsumedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- Debug.Assert(_offset != Unknown);
-
- if ((bool)frame.Pop()) {
- return _offset;
- }
-
- return +1;
- }
- }
-
- internal sealed class BranchNullInstruction : OffsetInstruction {
- private static Instruction[] _cache;
-
- public override Instruction[] Cache {
- get {
- if (_cache == null) {
- _cache = new Instruction[CacheSize];
- }
- return _cache;
- }
- }
-
- internal BranchNullInstruction() {
- }
-
- public override int ConsumedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- Debug.Assert(_offset != Unknown);
-
- if (frame.Pop() == null) {
- return _offset;
- }
-
- return +1;
- }
- }
-
- internal sealed class CoalescingBranchInstruction : OffsetInstruction {
- private static Instruction[] _cache;
-
- public override Instruction[] Cache {
- get {
- if (_cache == null) {
- _cache = new Instruction[CacheSize];
- }
- return _cache;
- }
- }
-
- internal CoalescingBranchInstruction() {
- }
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- Debug.Assert(_offset != Unknown);
-
- if (frame.Peek() != null) {
- return _offset;
- }
-
- return +1;
- }
- }
-
- internal class BranchInstruction : OffsetInstruction {
- private static Instruction[][][] _caches;
-
- public override Instruction[] Cache {
- get {
- if (_caches == null) {
- _caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] };
- }
- return _caches[ConsumedStack][ProducedStack] ?? (_caches[ConsumedStack][ProducedStack] = new Instruction[CacheSize]);
- }
- }
-
- internal readonly bool _hasResult;
- internal readonly bool _hasValue;
-
- internal BranchInstruction()
- : this(false, false) {
- }
-
- public BranchInstruction(bool hasResult, bool hasValue) {
- _hasResult = hasResult;
- _hasValue = hasValue;
- }
-
- public override int ConsumedStack {
- get { return _hasValue ? 1 : 0; }
- }
-
- public override int ProducedStack {
- get { return _hasResult ? 1 : 0; }
- }
-
- public override int Run(InterpretedFrame frame) {
- Debug.Assert(_offset != Unknown);
-
- return _offset;
- }
- }
-
- internal abstract class IndexedBranchInstruction : Instruction {
- protected const int CacheSize = 32;
-
- internal readonly int _labelIndex;
-
- public IndexedBranchInstruction(int labelIndex) {
- _labelIndex = labelIndex;
- }
-
- public RuntimeLabel GetLabel(InterpretedFrame frame) {
- return frame.Interpreter._labels[_labelIndex];
- }
-
- public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects) {
- int targetIndex = labelIndexer(_labelIndex);
- return ToString() + (targetIndex != BranchLabel.UnknownIndex ? " -> " + targetIndex.ToString() : "");
- }
-
- public override string ToString() {
- return InstructionName + "[" + _labelIndex + "]";
- }
- }
-
- /// <summary>
- /// This instruction implements a goto expression that can jump out of any expression.
- /// It pops values (arguments) from the evaluation stack that the expression tree nodes in between
- /// the goto expression and the target label node pushed and not consumed yet.
- /// A goto expression can jump into a node that evaluates arguments only if it carries
- /// a value and jumps right after the first argument (the carried value will be used as the first argument).
- /// Goto can jump into an arbitrary child of a BlockExpression since the block doesn’t accumulate values
- /// on evaluation stack as its child expressions are being evaluated.
- ///
- /// Goto needs to execute any finally blocks on the way to the target label.
- /// <example>
- /// {
- /// f(1, 2, try { g(3, 4, try { goto L } finally { ... }, 6) } finally { ... }, 7, 8)
- /// L: ...
- /// }
- /// </example>
- /// The goto expression here jumps to label L while having 4 items on evaluation stack (1, 2, 3 and 4).
- /// The jump needs to execute both finally blocks, the first one on stack level 4 the
- /// second one on stack level 2. So, it needs to jump the first finally block, pop 2 items from the stack,
- /// run second finally block and pop another 2 items from the stack and set instruction pointer to label L.
- ///
- /// Goto also needs to rethrow ThreadAbortException iff it jumps out of a catch handler and
- /// the current thread is in "abort requested" state.
- /// </summary>
- internal sealed class GotoInstruction : IndexedBranchInstruction {
- private const int Variants = 4;
- private static readonly GotoInstruction[] Cache = new GotoInstruction[Variants * CacheSize];
-
- private readonly bool _hasResult;
-
- // TODO: We can remember hasValue in label and look it up when calculating stack balance. That would save some cache.
- private readonly bool _hasValue;
-
- // The values should technically be Consumed = 1, Produced = 1 for gotos that target a label whose continuation depth
- // is different from the current continuation depth. However, in case of forward gotos, we don't not know that is the
- // case until the label is emitted. By then the consumed and produced stack information is useless.
- // The important thing here is that the stack balance is 0.
- public override int ConsumedContinuations { get { return 0; } }
- public override int ProducedContinuations { get { return 0; } }
-
- public override int ConsumedStack {
- get { return _hasValue ? 1 : 0; }
- }
-
- public override int ProducedStack {
- get { return _hasResult ? 1 : 0; }
- }
-
- private GotoInstruction(int targetIndex, bool hasResult, bool hasValue)
- : base(targetIndex) {
- _hasResult = hasResult;
- _hasValue = hasValue;
- }
-
- internal static GotoInstruction Create(int labelIndex, bool hasResult, bool hasValue) {
- if (labelIndex < CacheSize) {
- var index = Variants * labelIndex | (hasResult ? 2 : 0) | (hasValue ? 1 : 0);
- return Cache[index] ?? (Cache[index] = new GotoInstruction(labelIndex, hasResult, hasValue));
- }
- return new GotoInstruction(labelIndex, hasResult, hasValue);
- }
-
- public override int Run(InterpretedFrame frame) {
- // Are we jumping out of catch/finally while aborting the current thread?
- Interpreter.AbortThreadIfRequested(frame, _labelIndex);
-
- // goto the target label or the current finally continuation:
- return frame.Goto(_labelIndex, _hasValue ? frame.Pop() : Interpreter.NoValue);
- }
- }
-
- internal sealed class EnterTryFinallyInstruction : IndexedBranchInstruction {
- private readonly static EnterTryFinallyInstruction[] Cache = new EnterTryFinallyInstruction[CacheSize];
-
- public override int ProducedContinuations { get { return 1; } }
-
- private EnterTryFinallyInstruction(int targetIndex)
- : base(targetIndex) {
- }
-
- internal static EnterTryFinallyInstruction Create(int labelIndex) {
- if (labelIndex < CacheSize) {
- return Cache[labelIndex] ?? (Cache[labelIndex] = new EnterTryFinallyInstruction(labelIndex));
- }
- return new EnterTryFinallyInstruction(labelIndex);
- }
-
- public override int Run(InterpretedFrame frame) {
- // Push finally.
- frame.PushContinuation(_labelIndex);
- return 1;
- }
- }
-
- /// <summary>
- /// The first instruction of finally block.
- /// </summary>
- internal sealed class EnterFinallyInstruction : Instruction {
- internal static readonly Instruction Instance = new EnterFinallyInstruction();
-
- public override int ProducedStack { get { return 2; } }
- public override int ConsumedContinuations { get { return 1; } }
-
- private EnterFinallyInstruction() {
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.PushPendingContinuation();
- frame.RemoveContinuation();
- return 1;
- }
- }
-
- /// <summary>
- /// The last instruction of finally block.
- /// </summary>
- internal sealed class LeaveFinallyInstruction : Instruction {
- internal static readonly Instruction Instance = new LeaveFinallyInstruction();
-
- public override int ConsumedStack { get { return 2; } }
-
- private LeaveFinallyInstruction() {
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.PopPendingContinuation();
-
- // jump to goto target or to the next finally:
- return frame.YieldToPendingContinuation();
- }
- }
-
- // no-op: we need this just to balance the stack depth.
- internal sealed class EnterExceptionHandlerInstruction : Instruction {
- internal static readonly EnterExceptionHandlerInstruction Void = new EnterExceptionHandlerInstruction(false);
- internal static readonly EnterExceptionHandlerInstruction NonVoid = new EnterExceptionHandlerInstruction(true);
-
- // True if try-expression is non-void.
- private readonly bool _hasValue;
-
- private EnterExceptionHandlerInstruction(bool hasValue) {
- _hasValue = hasValue;
- }
-
- // If an exception is throws in try-body the expression result of try-body is not evaluated and loaded to the stack.
- // So the stack doesn't contain the try-body's value when we start executing the handler.
- // However, while emitting instructions try block falls thru the catch block with a value on stack.
- // We need to declare it consumed so that the stack state upon entry to the handler corresponds to the real
- // stack depth after throw jumped to this catch block.
- public override int ConsumedStack { get { return _hasValue ? 1 : 0; } }
-
- // A variable storing the current exception is pushed to the stack by exception handling.
- // Catch handlers: The value is immediately popped and stored into a local.
- // Fault handlers: The value is kept on stack during fault handler evaluation.
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- // nop (the exception value is pushed by the interpreter in HandleCatch)
- return 1;
- }
- }
-
- /// <summary>
- /// The last instruction of a catch exception handler.
- /// </summary>
- internal sealed class LeaveExceptionHandlerInstruction : IndexedBranchInstruction {
- private static LeaveExceptionHandlerInstruction[] Cache = new LeaveExceptionHandlerInstruction[2 * CacheSize];
-
- private readonly bool _hasValue;
-
- // The catch block yields a value if the body is non-void. This value is left on the stack.
- public override int ConsumedStack {
- get { return _hasValue ? 1 : 0; }
- }
-
- public override int ProducedStack {
- get { return _hasValue ? 1 : 0; }
- }
-
- private LeaveExceptionHandlerInstruction(int labelIndex, bool hasValue)
- : base(labelIndex) {
- _hasValue = hasValue;
- }
-
- internal static LeaveExceptionHandlerInstruction Create(int labelIndex, bool hasValue) {
- if (labelIndex < CacheSize) {
- int index = (2 * labelIndex) | (hasValue ? 1 : 0);
- return Cache[index] ?? (Cache[index] = new LeaveExceptionHandlerInstruction(labelIndex, hasValue));
- }
- return new LeaveExceptionHandlerInstruction(labelIndex, hasValue);
- }
-
- public override int Run(InterpretedFrame frame) {
- // CLR rethrows ThreadAbortException when leaving catch handler if abort is requested on the current thread.
- Interpreter.AbortThreadIfRequested(frame, _labelIndex);
- return GetLabel(frame).Index - frame.InstructionIndex;
- }
- }
-
- /// <summary>
- /// The last instruction of a fault exception handler.
- /// </summary>
- internal sealed class LeaveFaultInstruction : Instruction {
- internal static readonly Instruction NonVoid = new LeaveFaultInstruction(true);
- internal static readonly Instruction Void = new LeaveFaultInstruction(false);
-
- private readonly bool _hasValue;
-
- // The fault block has a value if the body is non-void, but the value is never used.
- // We compile the body of a fault block as void.
- // However, we keep the exception object that was pushed upon entering the fault block on the stack during execution of the block
- // and pop it at the end.
- public override int ConsumedStack {
- get { return 1; }
- }
-
- // While emitting instructions a non-void try-fault expression is expected to produce a value.
- public override int ProducedStack {
- get { return _hasValue ? 1 : 0; }
- }
-
- private LeaveFaultInstruction(bool hasValue) {
- _hasValue = hasValue;
- }
-
- public override int Run(InterpretedFrame frame) {
- // TODO: ThreadAbortException ?
-
- object exception = frame.Pop();
- ExceptionHandler handler;
- return frame.Interpreter.GotoHandler(frame, exception, out handler);
- }
- }
-
-
- internal sealed class ThrowInstruction : Instruction {
- internal static readonly ThrowInstruction Throw = new ThrowInstruction(true, false);
- internal static readonly ThrowInstruction VoidThrow = new ThrowInstruction(false, false);
- internal static readonly ThrowInstruction Rethrow = new ThrowInstruction(true, true);
- internal static readonly ThrowInstruction VoidRethrow = new ThrowInstruction(false, true);
-
- private readonly bool _hasResult, _rethrow;
-
- private ThrowInstruction(bool hasResult, bool isRethrow) {
- _hasResult = hasResult;
- _rethrow = isRethrow;
- }
-
- public override int ProducedStack {
- get { return _hasResult ? 1 : 0; }
- }
-
- public override int ConsumedStack {
- get {
- return 1;
- }
- }
-
- public override int Run(InterpretedFrame frame) {
- var ex = (Exception)frame.Pop();
- if (_rethrow) {
- ExceptionHandler handler;
- return frame.Interpreter.GotoHandler(frame, ex, out handler);
- }
- throw ex;
- }
- }
-
- internal sealed class SwitchInstruction : Instruction {
- private readonly Dictionary<int, int> _cases;
-
- internal SwitchInstruction(Dictionary<int, int> cases) {
- Assert.NotNull(cases);
- _cases = cases;
- }
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 0; } }
-
- public override int Run(InterpretedFrame frame) {
- int target;
- return _cases.TryGetValue((int)frame.Pop(), out target) ? target : 1;
- }
- }
-
- internal sealed class EnterLoopInstruction : Instruction {
- private readonly int _instructionIndex;
- private Dictionary<ParameterExpression, LocalVariable> _variables;
- private Dictionary<ParameterExpression, LocalVariable> _closureVariables;
- private LoopExpression _loop;
- private int _loopEnd;
- private int _compilationThreshold;
-
- internal EnterLoopInstruction(LoopExpression loop, LocalVariables locals, int compilationThreshold, int instructionIndex) {
- _loop = loop;
- _variables = locals.CopyLocals();
- _closureVariables = locals.ClosureVariables;
- _compilationThreshold = compilationThreshold;
- _instructionIndex = instructionIndex;
- }
-
- internal void FinishLoop(int loopEnd) {
- _loopEnd = loopEnd;
- }
-
- public override int Run(InterpretedFrame frame) {
- // Don't lock here, it's a frequently hit path.
- //
- // There could be multiple threads racing, but that is okay.
- // Two bad things can happen:
- // * We miss decrements (some thread sets the counter forward)
- // * We might enter the "if" branch more than once.
- //
- // The first is okay, it just means we take longer to compile.
- // The second we explicitly guard against inside of Compile().
- //
- // We can't miss 0. The first thread that writes -1 must have read 0 and hence start compilation.
- if (unchecked(_compilationThreshold--) == 0) {
-#if SILVERLIGHT
- if (PlatformAdaptationLayer.IsCompactFramework) {
- _compilationThreshold = Int32.MaxValue;
- return 1;
- }
-#endif
- if (frame.Interpreter.CompileSynchronously) {
- Compile(frame);
- } else {
- // Kick off the compile on another thread so this one can keep going,
- // Compile method backpatches the instruction when finished so we don't need to await the task.
-#if FEATURE_TASKS
- new Task(Compile, frame).Start();
-#else
- ThreadPool.QueueUserWorkItem(Compile, frame);
-#endif
- }
- }
- return 1;
- }
-
- private bool Compiled {
- get { return _loop == null; }
- }
-
- private void Compile(object frameObj) {
- if (Compiled) {
- return;
- }
-
- lock (this) {
- if (Compiled) {
- return;
- }
-
- PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Interpreted loop compiled");
-
- InterpretedFrame frame = (InterpretedFrame)frameObj;
- var compiler = new LoopCompiler(_loop, frame.Interpreter.LabelMapping, _variables, _closureVariables, _instructionIndex, _loopEnd);
- var instructions = frame.Interpreter.Instructions.Instructions;
-
- // replace this instruction with an optimized one:
- Interlocked.Exchange(ref instructions[_instructionIndex], new CompiledLoopInstruction(compiler.CreateDelegate()));
-
- // invalidate this instruction, some threads may still hold on it:
- _loop = null;
- _variables = null;
- _closureVariables = null;
- }
- }
- }
-
- internal sealed class CompiledLoopInstruction : Instruction {
- private readonly LoopFunc _compiledLoop;
-
- public CompiledLoopInstruction(LoopFunc compiledLoop) {
- Assert.NotNull(compiledLoop);
- _compiledLoop = compiledLoop;
- }
-
- public override int Run(InterpretedFrame frame) {
- return _compiledLoop(frame.Data, frame.Closure, frame);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DivInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DivInstruction.cs
deleted file mode 100644
index f7d14972564..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DivInstruction.cs
+++ /dev/null
@@ -1,132 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class DivInstruction : Instruction {
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double;
-
- public override int ConsumedStack { get { return 2; } }
- public override int ProducedStack { get { return 1; } }
-
- private DivInstruction() {
- }
-
- internal sealed class DivInt32 : DivInstruction {
- public override int Run(InterpretedFrame frame) {
- object l = frame.Data[frame.StackIndex - 2];
- object r = frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject((Int32)l / (Int32)r);
- frame.StackIndex--;
- return 1;
- }
- }
-
- internal sealed class DivInt16 : DivInstruction {
- public override int Run(InterpretedFrame frame) {
- object l = frame.Data[frame.StackIndex - 2];
- object r = frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 2] = (Int16)((Int16)l / (Int16)r);
- frame.StackIndex--;
- return 1;
- }
- }
-
- internal sealed class DivInt64 : DivInstruction {
- public override int Run(InterpretedFrame frame) {
- object l = frame.Data[frame.StackIndex - 2];
- object r = frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 2] = (Int64)((Int64)l / (Int64)r);
- frame.StackIndex--;
- return 1;
- }
- }
-
- internal sealed class DivUInt16 : DivInstruction {
- public override int Run(InterpretedFrame frame) {
- object l = frame.Data[frame.StackIndex - 2];
- object r = frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 2] = (UInt16)((UInt16)l / (UInt16)r);
- frame.StackIndex--;
- return 1;
- }
- }
-
- internal sealed class DivUInt32 : DivInstruction {
- public override int Run(InterpretedFrame frame) {
- object l = frame.Data[frame.StackIndex - 2];
- object r = frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 2] = (UInt32)((UInt32)l / (UInt32)r);
- frame.StackIndex--;
- return 1;
- }
- }
-
- internal sealed class DivUInt64 : DivInstruction {
- public override int Run(InterpretedFrame frame) {
- object l = frame.Data[frame.StackIndex - 2];
- object r = frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 2] = (UInt64)((UInt64)l / (UInt64)r);
- frame.StackIndex--;
- return 1;
- }
- }
-
- internal sealed class DivSingle : DivInstruction {
- public override int Run(InterpretedFrame frame) {
- object l = frame.Data[frame.StackIndex - 2];
- object r = frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 2] = (Single)((Single)l / (Single)r);
- frame.StackIndex--;
- return 1;
- }
- }
-
- internal sealed class DivDouble : DivInstruction {
- public override int Run(InterpretedFrame frame) {
- object l = frame.Data[frame.StackIndex - 2];
- object r = frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 2] = (Double)l / (Double)r;
- frame.StackIndex--;
- return 1;
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new DivInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new DivInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new DivInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new DivUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new DivUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new DivUInt64());
- case TypeCode.Single: return _Single ?? (_Single = new DivSingle());
- case TypeCode.Double: return _Double ?? (_Double = new DivDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "Div()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicInstructionN.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicInstructionN.cs
deleted file mode 100644
index 70576695132..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicInstructionN.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-
-using System;
-using System.Linq;
-using System.Collections.Generic;
-using System.Runtime.CompilerServices;
-using System.Reflection;
-
-using Microsoft.Scripting.Utils;
-using System.Security;
-
-namespace Microsoft.Scripting.Interpreter {
- internal sealed partial class DynamicInstructionN : Instruction {
- private readonly CallInstruction _targetInvocationInstruction;
- private readonly object _targetDelegate;
- private readonly CallSite _site;
- private readonly int _argumentCount;
- private readonly bool _isVoid;
-
- public DynamicInstructionN(Type delegateType, CallSite site) {
- var methodInfo = delegateType.GetMethod("Invoke");
- var parameters = methodInfo.GetParameters();
-
- // <Delegate>.Invoke is ok to target by a delegate in partial trust (SecurityException is not thrown):
- _targetInvocationInstruction = CallInstruction.Create(methodInfo, parameters);
- _site = site;
- _argumentCount = parameters.Length - 1;
- _targetDelegate = site.GetType().GetInheritedFields("Target").First().GetValue(site);
- }
-
- public DynamicInstructionN(Type delegateType, CallSite site, bool isVoid)
- : this(delegateType, site) {
- _isVoid = isVoid;
- }
-
- public override int ProducedStack { get { return _isVoid ? 0 : 1; } }
- public override int ConsumedStack { get { return _argumentCount; } }
-
- public override int Run(InterpretedFrame frame) {
- int first = frame.StackIndex - _argumentCount;
- object[] args = new object[1 + _argumentCount];
- args[0] = _site;
- for (int i = 0; i < _argumentCount; i++) {
- args[1 + i] = frame.Data[first + i];
- }
-
- object ret = _targetInvocationInstruction.InvokeInstance(_targetDelegate, args);
- if (_isVoid) {
- frame.StackIndex = first;
- } else {
- frame.Data[first] = ret;
- frame.StackIndex = first + 1;
- }
-
- return 1;
- }
-
- public override string ToString() {
- return "DynamicInstructionN(" + _site + ")";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicInstructions.Generated.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicInstructions.Generated.cs
deleted file mode 100644
index c98b957f6ce..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicInstructions.Generated.cs
+++ /dev/null
@@ -1,509 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-
-using System;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal partial class DynamicInstructionN {
- internal static Type GetDynamicInstructionType(Type delegateType) {
- Type[] argTypes = delegateType.GetGenericArguments();
- if (argTypes.Length == 0) return null;
- Type genericType;
- Type[] newArgTypes = ArrayUtils.RemoveFirst(argTypes);
- switch (newArgTypes.Length) {
- #region Generated Dynamic Instruction Types
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_types from: generate_dynamic_instructions.py
-
- case 1: genericType = typeof(DynamicInstruction<>); break;
- case 2: genericType = typeof(DynamicInstruction<,>); break;
- case 3: genericType = typeof(DynamicInstruction<,,>); break;
- case 4: genericType = typeof(DynamicInstruction<,,,>); break;
- case 5: genericType = typeof(DynamicInstruction<,,,,>); break;
- case 6: genericType = typeof(DynamicInstruction<,,,,,>); break;
- case 7: genericType = typeof(DynamicInstruction<,,,,,,>); break;
- case 8: genericType = typeof(DynamicInstruction<,,,,,,,>); break;
- case 9: genericType = typeof(DynamicInstruction<,,,,,,,,>); break;
- case 10: genericType = typeof(DynamicInstruction<,,,,,,,,,>); break;
- case 11: genericType = typeof(DynamicInstruction<,,,,,,,,,,>); break;
- case 12: genericType = typeof(DynamicInstruction<,,,,,,,,,,,>); break;
- case 13: genericType = typeof(DynamicInstruction<,,,,,,,,,,,,>); break;
- case 14: genericType = typeof(DynamicInstruction<,,,,,,,,,,,,,>); break;
- case 15: genericType = typeof(DynamicInstruction<,,,,,,,,,,,,,,>); break;
- case 16: genericType = typeof(DynamicInstruction<,,,,,,,,,,,,,,,>); break;
-
- // *** END GENERATED CODE ***
-
- #endregion
- default:
- throw Assert.Unreachable;
- }
-
- return genericType.MakeGenericType(newArgTypes);
- }
-
- internal static Instruction CreateUntypedInstruction(CallSiteBinder binder, int argCount) {
- // DLR Ref.Emits an UpdateAndExecute delegate for sites with more than 10 parameters
- if (argCount > 10 && PlatformAdaptationLayer.IsCompactFramework) {
- return null;
- }
-
- switch (argCount) {
- #region Generated Untyped Dynamic Instructions
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_untyped from: generate_dynamic_instructions.py
-
- case 0: return DynamicInstruction<object>.Factory(binder);
- case 1: return DynamicInstruction<object, object>.Factory(binder);
- case 2: return DynamicInstruction<object, object, object>.Factory(binder);
- case 3: return DynamicInstruction<object, object, object, object>.Factory(binder);
- case 4: return DynamicInstruction<object, object, object, object, object>.Factory(binder);
- case 5: return DynamicInstruction<object, object, object, object, object, object>.Factory(binder);
- case 6: return DynamicInstruction<object, object, object, object, object, object, object>.Factory(binder);
- case 7: return DynamicInstruction<object, object, object, object, object, object, object, object>.Factory(binder);
- case 8: return DynamicInstruction<object, object, object, object, object, object, object, object, object>.Factory(binder);
- case 9: return DynamicInstruction<object, object, object, object, object, object, object, object, object, object>.Factory(binder);
- case 10: return DynamicInstruction<object, object, object, object, object, object, object, object, object, object, object>.Factory(binder);
- case 11: return DynamicInstruction<object, object, object, object, object, object, object, object, object, object, object, object>.Factory(binder);
- case 12: return DynamicInstruction<object, object, object, object, object, object, object, object, object, object, object, object, object>.Factory(binder);
- case 13: return DynamicInstruction<object, object, object, object, object, object, object, object, object, object, object, object, object, object>.Factory(binder);
- case 14: return DynamicInstruction<object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>.Factory(binder);
- case 15: return DynamicInstruction<object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>.Factory(binder);
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- default: return null;
- }
- }
- }
-
- #region Generated Dynamic Instructions
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_instructions from: generate_dynamic_instructions.py
-
- internal class DynamicInstruction<TRet> : Instruction {
- private CallSite<Func<CallSite,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<TRet>(CallSite<Func<CallSite,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 0; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 0] = _site.Target(_site);
- frame.StackIndex -= -1;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,TRet>(CallSite<Func<CallSite,T0,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 1] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 1]);
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,TRet>(CallSite<Func<CallSite,T0,T1,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 2; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 2] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 2], (T1)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 1;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,T2,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,T2,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,T2,TRet>(CallSite<Func<CallSite,T0,T1,T2,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,T2,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 3; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 3] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 3], (T1)frame.Data[frame.StackIndex - 2], (T2)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 2;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,T2,T3,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,T2,T3,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,T2,T3,TRet>(CallSite<Func<CallSite,T0,T1,T2,T3,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,T2,T3,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 4; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 4] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 4], (T1)frame.Data[frame.StackIndex - 3], (T2)frame.Data[frame.StackIndex - 2], (T3)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 3;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,T2,T3,T4,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,T2,T3,T4,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,T2,T3,T4,TRet>(CallSite<Func<CallSite,T0,T1,T2,T3,T4,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,T2,T3,T4,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 5; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 5] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 5], (T1)frame.Data[frame.StackIndex - 4], (T2)frame.Data[frame.StackIndex - 3], (T3)frame.Data[frame.StackIndex - 2], (T4)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 4;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,T2,T3,T4,T5,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,T2,T3,T4,T5,TRet>(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 6; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 6] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 6], (T1)frame.Data[frame.StackIndex - 5], (T2)frame.Data[frame.StackIndex - 4], (T3)frame.Data[frame.StackIndex - 3], (T4)frame.Data[frame.StackIndex - 2], (T5)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 5;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,TRet>(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 7; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 7] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 7], (T1)frame.Data[frame.StackIndex - 6], (T2)frame.Data[frame.StackIndex - 5], (T3)frame.Data[frame.StackIndex - 4], (T4)frame.Data[frame.StackIndex - 3], (T5)frame.Data[frame.StackIndex - 2], (T6)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 6;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,TRet>(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 8; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 8] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 8], (T1)frame.Data[frame.StackIndex - 7], (T2)frame.Data[frame.StackIndex - 6], (T3)frame.Data[frame.StackIndex - 5], (T4)frame.Data[frame.StackIndex - 4], (T5)frame.Data[frame.StackIndex - 3], (T6)frame.Data[frame.StackIndex - 2], (T7)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 7;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 9; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 9] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 9], (T1)frame.Data[frame.StackIndex - 8], (T2)frame.Data[frame.StackIndex - 7], (T3)frame.Data[frame.StackIndex - 6], (T4)frame.Data[frame.StackIndex - 5], (T5)frame.Data[frame.StackIndex - 4], (T6)frame.Data[frame.StackIndex - 3], (T7)frame.Data[frame.StackIndex - 2], (T8)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 8;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 10; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 10] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 10], (T1)frame.Data[frame.StackIndex - 9], (T2)frame.Data[frame.StackIndex - 8], (T3)frame.Data[frame.StackIndex - 7], (T4)frame.Data[frame.StackIndex - 6], (T5)frame.Data[frame.StackIndex - 5], (T6)frame.Data[frame.StackIndex - 4], (T7)frame.Data[frame.StackIndex - 3], (T8)frame.Data[frame.StackIndex - 2], (T9)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 9;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 11; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 11] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 11], (T1)frame.Data[frame.StackIndex - 10], (T2)frame.Data[frame.StackIndex - 9], (T3)frame.Data[frame.StackIndex - 8], (T4)frame.Data[frame.StackIndex - 7], (T5)frame.Data[frame.StackIndex - 6], (T6)frame.Data[frame.StackIndex - 5], (T7)frame.Data[frame.StackIndex - 4], (T8)frame.Data[frame.StackIndex - 3], (T9)frame.Data[frame.StackIndex - 2], (T10)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 10;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 12; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 12] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 12], (T1)frame.Data[frame.StackIndex - 11], (T2)frame.Data[frame.StackIndex - 10], (T3)frame.Data[frame.StackIndex - 9], (T4)frame.Data[frame.StackIndex - 8], (T5)frame.Data[frame.StackIndex - 7], (T6)frame.Data[frame.StackIndex - 6], (T7)frame.Data[frame.StackIndex - 5], (T8)frame.Data[frame.StackIndex - 4], (T9)frame.Data[frame.StackIndex - 3], (T10)frame.Data[frame.StackIndex - 2], (T11)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 11;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 13; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 13] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 13], (T1)frame.Data[frame.StackIndex - 12], (T2)frame.Data[frame.StackIndex - 11], (T3)frame.Data[frame.StackIndex - 10], (T4)frame.Data[frame.StackIndex - 9], (T5)frame.Data[frame.StackIndex - 8], (T6)frame.Data[frame.StackIndex - 7], (T7)frame.Data[frame.StackIndex - 6], (T8)frame.Data[frame.StackIndex - 5], (T9)frame.Data[frame.StackIndex - 4], (T10)frame.Data[frame.StackIndex - 3], (T11)frame.Data[frame.StackIndex - 2], (T12)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 12;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 14; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 14] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 14], (T1)frame.Data[frame.StackIndex - 13], (T2)frame.Data[frame.StackIndex - 12], (T3)frame.Data[frame.StackIndex - 11], (T4)frame.Data[frame.StackIndex - 10], (T5)frame.Data[frame.StackIndex - 9], (T6)frame.Data[frame.StackIndex - 8], (T7)frame.Data[frame.StackIndex - 7], (T8)frame.Data[frame.StackIndex - 6], (T9)frame.Data[frame.StackIndex - 5], (T10)frame.Data[frame.StackIndex - 4], (T11)frame.Data[frame.StackIndex - 3], (T12)frame.Data[frame.StackIndex - 2], (T13)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 13;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
- internal class DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet> : Instruction {
- private CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>> _site;
-
- public static Instruction Factory(CallSiteBinder binder) {
- return new DynamicInstruction<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>>.Create(binder));
- }
-
- private DynamicInstruction(CallSite<Func<CallSite,T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>> site) {
- _site = site;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return 15; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex - 15] = _site.Target(_site, (T0)frame.Data[frame.StackIndex - 15], (T1)frame.Data[frame.StackIndex - 14], (T2)frame.Data[frame.StackIndex - 13], (T3)frame.Data[frame.StackIndex - 12], (T4)frame.Data[frame.StackIndex - 11], (T5)frame.Data[frame.StackIndex - 10], (T6)frame.Data[frame.StackIndex - 9], (T7)frame.Data[frame.StackIndex - 8], (T8)frame.Data[frame.StackIndex - 7], (T9)frame.Data[frame.StackIndex - 6], (T10)frame.Data[frame.StackIndex - 5], (T11)frame.Data[frame.StackIndex - 4], (T12)frame.Data[frame.StackIndex - 3], (T13)frame.Data[frame.StackIndex - 2], (T14)frame.Data[frame.StackIndex - 1]);
- frame.StackIndex -= 14;
- return 1;
- }
-
- public override string ToString() {
- return "Dynamic(" + _site.Binder.ToString() + ")";
- }
- }
-
-
- // *** END GENERATED CODE ***
-
- #endregion
-
-
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicSplatInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicSplatInstruction.cs
deleted file mode 100644
index b2426e7b414..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicSplatInstruction.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-
-using System;
-using System.Collections.Generic;
-using System.Runtime.CompilerServices;
-using System.Reflection;
-
-using Microsoft.Scripting.Utils;
-using Microsoft.Scripting.Ast;
-using Microsoft.Scripting.Runtime;
-
-namespace Microsoft.Scripting.Interpreter {
- /// <summary>
- /// Implements dynamic call site with many arguments. Wraps the arguments into <see cref="ArgumentArray"/>.
- /// </summary>
- internal sealed partial class DynamicSplatInstruction : Instruction {
- private readonly CallSite<Func<CallSite, ArgumentArray, object>> _site;
- private readonly int _argumentCount;
-
- internal DynamicSplatInstruction(int argumentCount, CallSite<Func<CallSite, ArgumentArray, object>> site) {
- _site = site;
- _argumentCount = argumentCount;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return _argumentCount; } }
-
- public override int Run(InterpretedFrame frame) {
- int first = frame.StackIndex - _argumentCount;
- object ret = _site.Target(_site, new ArgumentArray(frame.Data, first, _argumentCount));
- frame.Data[first] = ret;
- frame.StackIndex = first + 1;
-
- return 1;
- }
-
- public override string ToString() {
- return "DynamicSplatInstruction(" + _site + ")";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/EqualInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/EqualInstruction.cs
deleted file mode 100644
index ad4c33d19fb..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/EqualInstruction.cs
+++ /dev/null
@@ -1,201 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class EqualInstruction : ComparisonInstruction {
- // Perf: EqualityComparer<T> but is 3/2 to 2 times slower.
- private static Instruction _Reference, _Boolean, _SByte, _Int16, _Char, _String, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double;
- private static Instruction _BooleanLifted, _SByteLifted, _Int16Lifted, _CharLifted, _Int32Lifted, _Int64Lifted,
- _ByteLifted, _UInt16Lifted, _UInt32Lifted, _UInt64Lifted, _SingleLifted, _DoubleLifted;
-
- private EqualInstruction() {
- }
-
- protected override object DoNullComparison (object l, object r)
- {
- return LiftedToNull ? (object) null : (object) l == r;
- }
-
- internal sealed class EqualBoolean : EqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Boolean)l == (Boolean)r;
- }
- }
-
- internal sealed class EqualSByte : EqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (SByte)l == (SByte)r;
- }
- }
-
- internal sealed class EqualInt16 : EqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int16)l == (Int16)r;
- }
- }
-
- internal sealed class EqualChar : EqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Char)l == (Char)r;
- }
- }
-
- internal sealed class EqualString : EqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (String)l == (String)r;
- }
- }
-
- internal sealed class EqualInt32 : EqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int32)l == (Int32)r;
- }
- }
-
- internal sealed class EqualInt64 : EqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int64)l == (Int64)r;
- }
- }
-
- internal sealed class EqualByte : EqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Byte)l == (Byte)r;
- }
- }
-
- internal sealed class EqualUInt16 : EqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt16)l == (UInt16)r;
- }
- }
-
- internal sealed class EqualUInt32 : EqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt32)l == (UInt32)r;
- }
- }
-
- internal sealed class EqualUInt64 : EqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt64)l == (UInt64)r;
- }
- }
-
- internal sealed class EqualSingle : EqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Single)l == (Single)r;
- }
- }
-
- internal sealed class EqualDouble : EqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Double)l == (Double)r;
- }
- }
-
- internal sealed class EqualReference : EqualInstruction {
- protected override object Calculate (object l, object r)
- {
- return l == r;
- }
-
- protected override object DoCalculate (object l, object r)
- {
- throw Assert.Unreachable;
- }
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- public static Instruction Create(Type type) {
- // Boxed enums can be unboxed as their underlying types:
- switch ((type.IsEnum() ? Enum.GetUnderlyingType(type) : type).GetTypeCode()) {
- case TypeCode.Boolean: return _Boolean ?? (_Boolean = new EqualBoolean());
- case TypeCode.SByte: return _SByte ?? (_SByte = new EqualSByte());
- case TypeCode.Byte: return _Byte ?? (_Byte = new EqualByte());
- case TypeCode.Char: return _Char ?? (_Char = new EqualChar());
- case TypeCode.String: return _String ?? (_String = new EqualString());
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new EqualInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new EqualInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new EqualInt64());
-
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new EqualInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new EqualInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new EqualInt64());
-
- case TypeCode.Single: return _Single ?? (_Single = new EqualSingle());
- case TypeCode.Double: return _Double ?? (_Double = new EqualDouble());
-
- case TypeCode.Object:
- if (!type.IsValueType()) {
- return _Reference ?? (_Reference = new EqualReference());
- }
- // TODO: Nullable<T>
- throw new NotImplementedException();
-
- default:
- throw new NotImplementedException();
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- // Boxed enums can be unboxed as their underlying types:
- switch ((type.IsEnum() ? Enum.GetUnderlyingType(type) : type).GetTypeCode()) {
- case TypeCode.Boolean: return _BooleanLifted ?? (_BooleanLifted = new EqualBoolean() { LiftedToNull = true });
- case TypeCode.SByte: return _SByteLifted ?? (_SByteLifted = new EqualSByte() { LiftedToNull = true });
- case TypeCode.Byte: return _ByteLifted ?? (_ByteLifted = new EqualByte() { LiftedToNull = true });
- case TypeCode.Char: return _CharLifted ?? (_CharLifted = new EqualChar() { LiftedToNull = true });
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new EqualInt16() { LiftedToNull = true });
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new EqualInt32() { LiftedToNull = true });
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new EqualInt64() { LiftedToNull = true });
-
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new EqualInt16() { LiftedToNull = true });
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new EqualInt32() { LiftedToNull = true });
- case TypeCode.UInt64: return _UInt64Lifted ?? (_UInt64Lifted = new EqualInt64() { LiftedToNull = true });
-
- case TypeCode.Single: return _SingleLifted ?? (_SingleLifted = new EqualSingle() { LiftedToNull = true });
- case TypeCode.Double: return _DoubleLifted ?? (_DoubleLifted = new EqualDouble() { LiftedToNull = true });
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "Equal()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/FieldOperations.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/FieldOperations.cs
deleted file mode 100644
index 4bb8ec65c46..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/FieldOperations.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal sealed class LoadStaticFieldInstruction : Instruction {
- private readonly FieldInfo _field;
-
- public LoadStaticFieldInstruction(FieldInfo field) {
- Debug.Assert(field.IsStatic);
- _field = field;
- }
-
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Push(_field.GetValue(null));
- return +1;
- }
- }
-
- internal sealed class LoadFieldInstruction : Instruction {
- private readonly FieldInfo _field;
-
- public LoadFieldInstruction(FieldInfo field) {
- Assert.NotNull(field);
- _field = field;
- }
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Push(_field.GetValue(frame.Pop()));
- return +1;
- }
- }
-
- internal sealed class StoreFieldInstruction : Instruction {
- private readonly FieldInfo _field;
-
- public StoreFieldInstruction(FieldInfo field) {
- Assert.NotNull(field);
- _field = field;
- }
-
- public override int ConsumedStack { get { return 2; } }
- public override int ProducedStack { get { return 0; } }
-
- public override int Run(InterpretedFrame frame) {
- object value = frame.Pop();
- object self = frame.Pop();
- _field.SetValue(self, value);
- return +1;
- }
- }
-
- internal sealed class StoreStaticFieldInstruction : Instruction {
- private readonly FieldInfo _field;
-
- public StoreStaticFieldInstruction(FieldInfo field) {
- Assert.NotNull(field);
- _field = field;
- }
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 0; } }
-
- public override int Run(InterpretedFrame frame) {
- object value = frame.Pop();
- _field.SetValue(null, value);
- return +1;
- }
- }
-} \ No newline at end of file
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/GreaterThanInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/GreaterThanInstruction.cs
deleted file mode 100644
index 48d69a85ae6..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/GreaterThanInstruction.cs
+++ /dev/null
@@ -1,171 +0,0 @@
-//
-// GreaterThanInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- abstract class GreaterThanInstruction : ComparisonInstruction {
- private static Instruction _SByte, _Int16, _Char, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double;
- private static Instruction _SByteLifted, _Int16Lifted, _CharLifted, _Int32Lifted, _Int64Lifted, _ByteLifted, _UInt16Lifted, _UInt32Lifted, _UInt64Lifted, _SingleLifted, _DoubleLifted;
-
- private GreaterThanInstruction() {
- }
-
- protected override object DoNullComparison (object l, object r)
- {
- return LiftedToNull ? (object) null : (object) false;
- }
-
- internal sealed class GreaterThanSByte : GreaterThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (SByte)l > (SByte)r;
- }
- }
-
- internal sealed class GreaterThanInt16 : GreaterThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int16)l > (Int16)r;
- }
- }
-
- internal sealed class GreaterThanChar : GreaterThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Char)l > (Char)r;
- }
- }
-
- internal sealed class GreaterThanInt32 : GreaterThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int32)l > (Int32)r;
- }
- }
-
- internal sealed class GreaterThanInt64 : GreaterThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int64)l > (Int64)r;
- }
- }
-
- internal sealed class GreaterThanByte : GreaterThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Byte)l > (Byte)r;
- }
- }
-
- internal sealed class GreaterThanUInt16 : GreaterThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt16)l > (UInt16)r;
- }
- }
-
- internal sealed class GreaterThanUInt32 : GreaterThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt32)l > (UInt32)r;
- }
- }
-
- internal sealed class GreaterThanUInt64 : GreaterThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt64)l > (UInt64)r;
- }
- }
-
- internal sealed class GreaterThanSingle : GreaterThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Single)l > (Single)r;
- }
- }
-
- internal sealed class GreaterThanDouble : GreaterThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Double)l > (Double)r;
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.SByte: return _SByte ?? (_SByte = new GreaterThanSByte());
- case TypeCode.Byte: return _Byte ?? (_Byte = new GreaterThanByte());
- case TypeCode.Char: return _Char ?? (_Char = new GreaterThanChar());
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new GreaterThanInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new GreaterThanInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new GreaterThanInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new GreaterThanUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new GreaterThanUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new GreaterThanUInt64());
- case TypeCode.Single: return _Single ?? (_Single = new GreaterThanSingle());
- case TypeCode.Double: return _Double ?? (_Double = new GreaterThanDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.SByte: return _SByteLifted ?? (_SByteLifted = new GreaterThanSByte() { LiftedToNull = true });
- case TypeCode.Byte: return _ByteLifted ?? (_ByteLifted = new GreaterThanByte() { LiftedToNull = true });
- case TypeCode.Char: return _CharLifted ?? (_CharLifted = new GreaterThanChar() { LiftedToNull = true });
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new GreaterThanInt16() { LiftedToNull = true });
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new GreaterThanInt32() { LiftedToNull = true });
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new GreaterThanInt64() { LiftedToNull = true });
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new GreaterThanUInt16() { LiftedToNull = true });
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new GreaterThanUInt32() { LiftedToNull = true });
- case TypeCode.UInt64: return _UInt64Lifted ?? (_UInt64Lifted = new GreaterThanUInt64() { LiftedToNull = true });
- case TypeCode.Single: return _SingleLifted ?? (_SingleLifted = new GreaterThanSingle() { LiftedToNull = true });
- case TypeCode.Double: return _DoubleLifted ?? (_DoubleLifted = new GreaterThanDouble() { LiftedToNull = true });
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "GreaterThan()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/GreaterThanOrEqualInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/GreaterThanOrEqualInstruction.cs
deleted file mode 100644
index fd3f5ecdb17..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/GreaterThanOrEqualInstruction.cs
+++ /dev/null
@@ -1,171 +0,0 @@
-//
-// GreaterThanOrEqualInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- abstract class GreaterThanOrEqualInstruction : ComparisonInstruction {
- private static Instruction _SByte, _Int16, _Char, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double;
- private static Instruction _SByteLifted, _Int16Lifted, _CharLifted, _Int32Lifted, _Int64Lifted, _ByteLifted, _UInt16Lifted, _UInt32Lifted, _UInt64Lifted, _SingleLifted, _DoubleLifted;
-
- private GreaterThanOrEqualInstruction() {
- }
-
- protected override object DoNullComparison (object l, object r)
- {
- return LiftedToNull ? (object) null : (object) false;
- }
-
- internal sealed class GreaterThanOrEqualSByte : GreaterThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (SByte)l >= (SByte)r;
- }
- }
-
- internal sealed class GreaterThanOrEqualInt16 : GreaterThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int16)l >= (Int16)r;
- }
- }
-
- internal sealed class GreaterThanOrEqualChar : GreaterThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Char)l >= (Char)r;
- }
- }
-
- internal sealed class GreaterThanOrEqualInt32 : GreaterThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int32)l >= (Int32)r;
- }
- }
-
- internal sealed class GreaterThanOrEqualInt64 : GreaterThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int64)l >= (Int64)r;
- }
- }
-
- internal sealed class GreaterThanOrEqualByte : GreaterThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Byte)l >= (Byte)r;
- }
- }
-
- internal sealed class GreaterThanOrEqualUInt16 : GreaterThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt16)l >= (UInt16)r;
- }
- }
-
- internal sealed class GreaterThanOrEqualUInt32 : GreaterThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt32)l >= (UInt32)r;
- }
- }
-
- internal sealed class GreaterThanOrEqualUInt64 : GreaterThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt64)l >= (UInt64)r;
- }
- }
-
- internal sealed class GreaterThanOrEqualSingle : GreaterThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Single)l >= (Single)r;
- }
- }
-
- internal sealed class GreaterThanOrEqualDouble : GreaterThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Double)l >= (Double)r;
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.SByte: return _SByte ?? (_SByte = new GreaterThanOrEqualSByte());
- case TypeCode.Byte: return _Byte ?? (_Byte = new GreaterThanOrEqualByte());
- case TypeCode.Char: return _Char ?? (_Char = new GreaterThanOrEqualChar());
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new GreaterThanOrEqualInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new GreaterThanOrEqualInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new GreaterThanOrEqualInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new GreaterThanOrEqualUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new GreaterThanOrEqualUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new GreaterThanOrEqualUInt64());
- case TypeCode.Single: return _Single ?? (_Single = new GreaterThanOrEqualSingle());
- case TypeCode.Double: return _Double ?? (_Double = new GreaterThanOrEqualDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.SByte: return _SByteLifted ?? (_SByteLifted = new GreaterThanOrEqualSByte() { LiftedToNull = true });
- case TypeCode.Byte: return _ByteLifted ?? (_ByteLifted = new GreaterThanOrEqualByte() { LiftedToNull = true });
- case TypeCode.Char: return _CharLifted ?? (_CharLifted = new GreaterThanOrEqualChar() { LiftedToNull = true });
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new GreaterThanOrEqualInt16() { LiftedToNull = true });
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new GreaterThanOrEqualInt32() { LiftedToNull = true });
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new GreaterThanOrEqualInt64() { LiftedToNull = true });
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new GreaterThanOrEqualUInt16() { LiftedToNull = true });
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new GreaterThanOrEqualUInt32() { LiftedToNull = true });
- case TypeCode.UInt64: return _UInt64Lifted ?? (_UInt64Lifted = new GreaterThanOrEqualUInt64() { LiftedToNull = true });
- case TypeCode.Single: return _SingleLifted ?? (_SingleLifted = new GreaterThanOrEqualSingle() { LiftedToNull = true });
- case TypeCode.Double: return _DoubleLifted ?? (_DoubleLifted = new GreaterThanOrEqualDouble() { LiftedToNull = true });
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "GreaterThanOrEqual()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/Instruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/Instruction.cs
deleted file mode 100644
index 6f67063353b..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/Instruction.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- public interface IInstructionProvider {
- void AddInstructions(LightCompiler compiler);
- }
-
- public abstract partial class Instruction {
- public virtual int ConsumedStack { get { return 0; } }
- public virtual int ProducedStack { get { return 0; } }
- public virtual int ConsumedContinuations { get { return 0; } }
- public virtual int ProducedContinuations { get { return 0; } }
-
- public int StackBalance {
- get { return ProducedStack - ConsumedStack; }
- }
-
- public int ContinuationsBalance {
- get { return ProducedContinuations - ConsumedContinuations; }
- }
-
- public abstract int Run(InterpretedFrame frame);
-
- public virtual string InstructionName {
- get { return GetType().Name.Replace("Instruction", ""); }
- }
-
- public override string ToString() {
- return InstructionName + "()";
- }
-
- public virtual string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects) {
- return ToString();
- }
-
- public virtual object GetDebugCookie(LightCompiler compiler) {
- return null;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionFactory.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionFactory.cs
deleted file mode 100644
index 4a1f464a53e..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionFactory.cs
+++ /dev/null
@@ -1,123 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_NUMERICS
-using BigInt = System.Numerics.BigInteger;
-#endif
-
-using System;
-using System.Collections.Generic;
-
-using Microsoft.Scripting.Math;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- public abstract class InstructionFactory {
- // TODO: weak table for types in a collectible assembly?
- private static Dictionary<Type, InstructionFactory> _factories;
-
- internal static InstructionFactory GetFactory(Type type) {
- if (_factories == null) {
- _factories = new Dictionary<Type, InstructionFactory>() {
- { typeof(object), InstructionFactory<object>.Factory },
- { typeof(bool), InstructionFactory<bool>.Factory },
- { typeof(byte), InstructionFactory<byte>.Factory },
- { typeof(sbyte), InstructionFactory<sbyte>.Factory },
- { typeof(short), InstructionFactory<short>.Factory },
- { typeof(ushort), InstructionFactory<ushort>.Factory },
- { typeof(int), InstructionFactory<int>.Factory },
- { typeof(uint), InstructionFactory<uint>.Factory },
- { typeof(long), InstructionFactory<long>.Factory },
- { typeof(ulong), InstructionFactory<ulong>.Factory },
- { typeof(float), InstructionFactory<float>.Factory },
- { typeof(double), InstructionFactory<double>.Factory },
- { typeof(char), InstructionFactory<char>.Factory },
- { typeof(string), InstructionFactory<string>.Factory },
-#if FEATURE_NUMERICS
- { typeof(BigInt), InstructionFactory<BigInt>.Factory },
-#endif
-#if !MONO_INTERPRETER
- { typeof(BigInteger), InstructionFactory<BigInteger>.Factory }
-#endif
- };
- }
-
- lock (_factories) {
- InstructionFactory factory;
- if (!_factories.TryGetValue(type, out factory)) {
- factory = (InstructionFactory)typeof(InstructionFactory<>).MakeGenericType(type).GetDeclaredField("Factory").GetValue(null);
- _factories[type] = factory;
- }
- return factory;
- }
- }
-
- internal protected abstract Instruction GetArrayItem();
- internal protected abstract Instruction SetArrayItem();
- internal protected abstract Instruction TypeIs();
- internal protected abstract Instruction TypeAs();
- internal protected abstract Instruction DefaultValue();
- internal protected abstract Instruction NewArray();
- internal protected abstract Instruction NewArrayInit(int elementCount);
- internal protected abstract Instruction WrapToNullable(Type elementType);
- }
-
- public sealed class InstructionFactory<T> : InstructionFactory {
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
- public static readonly InstructionFactory Factory = new InstructionFactory<T>();
-
- private Instruction _getArrayItem;
- private Instruction _setArrayItem;
- private Instruction _typeIs;
- private Instruction _defaultValue;
- private Instruction _newArray;
- private Instruction _typeAs;
- private Instruction _nullableWrap;
-
- private InstructionFactory() { }
-
- internal protected override Instruction GetArrayItem() {
- return _getArrayItem ?? (_getArrayItem = new GetArrayItemInstruction<T>());
- }
-
- internal protected override Instruction SetArrayItem() {
- return _setArrayItem ?? (_setArrayItem = new SetArrayItemInstruction<T>());
- }
-
- internal protected override Instruction TypeIs() {
- return _typeIs ?? (_typeIs = new TypeIsInstruction<T>());
- }
-
- internal protected override Instruction TypeAs() {
- return _typeAs ?? (_typeAs = new TypeAsInstruction<T>());
- }
-
- internal protected override Instruction DefaultValue() {
- return _defaultValue ?? (_defaultValue = new DefaultValueInstruction<T>());
- }
-
- internal protected override Instruction NewArray() {
- return _newArray ?? (_newArray = new NewArrayInstruction<T>());
- }
-
- internal protected override Instruction NewArrayInit(int elementCount) {
- return new NewArrayInitInstruction<T>(elementCount);
- }
-
- internal protected override Instruction WrapToNullable(Type elementType) {
- return _nullableWrap ?? (_nullableWrap = new WrapToNullableInstruction<T>(elementType));
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionList.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionList.cs
deleted file mode 100644
index d6ebd1ae35f..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionList.cs
+++ /dev/null
@@ -1,1074 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-// Enables instruction counting and displaying stats at process exit.
-// #define STATS
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Security;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
- [DebuggerTypeProxy(typeof(InstructionArray.DebugView))]
- public struct InstructionArray {
- internal readonly int MaxStackDepth;
- internal readonly int MaxContinuationDepth;
- internal readonly Instruction[] Instructions;
- internal readonly object[] Objects;
- internal readonly RuntimeLabel[] Labels;
-
- // list of (instruction index, cookie) sorted by instruction index:
- internal readonly List<KeyValuePair<int, object>> DebugCookies;
-
- internal InstructionArray(int maxStackDepth, int maxContinuationDepth, Instruction[] instructions,
- object[] objects, RuntimeLabel[] labels, List<KeyValuePair<int, object>> debugCookies) {
-
- MaxStackDepth = maxStackDepth;
- MaxContinuationDepth = maxContinuationDepth;
- Instructions = instructions;
- DebugCookies = debugCookies;
- Objects = objects;
- Labels = labels;
- }
-
- internal int Length {
- get { return Instructions.Length; }
- }
-
- #region Debug View
-
- internal sealed class DebugView {
- private readonly InstructionArray _array;
-
- public DebugView(InstructionArray array) {
- _array = array;
-
- }
-
- [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public InstructionList.DebugView.InstructionView[]/*!*/ A0 {
- get {
- return InstructionList.DebugView.GetInstructionViews(
- _array.Instructions,
- _array.Objects,
- (index) => _array.Labels[index].Index,
- _array.DebugCookies
- );
- }
- }
- }
-
- #endregion
- }
-
- [DebuggerTypeProxy(typeof(InstructionList.DebugView))]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
- public sealed class InstructionList {
- private readonly List<Instruction> _instructions = new List<Instruction>();
- private List<object> _objects;
-
- private int _currentStackDepth;
- private int _maxStackDepth;
- private int _currentContinuationsDepth;
- private int _maxContinuationDepth;
- private int _runtimeLabelCount;
- private List<BranchLabel> _labels;
-
- // list of (instruction index, cookie) sorted by instruction index:
- private List<KeyValuePair<int, object>> _debugCookies = null;
-
- #region Debug View
-
- internal sealed class DebugView {
- private readonly InstructionList _list;
-
- public DebugView(InstructionList list) {
- _list = list;
- }
-
- [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public InstructionView[]/*!*/ A0 {
- get {
- return GetInstructionViews(
- _list._instructions,
- _list._objects,
- (index) => _list._labels[index].TargetIndex,
- _list._debugCookies
- );
- }
- }
-
- internal static InstructionView[] GetInstructionViews(IList<Instruction> instructions, IList<object> objects,
- Func<int, int> labelIndexer, IList<KeyValuePair<int, object>> debugCookies) {
-
- var result = new List<InstructionView>();
- int index = 0;
- int stackDepth = 0;
- int continuationsDepth = 0;
-
- var cookieEnumerator = (debugCookies != null ? debugCookies : new KeyValuePair<int, object>[0]).GetEnumerator();
- var hasCookie = cookieEnumerator.MoveNext();
-
- for (int i = 0; i < instructions.Count; i++) {
- object cookie = null;
- while (hasCookie && cookieEnumerator.Current.Key == i) {
- cookie = cookieEnumerator.Current.Value;
- hasCookie = cookieEnumerator.MoveNext();
- }
-
- int stackDiff = instructions[i].StackBalance;
- int contDiff = instructions[i].ContinuationsBalance;
- string name = instructions[i].ToDebugString(i, cookie, labelIndexer, objects);
- result.Add(new InstructionView(instructions[i], name, i, stackDepth, continuationsDepth));
-
- index++;
- stackDepth += stackDiff;
- continuationsDepth += contDiff;
- }
- return result.ToArray();
- }
-
- [DebuggerDisplay("{GetValue(),nq}", Name = "{GetName(),nq}", Type = "{GetDisplayType(), nq}")]
- internal struct InstructionView {
- private readonly int _index;
- private readonly int _stackDepth;
- private readonly int _continuationsDepth;
- private readonly string _name;
- private readonly Instruction _instruction;
-
- internal string GetName() {
- return _index.ToString() +
- (_continuationsDepth == 0 ? "" : " C(" + _continuationsDepth.ToString() + ")") +
- (_stackDepth == 0 ? "" : " S(" + _stackDepth.ToString() + ")");
- }
-
- internal string GetValue() {
- return _name;
- }
-
- internal string GetDisplayType() {
- return _instruction.ContinuationsBalance.ToString() + "/" + _instruction.StackBalance.ToString();
- }
-
- public InstructionView(Instruction instruction, string name, int index, int stackDepth, int continuationsDepth) {
- _instruction = instruction;
- _name = name;
- _index = index;
- _stackDepth = stackDepth;
- _continuationsDepth = continuationsDepth;
- }
- }
- }
-
- #endregion
-
- #region Core Emit Ops
-
- public void Emit(Instruction instruction) {
- _instructions.Add(instruction);
- UpdateStackDepth(instruction);
- }
-
- private void UpdateStackDepth(Instruction instruction) {
- Debug.Assert(instruction.ConsumedStack >= 0 && instruction.ProducedStack >= 0 &&
- instruction.ConsumedContinuations >= 0 && instruction.ProducedContinuations >= 0);
-
- _currentStackDepth -= instruction.ConsumedStack;
- Debug.Assert(_currentStackDepth >= 0);
- _currentStackDepth += instruction.ProducedStack;
- if (_currentStackDepth > _maxStackDepth) {
- _maxStackDepth = _currentStackDepth;
- }
-
- _currentContinuationsDepth -= instruction.ConsumedContinuations;
- Debug.Assert(_currentContinuationsDepth >= 0);
- _currentContinuationsDepth += instruction.ProducedContinuations;
- if (_currentContinuationsDepth > _maxContinuationDepth) {
- _maxContinuationDepth = _currentContinuationsDepth;
- }
- }
-
- /// <summary>
- /// Attaches a cookie to the last emitted instruction.
- /// </summary>
- [Conditional("DEBUG")]
- public void SetDebugCookie(object cookie) {
-#if DEBUG
- if (_debugCookies == null) {
- _debugCookies = new List<KeyValuePair<int, object>>();
- }
-
- Debug.Assert(Count > 0);
- _debugCookies.Add(new KeyValuePair<int, object>(Count - 1, cookie));
-#endif
- }
-
- public int Count {
- get { return _instructions.Count; }
- }
-
- public int CurrentStackDepth {
- get { return _currentStackDepth; }
- }
-
- public int CurrentContinuationsDepth {
- get { return _currentContinuationsDepth; }
- }
-
- public int MaxStackDepth {
- get { return _maxStackDepth; }
- }
-
- internal Instruction GetInstruction(int index) {
- return _instructions[index];
- }
-
-#if STATS
- private static Dictionary<string, int> _executedInstructions = new Dictionary<string, int>();
- private static Dictionary<string, Dictionary<object, bool>> _instances = new Dictionary<string, Dictionary<object, bool>>();
-
- static InstructionList() {
- AppDomain.CurrentDomain.ProcessExit += new EventHandler((_, __) => {
- PerfTrack.DumpHistogram(_executedInstructions);
- Console.WriteLine("-- Total executed: {0}", _executedInstructions.Values.Aggregate(0, (sum, value) => sum + value));
- Console.WriteLine("-----");
-
- var referenced = new Dictionary<string, int>();
- int total = 0;
- foreach (var entry in _instances) {
- referenced[entry.Key] = entry.Value.Count;
- total += entry.Value.Count;
- }
-
- PerfTrack.DumpHistogram(referenced);
- Console.WriteLine("-- Total referenced: {0}", total);
- Console.WriteLine("-----");
- });
- }
-#endif
- public InstructionArray ToArray() {
-#if STATS
- lock (_executedInstructions) {
- _instructions.ForEach((instr) => {
- int value = 0;
- var name = instr.GetType().Name;
- _executedInstructions.TryGetValue(name, out value);
- _executedInstructions[name] = value + 1;
-
- Dictionary<object, bool> dict;
- if (!_instances.TryGetValue(name, out dict)) {
- _instances[name] = dict = new Dictionary<object, bool>();
- }
- dict[instr] = true;
- });
- }
-#endif
- return new InstructionArray(
- _maxStackDepth,
- _maxContinuationDepth,
- _instructions.ToArray(),
- (_objects != null) ? _objects.ToArray() : null,
- BuildRuntimeLabels(),
- _debugCookies
- );
- }
-
- #endregion
-
- #region Stack Operations
-
- private const int PushIntMinCachedValue = -100;
- private const int PushIntMaxCachedValue = 100;
- private const int CachedObjectCount = 256;
-
- private static Instruction _null;
- private static Instruction _true;
- private static Instruction _false;
- private static Instruction[] _ints;
- private static Instruction[] _loadObjectCached;
-
- public void EmitLoad(object value) {
- EmitLoad(value, null);
- }
-
- public void EmitLoad(bool value) {
- if ((bool)value) {
- Emit(_true ?? (_true = new LoadObjectInstruction(value)));
- } else {
- Emit(_false ?? (_false = new LoadObjectInstruction(value)));
- }
- }
-
- public void EmitLoad(object value, Type type) {
- if (value == null) {
- Emit(_null ?? (_null = new LoadObjectInstruction(null)));
- return;
- }
-
- if (type == null || type.IsValueType()) {
- if (value is bool) {
- EmitLoad((bool)value);
- return;
- }
-
- if (value is int) {
- int i = (int)value;
- if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue) {
- if (_ints == null) {
- _ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1];
- }
- i -= PushIntMinCachedValue;
- Emit(_ints[i] ?? (_ints[i] = new LoadObjectInstruction(value)));
- return;
- }
- }
- }
-
- if (_objects == null) {
- _objects = new List<object>();
- if (_loadObjectCached == null) {
- _loadObjectCached = new Instruction[CachedObjectCount];
- }
- }
-
- if (_objects.Count < _loadObjectCached.Length) {
- uint index = (uint)_objects.Count;
- _objects.Add(value);
- Emit(_loadObjectCached[index] ?? (_loadObjectCached[index] = new LoadCachedObjectInstruction(index)));
- } else {
- Emit(new LoadObjectInstruction(value));
- }
- }
-
- public void EmitDup() {
- Emit(DupInstruction.Instance);
- }
-
- public void EmitPop() {
- Emit(PopInstruction.Instance);
- }
-
- public void EmitStore(object value) {
- Emit (new PushValueInstruction (value));
- }
-
- #endregion
-
- #region Locals
-
- internal void SwitchToBoxed(int index, int instructionIndex) {
- var instruction = _instructions[instructionIndex] as IBoxableInstruction;
-
- if (instruction != null) {
- var newInstruction = instruction.BoxIfIndexMatches(index);
- if (newInstruction != null) {
- _instructions[instructionIndex] = newInstruction;
- }
- }
- }
-
- private const int LocalInstrCacheSize = 64;
-
- private static Instruction[] _loadLocal;
- private static Instruction[] _loadLocalBoxed;
- private static Instruction[] _loadLocalFromClosure;
- private static Instruction[] _loadLocalFromClosureBoxed;
- private static Instruction[] _assignLocal;
- private static Instruction[] _storeLocal;
- private static Instruction[] _assignLocalBoxed;
- private static Instruction[] _storeLocalBoxed;
- private static Instruction[] _assignLocalToClosure;
- private static Instruction[] _initReference;
- private static Instruction[] _initImmutableRefBox;
- private static Instruction[] _parameterBox;
- private static Instruction[] _parameter;
-
- public void EmitLoadLocal(int index) {
- if (_loadLocal == null) {
- _loadLocal = new Instruction[LocalInstrCacheSize];
- }
-
- if (index < _loadLocal.Length) {
- Emit(_loadLocal[index] ?? (_loadLocal[index] = new LoadLocalInstruction(index)));
- } else {
- Emit(new LoadLocalInstruction(index));
- }
- }
-
- public void EmitLoadLocalBoxed(int index) {
- Emit(LoadLocalBoxed(index));
- }
-
- internal static Instruction LoadLocalBoxed(int index) {
- if (_loadLocalBoxed == null) {
- _loadLocalBoxed = new Instruction[LocalInstrCacheSize];
- }
-
- if (index < _loadLocalBoxed.Length) {
- return _loadLocalBoxed[index] ?? (_loadLocalBoxed[index] = new LoadLocalBoxedInstruction(index));
- } else {
- return new LoadLocalBoxedInstruction(index);
- }
- }
-
- public void EmitLoadLocalFromClosure(int index) {
- if (_loadLocalFromClosure == null) {
- _loadLocalFromClosure = new Instruction[LocalInstrCacheSize];
- }
-
- if (index < _loadLocalFromClosure.Length) {
- Emit(_loadLocalFromClosure[index] ?? (_loadLocalFromClosure[index] = new LoadLocalFromClosureInstruction(index)));
- } else {
- Emit(new LoadLocalFromClosureInstruction(index));
- }
- }
-
- public void EmitLoadLocalFromClosureBoxed(int index) {
- if (_loadLocalFromClosureBoxed == null) {
- _loadLocalFromClosureBoxed = new Instruction[LocalInstrCacheSize];
- }
-
- if (index < _loadLocalFromClosureBoxed.Length) {
- Emit(_loadLocalFromClosureBoxed[index] ?? (_loadLocalFromClosureBoxed[index] = new LoadLocalFromClosureBoxedInstruction(index)));
- } else {
- Emit(new LoadLocalFromClosureBoxedInstruction(index));
- }
- }
-
- public void EmitAssignLocal(int index) {
- if (_assignLocal == null) {
- _assignLocal = new Instruction[LocalInstrCacheSize];
- }
-
- if (index < _assignLocal.Length) {
- Emit(_assignLocal[index] ?? (_assignLocal[index] = new AssignLocalInstruction(index)));
- } else {
- Emit(new AssignLocalInstruction(index));
- }
- }
-
- public void EmitStoreLocal(int index) {
- if (_storeLocal == null) {
- _storeLocal = new Instruction[LocalInstrCacheSize];
- }
-
- if (index < _storeLocal.Length) {
- Emit(_storeLocal[index] ?? (_storeLocal[index] = new StoreLocalInstruction(index)));
- } else {
- Emit(new StoreLocalInstruction(index));
- }
- }
-
- public void EmitAssignLocalBoxed(int index) {
- Emit(AssignLocalBoxed(index));
- }
-
- internal static Instruction AssignLocalBoxed(int index) {
- if (_assignLocalBoxed == null) {
- _assignLocalBoxed = new Instruction[LocalInstrCacheSize];
- }
-
- if (index < _assignLocalBoxed.Length) {
- return _assignLocalBoxed[index] ?? (_assignLocalBoxed[index] = new AssignLocalBoxedInstruction(index));
- } else {
- return new AssignLocalBoxedInstruction(index);
- }
- }
-
- public void EmitStoreLocalBoxed(int index) {
- Emit(StoreLocalBoxed(index));
- }
-
- internal static Instruction StoreLocalBoxed(int index) {
- if (_storeLocalBoxed == null) {
- _storeLocalBoxed = new Instruction[LocalInstrCacheSize];
- }
-
- if (index < _storeLocalBoxed.Length) {
- return _storeLocalBoxed[index] ?? (_storeLocalBoxed[index] = new StoreLocalBoxedInstruction(index));
- } else {
- return new StoreLocalBoxedInstruction(index);
- }
- }
-
- public void EmitAssignLocalToClosure(int index) {
- if (_assignLocalToClosure == null) {
- _assignLocalToClosure = new Instruction[LocalInstrCacheSize];
- }
-
- if (index < _assignLocalToClosure.Length) {
- Emit(_assignLocalToClosure[index] ?? (_assignLocalToClosure[index] = new AssignLocalToClosureInstruction(index)));
- } else {
- Emit(new AssignLocalToClosureInstruction(index));
- }
- }
-
- public void EmitStoreLocalToClosure(int index) {
- EmitAssignLocalToClosure(index);
- EmitPop();
- }
-
- public void EmitInitializeLocal(int index, Type type) {
- object value = ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(type);
- if (value != null) {
- Emit(new InitializeLocalInstruction.ImmutableValue(index, value));
- } else if (type.IsValueType()) {
- Emit(new InitializeLocalInstruction.MutableValue(index, type));
- } else {
- Emit(InitReference(index));
- }
- }
-
- internal void EmitInitializeParameter(int index) {
- Emit(Parameter(index));
- }
-
- internal static Instruction Parameter(int index) {
- if (_parameter == null) {
- _parameter = new Instruction[LocalInstrCacheSize];
- }
-
- if (index < _parameter.Length) {
- return _parameter[index] ?? (_parameter[index] = new InitializeLocalInstruction.Parameter(index));
- }
-
- return new InitializeLocalInstruction.Parameter(index);
- }
-
- internal static Instruction ParameterBox(int index) {
- if (_parameterBox == null) {
- _parameterBox = new Instruction[LocalInstrCacheSize];
- }
-
- if (index < _parameterBox.Length) {
- return _parameterBox[index] ?? (_parameterBox[index] = new InitializeLocalInstruction.ParameterBox(index));
- }
-
- return new InitializeLocalInstruction.ParameterBox(index);
- }
-
- internal static Instruction InitReference(int index) {
- if (_initReference == null) {
- _initReference = new Instruction[LocalInstrCacheSize];
- }
-
- if (index < _initReference.Length) {
- return _initReference[index] ?? (_initReference[index] = new InitializeLocalInstruction.Reference(index));
- }
-
- return new InitializeLocalInstruction.Reference(index);
- }
-
- internal static Instruction InitImmutableRefBox(int index) {
- if (_initImmutableRefBox == null) {
- _initImmutableRefBox = new Instruction[LocalInstrCacheSize];
- }
-
- if (index < _initImmutableRefBox.Length) {
- return _initImmutableRefBox[index] ?? (_initImmutableRefBox[index] = new InitializeLocalInstruction.ImmutableBox(index, null));
- }
-
- return new InitializeLocalInstruction.ImmutableBox(index, null);
- }
-
- public void EmitNewRuntimeVariables(int count) {
- Emit(new RuntimeVariablesInstruction(count));
- }
-
- #endregion
-
- #region Array Operations
-
- public void EmitGetArrayItem(Type arrayType) {
- Type elementType = arrayType.GetElementType();
- if (elementType.IsClass() || elementType.IsInterface()) {
- Emit(InstructionFactory<object>.Factory.GetArrayItem());
- } else {
- Emit(InstructionFactory.GetFactory(elementType).GetArrayItem());
- }
- }
-
- public void EmitGetArrayLength(Type arrayType) {
- Emit(GetArrayLengthInstruction.Create());
- }
-
- public void EmitSetArrayItem(Type arrayType) {
- Type elementType = arrayType.GetElementType();
- if (elementType.IsClass() || elementType.IsInterface()) {
- Emit(InstructionFactory<object>.Factory.SetArrayItem());
- } else {
- Emit(InstructionFactory.GetFactory(elementType).SetArrayItem());
- }
- }
-
- public void EmitNewArray(Type elementType) {
- Emit(InstructionFactory.GetFactory(elementType).NewArray());
- }
-
- public void EmitNewArrayBounds(Type elementType, int rank) {
- Emit(new NewArrayBoundsInstruction(elementType, rank));
- }
-
- public void EmitNewArrayInit(Type elementType, int elementCount) {
- Emit(InstructionFactory.GetFactory(elementType).NewArrayInit(elementCount));
- }
-
- #endregion
-
- #region Arithmetic Operations
-
- public void EmitAdd(Type type, bool @checked) {
- if (@checked) {
- Emit(AddOvfInstruction.Create(type));
- } else {
- Emit(AddInstruction.Create(type));
- }
- }
-
- public void EmitSub(Type type, bool @checked) {
- if (@checked) {
- Emit(SubOvfInstruction.Create(type));
- } else {
- Emit(SubInstruction.Create(type));
- }
- }
-
- public void EmitMul(Type type, bool @checked) {
- if (@checked) {
- Emit(MulOvfInstruction.Create(type));
- } else {
- Emit(MulInstruction.Create(type));
- }
- }
-
- public void EmitDiv(Type type) {
- Emit(DivInstruction.Create(type));
- }
-
- public void EmitMod(Type type) {
- Emit(ModInstruction.Create(type));
- }
-
- #endregion
-
- public void EmitIncrement (Type type) {
- Emit (new PushValueInstruction (1));
- EmitAdd (type, false);
- }
-
- public void EmitShl(Type type, bool lifted) {
- Emit(lifted ? ShlInstruction.CreateLifted(type) : ShlInstruction.Create(type));
- }
-
- public void EmitShr(Type type, bool lifted) {
- Emit(lifted ? ShrInstruction.CreateLifted(type) : ShrInstruction.Create(type));
- }
-
- public void EmitOr(Type type, bool lifted) {
- Emit(lifted ? OrInstruction.CreateLifted(type) : OrInstruction.Create(type));
- }
-
- public void EmitAnd(Type type, bool lifted) {
- Emit(lifted ? AndInstruction.CreateLifted (type) : AndInstruction.Create(type));
- }
-
- public void EmitExclusiveOr(Type type, bool lifted) {
- Emit(lifted ? XorInstruction.CreateLifted(type) : XorInstruction.Create(type));
- }
-
- #region Comparisons
-
- public void EmitEqual(Type type, bool liftedResult) {
- Emit(liftedResult ?
- EqualInstruction.CreateLifted(TypeUtils.GetNonNullableType (type)) :
- EqualInstruction.Create(TypeUtils.GetNonNullableType (type)));
- }
-
- public void EmitNotEqual(Type type, bool liftedResult) {
- Emit(liftedResult ?
- NotEqualInstruction.CreateLifted(TypeUtils.GetNonNullableType (type)) :
- NotEqualInstruction.Create(TypeUtils.GetNonNullableType (type)));
- }
-
- public void EmitLessThan(Type type, bool liftedResult) {
- Emit(liftedResult ?
- LessThanInstruction.CreateLifted(TypeUtils.GetNonNullableType (type)) :
- LessThanInstruction.Create(TypeUtils.GetNonNullableType (type)));
- }
-
- public void EmitLessThanOrEqual(Type type, bool liftedResult) {
- Emit(liftedResult ?
- LessThanOrEqualInstruction.CreateLifted(TypeUtils.GetNonNullableType (type)) :
- LessThanOrEqualInstruction.Create(TypeUtils.GetNonNullableType (type)));
- }
-
- public void EmitGreaterThan(Type type, bool liftedResult) {
- Emit(liftedResult ?
- GreaterThanInstruction.CreateLifted(TypeUtils.GetNonNullableType (type)) :
- GreaterThanInstruction.Create(TypeUtils.GetNonNullableType (type)));
- }
-
- public void EmitGreaterThanOrEqual(Type type, bool liftedResult) {
- Emit(liftedResult ?
- GreaterThanOrEqualInstruction.CreateLifted(TypeUtils.GetNonNullableType (type)) :
- GreaterThanOrEqualInstruction.Create(TypeUtils.GetNonNullableType (type)));
- }
-
- #endregion
-
- #region Conversions
-
- public void EmitNumericConvertChecked(TypeCode from, TypeCode to) {
- Emit(new NumericConvertInstruction.Checked(from, to));
- }
-
- public void EmitNumericConvertUnchecked(TypeCode from, TypeCode to) {
- Emit(new NumericConvertInstruction.Unchecked(from, to));
- }
-
- #endregion
-
- #region Unary Operators
-
- public void EmitNegate(Type type, bool @checked, bool lifted) {
- if (@checked)
- Emit(lifted ? NegateOvfInstruction.CreateLifted(type) : NegateOvfInstruction.Create(type));
- else
- Emit(lifted ? NegateInstruction.CreateLifted(type) : NegateInstruction.Create(type));
- }
-
- public void EmitNot(Type type, bool lifted) {
- Emit(lifted ? NotInstruction.CreateLifted (type) : NotInstruction.Create(type));
- }
-
- #endregion
-
- #region Nullable operations
-
- public void EmitWrap (Type elementType)
- {
- Emit(InstructionFactory.GetFactory(elementType).WrapToNullable (elementType));
- }
-
- #endregion
-
- #region Types
-
- public void EmitDefaultValue(Type type) {
- Emit(InstructionFactory.GetFactory(type).DefaultValue());
- }
-
- public void EmitNew(ConstructorInfo constructorInfo) {
- Emit(new NewInstruction(constructorInfo));
- }
-
- internal void EmitCreateDelegate(LightDelegateCreator creator) {
- Emit(new CreateDelegateInstruction(creator));
- }
-
- public void EmitTypeEquals() {
- Emit(TypeEqualsInstruction.Instance);
- }
-
- public void EmitTypeIs(Type type) {
- Emit(InstructionFactory.GetFactory(type).TypeIs());
- }
-
- public void EmitTypeAs(Type type) {
- Emit(InstructionFactory.GetFactory(type).TypeAs());
- }
-
- #endregion
-
- #region Fields and Methods
-
- private static readonly Dictionary<FieldInfo, Instruction> _loadFields = new Dictionary<FieldInfo, Instruction>();
-
- public void EmitLoadField(FieldInfo field) {
- Emit(GetLoadField(field));
- }
-
- private Instruction GetLoadField(FieldInfo field) {
- lock (_loadFields) {
- Instruction instruction;
- if (!_loadFields.TryGetValue(field, out instruction)) {
- if (field.IsStatic) {
- instruction = new LoadStaticFieldInstruction(field);
- } else {
- instruction = new LoadFieldInstruction(field);
- }
- _loadFields.Add(field, instruction);
- }
- return instruction;
- }
- }
-
- public void EmitStoreField(FieldInfo field) {
- if (field.IsStatic) {
- Emit(new StoreStaticFieldInstruction(field));
- } else {
- Emit(new StoreFieldInstruction(field));
- }
- }
-
- #endregion
-
- #region Dynamic
-
- public void EmitDynamic(Type type, CallSiteBinder binder) {
- Emit(CreateDynamicInstruction(type, binder));
- }
-
- #region Generated Dynamic InstructionList Factory
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_instructionlist_factory from: generate_dynamic_instructions.py
-
- public void EmitDynamic<T0, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, T2, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, T2, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, T2, T3, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, T2, T3, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, T2, T3, T4, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, T2, T3, T4, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, T2, T3, T4, T5, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TRet>.Factory(binder));
- }
-
- public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TRet>(CallSiteBinder binder) {
- Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TRet>.Factory(binder));
- }
-
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- private static Dictionary<Type, Func<CallSiteBinder, Instruction>> _factories =
- new Dictionary<Type, Func<CallSiteBinder, Instruction>>();
-
- /// <exception cref="SecurityException">Instruction can't be created due to insufficient privileges.</exception>
- internal static Instruction CreateDynamicInstruction(Type delegateType, CallSiteBinder binder) {
- Func<CallSiteBinder, Instruction> factory;
- lock (_factories) {
- if (!_factories.TryGetValue(delegateType, out factory)) {
- if (delegateType.GetMethod("Invoke").ReturnType == typeof(void)) {
- // TODO: We should generally support void returning binders but the only
- // ones that exist are delete index/member who's perf isn't that critical.
- return new DynamicInstructionN(delegateType, CallSite.Create(delegateType, binder), true);
- }
-
- Type instructionType = DynamicInstructionN.GetDynamicInstructionType(delegateType);
- if (instructionType == null) {
- return new DynamicInstructionN(delegateType, CallSite.Create(delegateType, binder));
- }
-
- factory = (Func<CallSiteBinder, Instruction>)instructionType.GetMethod("Factory").CreateDelegate(typeof(Func<CallSiteBinder, Instruction>));
- _factories[delegateType] = factory;
- }
- }
- return factory(binder);
- }
-
- #endregion
-
- #region Control Flow
-
- private static readonly RuntimeLabel[] EmptyRuntimeLabels = new RuntimeLabel[] { new RuntimeLabel(Interpreter.RethrowOnReturn, 0, 0) };
-
- private RuntimeLabel[] BuildRuntimeLabels() {
- if (_runtimeLabelCount == 0) {
- return EmptyRuntimeLabels;
- }
-
- var result = new RuntimeLabel[_runtimeLabelCount + 1];
- foreach (BranchLabel label in _labels) {
- if (label.HasRuntimeLabel) {
- result[label.LabelIndex] = label.ToRuntimeLabel();
- }
- }
- // "return and rethrow" label:
- result[result.Length - 1] = new RuntimeLabel(Interpreter.RethrowOnReturn, 0, 0);
- return result;
- }
-
- public BranchLabel MakeLabel() {
- if (_labels == null) {
- _labels = new List<BranchLabel>();
- }
-
- var label = new BranchLabel();
- _labels.Add(label);
- return label;
- }
-
- internal void FixupBranch(int branchIndex, int offset) {
- _instructions[branchIndex] = ((OffsetInstruction)_instructions[branchIndex]).Fixup(offset);
- }
-
- private int EnsureLabelIndex(BranchLabel label) {
- if (label.HasRuntimeLabel) {
- return label.LabelIndex;
- }
-
- label.LabelIndex = _runtimeLabelCount;
- _runtimeLabelCount++;
- return label.LabelIndex;
- }
-
- public int MarkRuntimeLabel() {
- BranchLabel handlerLabel = MakeLabel();
- MarkLabel(handlerLabel);
- return EnsureLabelIndex(handlerLabel);
- }
-
- public void MarkLabel(BranchLabel label) {
- label.Mark(this);
- }
-
- public void EmitGoto(BranchLabel label, bool hasResult, bool hasValue) {
- Emit(GotoInstruction.Create(EnsureLabelIndex(label), hasResult, hasValue));
- }
-
- private void EmitBranch(OffsetInstruction instruction, BranchLabel label) {
- Emit(instruction);
- label.AddBranch(this, Count - 1);
- }
-
- public void EmitBranch(BranchLabel label) {
- EmitBranch(new BranchInstruction(), label);
- }
-
- public void EmitBranch(BranchLabel label, bool hasResult, bool hasValue) {
- EmitBranch(new BranchInstruction(hasResult, hasValue), label);
- }
-
- public void EmitCoalescingBranch(BranchLabel leftNotNull) {
- EmitBranch(new CoalescingBranchInstruction(), leftNotNull);
- }
-
- public void EmitBranchTrue(BranchLabel elseLabel) {
- EmitBranch(new BranchTrueInstruction(), elseLabel);
- }
-
- public void EmitBranchFalse(BranchLabel elseLabel) {
- EmitBranch(new BranchFalseInstruction(), elseLabel);
- }
-
- public void EmitBranchNull(BranchLabel elseLabel) {
- EmitBranch(new BranchNullInstruction(), elseLabel);
- }
-
- public void EmitThrow() {
- Emit(ThrowInstruction.Throw);
- }
-
- public void EmitThrowVoid() {
- Emit(ThrowInstruction.VoidThrow);
- }
-
- public void EmitRethrow() {
- Emit(ThrowInstruction.Rethrow);
- }
-
- public void EmitRethrowVoid() {
- Emit(ThrowInstruction.VoidRethrow);
- }
-
- public void EmitEnterTryFinally(BranchLabel finallyStartLabel) {
- Emit(EnterTryFinallyInstruction.Create(EnsureLabelIndex(finallyStartLabel)));
- }
-
- public void EmitEnterFinally() {
- Emit(EnterFinallyInstruction.Instance);
- }
-
- public void EmitLeaveFinally() {
- Emit(LeaveFinallyInstruction.Instance);
- }
-
- public void EmitLeaveFault(bool hasValue) {
- Emit(hasValue ? LeaveFaultInstruction.NonVoid : LeaveFaultInstruction.Void);
- }
-
- public void EmitEnterExceptionHandlerNonVoid() {
- Emit(EnterExceptionHandlerInstruction.NonVoid);
- }
-
- public void EmitEnterExceptionHandlerVoid() {
- Emit(EnterExceptionHandlerInstruction.Void);
- }
-
- public void EmitLeaveExceptionHandler(bool hasValue, BranchLabel tryExpressionEndLabel) {
- Emit(LeaveExceptionHandlerInstruction.Create(EnsureLabelIndex(tryExpressionEndLabel), hasValue));
- }
-
- public void EmitSwitch(Dictionary<int, int> cases) {
- Emit(new SwitchInstruction(cases));
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LabelInfo.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LabelInfo.cs
deleted file mode 100644
index 2517a85baf1..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LabelInfo.cs
+++ /dev/null
@@ -1,309 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-#if FEATURE_REFEMIT
-using System.Reflection.Emit;
-#endif
-using System.Text;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
-
- /// <summary>
- /// Contains compiler state corresponding to a LabelTarget
- /// See also LabelScopeInfo.
- /// </summary>
- internal sealed class LabelInfo {
- // The tree node representing this label
- private readonly LabelTarget _node;
-
- // The BranchLabel label, will be mutated if Node is redefined
- private BranchLabel _label;
-
- // The blocks where this label is defined. If it has more than one item,
- // the blocks can't be jumped to except from a child block
- // If there's only 1 block (the common case) it's stored here, if there's multiple blocks it's stored
- // as a HashSet<LabelScopeInfo>
- private object _definitions;
-
- // Blocks that jump to this block
- private readonly List<LabelScopeInfo> _references = new List<LabelScopeInfo>();
-
- // True if at least one jump is across blocks
- // If we have any jump across blocks to this label, then the
- // LabelTarget can only be defined in one place
- private bool _acrossBlockJump;
-
- internal LabelInfo(LabelTarget node) {
- _node = node;
- }
-
- internal BranchLabel GetLabel(LightCompiler compiler) {
- EnsureLabel(compiler);
- return _label;
- }
-
- internal void Reference(LabelScopeInfo block) {
- _references.Add(block);
- if (HasDefinitions) {
- ValidateJump(block);
- }
- }
-
- internal void Define(LabelScopeInfo block) {
- // Prevent the label from being shadowed, which enforces cleaner
- // trees. Also we depend on this for simplicity (keeping only one
- // active IL Label per LabelInfo)
- for (LabelScopeInfo j = block; j != null; j = j.Parent) {
- if (j.ContainsTarget(_node)) {
- throw new InvalidOperationException(String.Format("Label target already defined: {0}", _node.Name));
- }
- }
-
- AddDefinition(block);
- block.AddLabelInfo(_node, this);
-
- // Once defined, validate all jumps
- if (HasDefinitions && !HasMultipleDefinitions) {
- foreach (var r in _references) {
- ValidateJump(r);
- }
- } else {
- // Was just redefined, if we had any across block jumps, they're
- // now invalid
- if (_acrossBlockJump) {
- throw new InvalidOperationException("Ambiguous jump");
- }
- // For local jumps, we need a new IL label
- // This is okay because:
- // 1. no across block jumps have been made or will be made
- // 2. we don't allow the label to be shadowed
- _label = null;
- }
- }
-
- private void ValidateJump(LabelScopeInfo reference) {
- // look for a simple jump out
- for (LabelScopeInfo j = reference; j != null; j = j.Parent) {
- if (DefinedIn(j)) {
- // found it, jump is valid!
- return;
- }
- if (j.Kind == LabelScopeKind.Filter) {
- break;
- }
- }
-
- _acrossBlockJump = true;
-
- if (HasMultipleDefinitions) {
- throw new InvalidOperationException(String.Format("Ambiguous jump {0}", _node.Name));
- }
-
- // We didn't find an outward jump. Look for a jump across blocks
- LabelScopeInfo def = FirstDefinition();
- LabelScopeInfo common = CommonNode(def, reference, b => b.Parent);
-
- // Validate that we aren't jumping across a finally
- for (LabelScopeInfo j = reference; j != common; j = j.Parent) {
- if (j.Kind == LabelScopeKind.Filter) {
- throw new InvalidOperationException("Control cannot leave filter test");
- }
- }
-
- // Valdiate that we aren't jumping into a catch or an expression
- for (LabelScopeInfo j = def; j != common; j = j.Parent) {
- if (!j.CanJumpInto) {
- if (j.Kind == LabelScopeKind.Expression) {
- throw new InvalidOperationException("Control cannot enter an expression");
- } else {
- throw new InvalidOperationException("Control cannot enter try");
- }
- }
- }
- }
-
- internal void ValidateFinish() {
- // Make sure that if this label was jumped to, it is also defined
- if (_references.Count > 0 && !HasDefinitions) {
- throw new InvalidOperationException("label target undefined");
- }
- }
-
- private void EnsureLabel(LightCompiler compiler) {
- if (_label == null) {
- _label = compiler.Instructions.MakeLabel();
- }
- }
-
- private bool DefinedIn(LabelScopeInfo scope) {
- if (_definitions == scope) {
- return true;
- }
-
- HashSet<LabelScopeInfo> definitions = _definitions as HashSet<LabelScopeInfo>;
- if (definitions != null) {
- return definitions.Contains(scope);
- }
- return false;
- }
-
- private bool HasDefinitions {
- get {
- return _definitions != null;
- }
- }
-
- private LabelScopeInfo FirstDefinition() {
- LabelScopeInfo scope = _definitions as LabelScopeInfo;
- if (scope != null) {
- return scope;
- }
- return ((HashSet<LabelScopeInfo>)_definitions).First();
- }
-
- private void AddDefinition(LabelScopeInfo scope) {
- if (_definitions == null) {
- _definitions = scope;
- } else {
- HashSet<LabelScopeInfo> set = _definitions as HashSet<LabelScopeInfo>;
- if(set == null) {
- _definitions = set = new HashSet<LabelScopeInfo>() { (LabelScopeInfo)_definitions };
- }
- set.Add(scope);
- }
- }
-
- private bool HasMultipleDefinitions {
- get {
- return _definitions is HashSet<LabelScopeInfo>;
- }
- }
-
- internal static T CommonNode<T>(T first, T second, Func<T, T> parent) where T : class {
- var cmp = EqualityComparer<T>.Default;
- if (cmp.Equals(first, second)) {
- return first;
- }
- var set = new HashSet<T>(cmp);
- for (T t = first; t != null; t = parent(t)) {
- set.Add(t);
- }
- for (T t = second; t != null; t = parent(t)) {
- if (set.Contains(t)) {
- return t;
- }
- }
- return null;
- }
- }
-
- public enum LabelScopeKind {
- // any "statement like" node that can be jumped into
- Statement,
-
- // these correspond to the node of the same name
- Block,
- Switch,
- Lambda,
- Try,
-
- // these correspond to the part of the try block we're in
- Catch,
- Finally,
- Filter,
-
- // the catch-all value for any other expression type
- // (means we can't jump into it)
- Expression,
- }
-
- //
- // Tracks scoping information for LabelTargets. Logically corresponds to a
- // "label scope". Even though we have arbitrary goto support, we still need
- // to track what kinds of nodes that gotos are jumping through, both to
- // emit property IL ("leave" out of a try block), and for validation, and
- // to allow labels to be duplicated in the tree, as long as the jumps are
- // considered "up only" jumps.
- //
- // We create one of these for every Expression that can be jumped into, as
- // well as creating them for the first expression we can't jump into. The
- // "Kind" property indicates what kind of scope this is.
- //
- internal sealed class LabelScopeInfo {
- private HybridReferenceDictionary<LabelTarget, LabelInfo> Labels; // lazily allocated, we typically use this only once every 6th-7th block
- internal readonly LabelScopeKind Kind;
- internal readonly LabelScopeInfo Parent;
-
- internal LabelScopeInfo(LabelScopeInfo parent, LabelScopeKind kind) {
- Parent = parent;
- Kind = kind;
- }
-
- /// <summary>
- /// Returns true if we can jump into this node
- /// </summary>
- internal bool CanJumpInto {
- get {
- switch (Kind) {
- case LabelScopeKind.Block:
- case LabelScopeKind.Statement:
- case LabelScopeKind.Switch:
- case LabelScopeKind.Lambda:
- return true;
- }
- return false;
- }
- }
-
-
- internal bool ContainsTarget(LabelTarget target) {
- if (Labels == null) {
- return false;
- }
-
- return Labels.ContainsKey(target);
- }
-
- internal bool TryGetLabelInfo(LabelTarget target, out LabelInfo info) {
- if (Labels == null) {
- info = null;
- return false;
- }
-
- return Labels.TryGetValue(target, out info);
- }
-
- internal void AddLabelInfo(LabelTarget target, LabelInfo info) {
- Debug.Assert(CanJumpInto);
-
- if (Labels == null) {
- Labels = new HybridReferenceDictionary<LabelTarget, LabelInfo>();
- }
-
- Labels[target] = info;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LessThanInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LessThanInstruction.cs
deleted file mode 100644
index 586deb8bd23..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LessThanInstruction.cs
+++ /dev/null
@@ -1,171 +0,0 @@
-//
-// LessThanInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- abstract class LessThanInstruction : ComparisonInstruction {
- private static Instruction _SByte, _Int16, _Char, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double;
- private static Instruction _SByteLifted, _Int16Lifted, _CharLifted, _Int32Lifted, _Int64Lifted, _ByteLifted, _UInt16Lifted, _UInt32Lifted, _UInt64Lifted, _SingleLifted, _DoubleLifted;
-
- private LessThanInstruction() {
- }
-
- protected override object DoNullComparison (object l, object r)
- {
- return LiftedToNull ? (object) null : (object) false;
- }
-
- internal sealed class LessThanSByte : LessThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (SByte)l < (SByte)r;
- }
- }
-
- internal sealed class LessThanInt16 : LessThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int16)l < (Int16)r;
- }
- }
-
- internal sealed class LessThanChar : LessThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Char)l < (Char)r;
- }
- }
-
- internal sealed class LessThanInt32 : LessThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int32)l < (Int32)r;
- }
- }
-
- internal sealed class LessThanInt64 : LessThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int64)l < (Int64)r;
- }
- }
-
- internal sealed class LessThanByte : LessThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Byte)l < (Byte)r;
- }
- }
-
- internal sealed class LessThanUInt16 : LessThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt16)l < (UInt16)r;
- }
- }
-
- internal sealed class LessThanUInt32 : LessThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt32)l < (UInt32)r;
- }
- }
-
- internal sealed class LessThanUInt64 : LessThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt64)l < (UInt64)r;
- }
- }
-
- internal sealed class LessThanSingle : LessThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Single)l < (Single)r;
- }
- }
-
- internal sealed class LessThanDouble : LessThanInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Double)l < (Double)r;
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.SByte: return _SByte ?? (_SByte = new LessThanSByte());
- case TypeCode.Byte: return _Byte ?? (_Byte = new LessThanByte());
- case TypeCode.Char: return _Char ?? (_Char = new LessThanChar());
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new LessThanInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new LessThanInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new LessThanInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new LessThanUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new LessThanUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new LessThanUInt64());
- case TypeCode.Single: return _Single ?? (_Single = new LessThanSingle());
- case TypeCode.Double: return _Double ?? (_Double = new LessThanDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.SByte: return _SByteLifted ?? (_SByteLifted = new LessThanSByte() { LiftedToNull = true });
- case TypeCode.Byte: return _ByteLifted ?? (_ByteLifted = new LessThanByte() { LiftedToNull = true });
- case TypeCode.Char: return _CharLifted ?? (_CharLifted = new LessThanChar() { LiftedToNull = true });
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new LessThanInt16() { LiftedToNull = true });
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new LessThanInt32() { LiftedToNull = true });
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new LessThanInt64() { LiftedToNull = true });
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new LessThanUInt16() { LiftedToNull = true });
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new LessThanUInt32() { LiftedToNull = true });
- case TypeCode.UInt64: return _UInt64Lifted ?? (_UInt64Lifted = new LessThanUInt64() { LiftedToNull = true });
- case TypeCode.Single: return _SingleLifted ?? (_SingleLifted = new LessThanSingle() { LiftedToNull = true });
- case TypeCode.Double: return _DoubleLifted ?? (_DoubleLifted = new LessThanDouble() { LiftedToNull = true });
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "LessThan()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LessThanOrEqualInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LessThanOrEqualInstruction.cs
deleted file mode 100644
index a441ee52a2b..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LessThanOrEqualInstruction.cs
+++ /dev/null
@@ -1,171 +0,0 @@
-//
-// LessThanOrEqualInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- abstract class LessThanOrEqualInstruction : ComparisonInstruction {
- private static Instruction _SByte, _Int16, _Char, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double;
- private static Instruction _SByteLifted, _Int16Lifted, _CharLifted, _Int32Lifted, _Int64Lifted, _ByteLifted, _UInt16Lifted, _UInt32Lifted, _UInt64Lifted, _SingleLifted, _DoubleLifted;
-
- private LessThanOrEqualInstruction() {
- }
-
- protected override object DoNullComparison (object l, object r)
- {
- return LiftedToNull ? (object) null : (object) false;
- }
-
- internal sealed class LessThanOrEqualSByte : LessThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (SByte)l <= (SByte)r;
- }
- }
-
- internal sealed class LessThanOrEqualInt16 : LessThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int16)l <= (Int16)r;
- }
- }
-
- internal sealed class LessThanOrEqualChar : LessThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Char)l <= (Char)r;
- }
- }
-
- internal sealed class LessThanOrEqualInt32 : LessThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int32)l <= (Int32)r;
- }
- }
-
- internal sealed class LessThanOrEqualInt64 : LessThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int64)l <= (Int64)r;
- }
- }
-
- internal sealed class LessThanOrEqualByte : LessThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Byte)l <= (Byte)r;
- }
- }
-
- internal sealed class LessThanOrEqualUInt16 : LessThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt16)l <= (UInt16)r;
- }
- }
-
- internal sealed class LessThanOrEqualUInt32 : LessThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt32)l <= (UInt32)r;
- }
- }
-
- internal sealed class LessThanOrEqualUInt64 : LessThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt64)l <= (UInt64)r;
- }
- }
-
- internal sealed class LessThanOrEqualSingle : LessThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Single)l <= (Single)r;
- }
- }
-
- internal sealed class LessThanOrEqualDouble : LessThanOrEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Double)l <= (Double)r;
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.SByte: return _SByte ?? (_SByte = new LessThanOrEqualSByte());
- case TypeCode.Byte: return _Byte ?? (_Byte = new LessThanOrEqualByte());
- case TypeCode.Char: return _Char ?? (_Char = new LessThanOrEqualChar());
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new LessThanOrEqualInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new LessThanOrEqualInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new LessThanOrEqualInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new LessThanOrEqualUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new LessThanOrEqualUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new LessThanOrEqualUInt64());
- case TypeCode.Single: return _Single ?? (_Single = new LessThanOrEqualSingle());
- case TypeCode.Double: return _Double ?? (_Double = new LessThanOrEqualDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.SByte: return _SByteLifted ?? (_SByteLifted = new LessThanOrEqualSByte() { LiftedToNull = true });
- case TypeCode.Byte: return _ByteLifted ?? (_ByteLifted = new LessThanOrEqualByte() { LiftedToNull = true });
- case TypeCode.Char: return _CharLifted ?? (_CharLifted = new LessThanOrEqualChar() { LiftedToNull = true });
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new LessThanOrEqualInt16() { LiftedToNull = true });
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new LessThanOrEqualInt32() { LiftedToNull = true });
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new LessThanOrEqualInt64() { LiftedToNull = true });
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new LessThanOrEqualUInt16() { LiftedToNull = true });
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new LessThanOrEqualUInt32() { LiftedToNull = true });
- case TypeCode.UInt64: return _UInt64Lifted ?? (_UInt64Lifted = new LessThanOrEqualUInt64() { LiftedToNull = true });
- case TypeCode.Single: return _SingleLifted ?? (_SingleLifted = new LessThanOrEqualSingle() { LiftedToNull = true });
- case TypeCode.Double: return _DoubleLifted ?? (_DoubleLifted = new LessThanOrEqualDouble() { LiftedToNull = true });
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "LessThanOrEqual()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LocalAccess.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LocalAccess.cs
deleted file mode 100644
index bc0709553d1..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LocalAccess.cs
+++ /dev/null
@@ -1,374 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Runtime;
-using System.Collections.Generic;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal interface IBoxableInstruction {
- Instruction BoxIfIndexMatches(int index);
- }
-
- internal abstract class LocalAccessInstruction : Instruction {
- internal readonly int _index;
-
- protected LocalAccessInstruction(int index) {
- _index = index;
- }
-
- public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects) {
- return cookie == null ?
- InstructionName + "(" + _index + ")" :
- InstructionName + "(" + cookie + ": " + _index + ")";
- }
- }
-
- #region Load
-
- internal sealed class LoadLocalInstruction : LocalAccessInstruction, IBoxableInstruction {
- internal LoadLocalInstruction(int index)
- : base(index) {
- }
-
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex++] = frame.Data[_index];
- //frame.Push(frame.Data[_index]);
- return +1;
- }
-
- public Instruction BoxIfIndexMatches(int index) {
- return (index == _index) ? InstructionList.LoadLocalBoxed(index) : null;
- }
- }
-
- internal sealed class LoadLocalBoxedInstruction : LocalAccessInstruction {
- internal LoadLocalBoxedInstruction(int index)
- : base(index) {
- }
-
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- var box = (StrongBox<object>)frame.Data[_index];
- frame.Data[frame.StackIndex++] = box.Value;
- return +1;
- }
- }
-
- internal sealed class LoadLocalFromClosureInstruction : LocalAccessInstruction {
- internal LoadLocalFromClosureInstruction(int index)
- : base(index) {
- }
-
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- var box = frame.Closure[_index];
- frame.Data[frame.StackIndex++] = box.Value;
- return +1;
- }
- }
-
- internal sealed class LoadLocalFromClosureBoxedInstruction : LocalAccessInstruction {
- internal LoadLocalFromClosureBoxedInstruction(int index)
- : base(index) {
- }
-
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- var box = frame.Closure[_index];
- frame.Data[frame.StackIndex++] = box;
- return +1;
- }
- }
-
- #endregion
-
- #region Store, Assign
-
- internal sealed class AssignLocalInstruction : LocalAccessInstruction, IBoxableInstruction {
- internal AssignLocalInstruction(int index)
- : base(index) {
- }
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[_index] = frame.Peek();
- return +1;
- }
-
- public Instruction BoxIfIndexMatches(int index) {
- return (index == _index) ? InstructionList.AssignLocalBoxed(index) : null;
- }
- }
-
- internal sealed class StoreLocalInstruction : LocalAccessInstruction, IBoxableInstruction {
- internal StoreLocalInstruction(int index)
- : base(index) {
- }
-
- public override int ConsumedStack { get { return 1; } }
- public override int Run(InterpretedFrame frame) {
- frame.Data[_index] = frame.Data[--frame.StackIndex];
- //frame.Data[_index] = frame.Pop();
- return +1;
- }
-
- public Instruction BoxIfIndexMatches(int index) {
- return (index == _index) ? InstructionList.StoreLocalBoxed(index) : null;
- }
- }
-
- internal sealed class AssignLocalBoxedInstruction : LocalAccessInstruction {
- internal AssignLocalBoxedInstruction(int index)
- : base(index) {
- }
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- var box = (StrongBox<object>)frame.Data[_index];
- box.Value = frame.Peek();
- return +1;
- }
- }
-
- internal sealed class StoreLocalBoxedInstruction : LocalAccessInstruction {
- internal StoreLocalBoxedInstruction(int index)
- : base(index) {
- }
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 0; } }
-
- public override int Run(InterpretedFrame frame) {
- var box = (StrongBox<object>)frame.Data[_index];
- box.Value = frame.Data[--frame.StackIndex];
- return +1;
- }
- }
-
- internal sealed class AssignLocalToClosureInstruction : LocalAccessInstruction {
- internal AssignLocalToClosureInstruction(int index)
- : base(index) {
- }
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- var box = frame.Closure[_index];
- box.Value = frame.Peek();
- return +1;
- }
- }
-
- #endregion
-
- #region Initialize
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors")]
- internal abstract class InitializeLocalInstruction : LocalAccessInstruction {
- internal InitializeLocalInstruction(int index)
- : base(index) {
- }
-
- internal sealed class Reference : InitializeLocalInstruction, IBoxableInstruction {
- internal Reference(int index)
- : base(index) {
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[_index] = null;
- return 1;
- }
-
- public Instruction BoxIfIndexMatches(int index) {
- return (index == _index) ? InstructionList.InitImmutableRefBox(index) : null;
- }
-
- public override string InstructionName {
- get { return "InitRef"; }
- }
- }
-
- internal sealed class ImmutableValue : InitializeLocalInstruction, IBoxableInstruction {
- private readonly object _defaultValue;
-
- internal ImmutableValue(int index, object defaultValue)
- : base(index) {
- _defaultValue = defaultValue;
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[_index] = _defaultValue;
- return 1;
- }
-
- public Instruction BoxIfIndexMatches(int index) {
- return (index == _index) ? new ImmutableBox(index, _defaultValue) : null;
- }
-
- public override string InstructionName {
- get { return "InitImmutableValue"; }
- }
- }
-
- internal sealed class ImmutableBox : InitializeLocalInstruction {
- // immutable value:
- private readonly object _defaultValue;
-
- internal ImmutableBox(int index, object defaultValue)
- : base(index) {
- _defaultValue = defaultValue;
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[_index] = new StrongBox<object>(_defaultValue);
- return 1;
- }
-
- public override string InstructionName {
- get { return "InitImmutableBox"; }
- }
- }
-
- internal sealed class ParameterBox : InitializeLocalInstruction {
- public ParameterBox(int index)
- : base(index) {
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[_index] = new StrongBox<object>(frame.Data[_index]);
- return 1;
- }
-
- }
-
- internal sealed class Parameter : InitializeLocalInstruction, IBoxableInstruction {
- internal Parameter(int index)
- : base(index) {
- }
-
- public override int Run(InterpretedFrame frame) {
- // nop
- return 1;
- }
-
- public Instruction BoxIfIndexMatches(int index) {
- if (index == _index) {
- return InstructionList.ParameterBox(index);
- }
- return null;
- }
-
- public override string InstructionName {
- get { return "InitParameter"; }
- }
- }
-
- internal sealed class MutableValue : InitializeLocalInstruction, IBoxableInstruction {
- private readonly Type _type;
-
- internal MutableValue(int index, Type type)
- : base(index) {
- _type = type;
- }
-
- public override int Run(InterpretedFrame frame) {
- try {
- frame.Data[_index] = Activator.CreateInstance(_type);
- } catch (TargetInvocationException e) {
- ExceptionHelpers.UpdateForRethrow(e.InnerException);
- throw e.InnerException;
- }
-
- return 1;
- }
-
- public Instruction BoxIfIndexMatches(int index) {
- return (index == _index) ? new MutableBox(index, _type) : null;
- }
-
- public override string InstructionName {
- get { return "InitMutableValue"; }
- }
- }
-
- internal sealed class MutableBox : InitializeLocalInstruction {
- private readonly Type _type;
-
- internal MutableBox(int index, Type type)
- : base(index) {
- _type = type;
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[_index] = new StrongBox<object>(Activator.CreateInstance(_type));
- return 1;
- }
-
- public override string InstructionName {
- get { return "InitMutableBox"; }
- }
- }
- }
-
- #endregion
-
- #region RuntimeVariables
-
- internal sealed class RuntimeVariablesInstruction : Instruction {
- private readonly int _count;
-
- public RuntimeVariablesInstruction(int count) {
- _count = count;
- }
-
- public override int ProducedStack { get { return 1; } }
- public override int ConsumedStack { get { return _count; } }
-
- public override int Run(InterpretedFrame frame) {
- var ret = new IStrongBox[_count];
- for (int i = ret.Length - 1; i >= 0; i--) {
- ret[i] = (IStrongBox)frame.Pop();
- }
- frame.Push(RuntimeVariables.Create(ret));
- return +1;
- }
-
- public override string ToString() {
- return "GetRuntimeVariables()";
- }
- }
-
- #endregion
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ModInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ModInstruction.cs
deleted file mode 100644
index c8ff766e5e1..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ModInstruction.cs
+++ /dev/null
@@ -1,118 +0,0 @@
-//
-// ModInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class ModInstruction : ArithmeticInstruction {
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double;
-
- private ModInstruction() {
- }
-
- internal sealed class ModInt32 : ModInstruction {
- protected override object Calculate (object l, object r)
- {
- return ScriptingRuntimeHelpers.Int32ToObject(unchecked((Int32)l % (Int32)r));
- }
- }
-
- internal sealed class ModInt16 : ModInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int16)unchecked((Int16)l % (Int16)r);
- }
- }
-
- internal sealed class ModInt64 : ModInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64)unchecked((Int64)l % (Int64)r);
- }
- }
-
- internal sealed class ModUInt16 : ModInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt16)unchecked((UInt16)l % (UInt16)r);
- }
- }
-
- internal sealed class ModUInt32 : ModInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32)unchecked((UInt32)l % (UInt32)r);
- }
- }
-
- internal sealed class ModUInt64 : ModInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64)unchecked((UInt64)l % (UInt64)r);
- }
- }
-
- internal sealed class ModSingle : ModInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Single)((Single)l % (Single)r);
- }
- }
-
- internal sealed class ModDouble : ModInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Double)l % (Double)r;
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new ModInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new ModInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new ModInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new ModUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new ModUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new ModUInt64());
- case TypeCode.Single: return _Single ?? (_Single = new ModSingle());
- case TypeCode.Double: return _Double ?? (_Double = new ModDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "Mod()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/MulInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/MulInstruction.cs
deleted file mode 100644
index 48ef3518bb2..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/MulInstruction.cs
+++ /dev/null
@@ -1,204 +0,0 @@
-//
-// MulInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class MulInstruction : ArithmeticInstruction {
-
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double;
-
- private MulInstruction() {
- }
-
- internal sealed class MulInt32 : MulInstruction {
- protected override object Calculate (object l, object r)
- {
- return ScriptingRuntimeHelpers.Int32ToObject(unchecked((Int32)l * (Int32)r));
- }
- }
-
- internal sealed class MulInt16 : MulInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int16)unchecked((Int16)l * (Int16)r);
- }
- }
-
- internal sealed class MulInt64 : MulInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64)unchecked((Int64)l * (Int64)r);
- }
- }
-
- internal sealed class MulUInt16 : MulInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt16)unchecked((UInt16)l * (UInt16)r);
- }
- }
-
- internal sealed class MulUInt32 : MulInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32)unchecked((UInt32)l * (UInt32)r);
- }
- }
-
- internal sealed class MulUInt64 : MulInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64)unchecked((UInt64)l * (UInt64)r);
- }
- }
-
- internal sealed class MulSingle : MulInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Single)((Single)l * (Single)r);
- }
- }
-
- internal sealed class MulDouble : MulInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Double)l * (Double)r;
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new MulInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new MulInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new MulInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new MulUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new MulUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new MulUInt64());
- case TypeCode.Single: return _Single ?? (_Single = new MulSingle());
- case TypeCode.Double: return _Double ?? (_Double = new MulDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "Mul()";
- }
- }
-
- internal abstract class MulOvfInstruction : ArithmeticInstruction {
-
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double;
-
- private MulOvfInstruction() {
- }
-
- internal sealed class MulOvfInt32 : MulOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return ScriptingRuntimeHelpers.Int32ToObject(checked((Int32)l * (Int32)r));
- }
- }
-
- internal sealed class MulOvfInt16 : MulOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((Int16)((Int16)l * (Int16)r));
- }
- }
-
- internal sealed class MulOvfInt64 : MulOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((Int64)((Int64)l * (Int64)r));
- }
- }
-
- internal sealed class MulOvfUInt16 : MulOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((UInt16)((UInt16)l * (UInt16)r));
- }
- }
-
- internal sealed class MulOvfUInt32 : MulOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((UInt32)((UInt32)l * (UInt32)r));
- }
- }
-
- internal sealed class MulOvfUInt64 : MulOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((UInt64)((UInt64)l * (UInt64)r));
- }
- }
-
- internal sealed class MulOvfSingle : MulOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Single)((Single)l * (Single)r);
- }
- }
-
- internal sealed class MulOvfDouble : MulOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Double)l * (Double)r;
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new MulOvfInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new MulOvfInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new MulOvfInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new MulOvfUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new MulOvfUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new MulOvfUInt64());
- case TypeCode.Single: return _Single ?? (_Single = new MulOvfSingle());
- case TypeCode.Double: return _Double ?? (_Double = new MulOvfDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "MulOvf()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NegateInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NegateInstruction.cs
deleted file mode 100644
index 5652f5bc78b..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NegateInstruction.cs
+++ /dev/null
@@ -1,368 +0,0 @@
-//
-// NegateInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class NegateInstruction : Instruction {
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _Single, _Double;
- private static Instruction _Int16Lifted, _Int32Lifted, _Int64Lifted, _UInt16Lifted, _UInt32Lifted, _SingleLifted, _DoubleLifted;
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- private NegateInstruction() {
- }
-
- internal sealed class NegateInt32 : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = ScriptingRuntimeHelpers.Int32ToObject(unchecked(-(Int32)v));
- return 1;
- }
- }
-
- internal sealed class NegateInt16 : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int16)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Int16)unchecked(-v);
- return 1;
- }
- }
-
- internal sealed class NegateInt64 : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int64)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Int64)unchecked(-v);
- return 1;
- }
- }
-
- internal sealed class NegateUInt16 : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt16)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (UInt16)unchecked(-v);
- return 1;
-
- }
- }
-
- internal sealed class NegateUInt32 : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt32)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (UInt32)unchecked(-v);
- return 1;
-
- }
- }
-
- internal sealed class NegateSingle : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Single)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Single)unchecked(-v);
- return 1;
-
- }
- }
-
- internal sealed class NegateDouble : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Double)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Double)unchecked(-v);
- return 1;
-
- }
- }
-
- internal sealed class NegateInt32Lifted : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int32?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Int32?)(unchecked(-v));
- return 1;
- }
- }
-
- internal sealed class NegateInt16Lifted : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int16?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Int16?)unchecked(-v);
- return 1;
- }
- }
-
- internal sealed class NegateInt64Lifted : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int64?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Int64?)unchecked(-v);
- return 1;
- }
- }
-
- internal sealed class NegateUInt16Lifted : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt16?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (UInt16?)unchecked(-v);
- return 1;
-
- }
- }
-
- internal sealed class NegateUInt32Lifted : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt32?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (UInt32?)unchecked(-v);
- return 1;
-
- }
- }
-
- internal sealed class NegateSingleLifted : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Single?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Single?)unchecked(-v);
- return 1;
-
- }
- }
-
- internal sealed class NegateDoubleLifted : NegateInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Double?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Double?)unchecked(-v);
- return 1;
-
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new NegateInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new NegateInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new NegateInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new NegateUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new NegateUInt32());
- case TypeCode.Single: return _Single ?? (_Single = new NegateSingle());
- case TypeCode.Double: return _Double ?? (_Double = new NegateDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new NegateInt16Lifted());
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new NegateInt32Lifted());
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new NegateInt64Lifted());
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new NegateUInt16Lifted());
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new NegateUInt32Lifted());
- case TypeCode.Single: return _SingleLifted ?? (_SingleLifted = new NegateSingleLifted());
- case TypeCode.Double: return _DoubleLifted ?? (_DoubleLifted = new NegateDoubleLifted());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "Negate()";
- }
- }
-
- internal abstract class NegateOvfInstruction : Instruction {
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _Single, _Double;
- private static Instruction _Int16Lifted, _Int32Lifted, _Int64Lifted, _UInt16Lifted, _UInt32Lifted, _SingleLifted, _DoubleLifted;
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- private NegateOvfInstruction() {
- }
-
- internal sealed class NegateOvfInt32 : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int32)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = ScriptingRuntimeHelpers.Int32ToObject(checked(-v));
- return 1;
- }
- }
-
- internal sealed class NegateOvfInt16 : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int16)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = checked((Int16)(-v));
- return 1;
- }
- }
-
- internal sealed class NegateOvfInt64 : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int64)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = checked((Int64)(-v));
- return 1;
- }
- }
-
- internal sealed class NegateOvfUInt16 : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt16)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = checked((UInt16)(-v));
- return 1;
-
- }
- }
-
- internal sealed class NegateOvfUInt32 : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt32)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = checked((UInt32)(-v));
- return 1;
-
- }
- }
-
- internal sealed class NegateOvfSingle : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Single)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Single)checked(-v);
- return 1;
-
- }
- }
-
- internal sealed class NegateOvfDouble : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Double)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Double)checked(-v);
- return 1;
-
- }
- }
-
- internal sealed class NegateOvfInt32Lifted : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int32?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Int32?)(unchecked(-v));
- return 1;
- }
- }
-
- internal sealed class NegateOvfInt16Lifted : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int16?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Int16?)unchecked(-v);
- return 1;
- }
- }
-
- internal sealed class NegateOvfInt64Lifted : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int64?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Int64?)unchecked(-v);
- return 1;
- }
- }
-
- internal sealed class NegateOvfUInt16Lifted : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt16?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (UInt16?)unchecked(-v);
- return 1;
-
- }
- }
-
- internal sealed class NegateOvfUInt32Lifted : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt32?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (UInt32?)unchecked(-v);
- return 1;
-
- }
- }
-
- internal sealed class NegateOvfSingleLifted : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Single?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Single?)unchecked(-v);
- return 1;
-
- }
- }
-
- internal sealed class NegateOvfDoubleLifted : NegateOvfInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Double?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Double?)unchecked(-v);
- return 1;
-
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new NegateOvfInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new NegateOvfInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new NegateOvfInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new NegateOvfUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new NegateOvfUInt32());
- case TypeCode.Single: return _Single ?? (_Single = new NegateOvfSingle());
- case TypeCode.Double: return _Double ?? (_Double = new NegateOvfDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new NegateOvfInt16Lifted());
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new NegateOvfInt32Lifted());
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new NegateOvfInt64Lifted());
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new NegateOvfUInt16Lifted());
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new NegateOvfUInt32Lifted());
- case TypeCode.Single: return _SingleLifted ?? (_SingleLifted = new NegateOvfSingleLifted());
- case TypeCode.Double: return _DoubleLifted ?? (_DoubleLifted = new NegateOvfDoubleLifted());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "NegateOvf()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NotEqualInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NotEqualInstruction.cs
deleted file mode 100644
index ebf5e68885a..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NotEqualInstruction.cs
+++ /dev/null
@@ -1,202 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class NotEqualInstruction : ComparisonInstruction {
- // Perf: EqualityComparer<T> but is 3/2 to 2 times slower.
- private static Instruction _Reference, _Boolean, _SByte, _Int16, _Char, _String, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double;
- private static Instruction _BooleanLifted, _SByteLifted, _Int16Lifted, _CharLifted, _Int32Lifted, _Int64Lifted,
- _ByteLifted, _UInt16Lifted, _UInt32Lifted, _UInt64Lifted, _SingleLifted, _DoubleLifted;
-
- private NotEqualInstruction() {
- }
-
- protected override object DoNullComparison (object l, object r)
- {
- return LiftedToNull ? (object) null : (object) l != r;
- }
-
- internal sealed class NotEqualBoolean : NotEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Boolean)l != (Boolean)r;
- }
- }
-
- internal sealed class NotEqualSByte : NotEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (SByte)l != (SByte)r;
- }
- }
-
- internal sealed class NotEqualInt16 : NotEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int16)l != (Int16)r;
- }
- }
-
- internal sealed class NotEqualChar : NotEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Char)l != (Char)r;
- }
- }
-
- internal sealed class NotEqualString : NotEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (String)l != (String)r;
- }
- }
-
- internal sealed class NotEqualInt32 : NotEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int32)l != (Int32)r;
- }
- }
-
- internal sealed class NotEqualInt64 : NotEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Int64)l != (Int64)r;
- }
- }
-
- internal sealed class NotEqualByte : NotEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Byte)l != (Byte)r;
- }
- }
-
- internal sealed class NotEqualUInt16 : NotEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt16)l != (UInt16)r;
- }
- }
-
- internal sealed class NotEqualUInt32 : NotEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt32)l != (UInt32)r;
- }
- }
-
- internal sealed class NotEqualUInt64 : NotEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (UInt64)l != (UInt64)r;
- }
- }
-
- internal sealed class NotEqualSingle : NotEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Single)l != (Single)r;
- }
- }
-
- internal sealed class NotEqualDouble : NotEqualInstruction {
- protected override object DoCalculate (object l, object r)
- {
- return (Double)l != (Double)r;
- }
- }
-
- internal sealed class NotEqualReference : NotEqualInstruction {
- protected override object Calculate (object l, object r)
- {
- return l != r;
- }
-
- protected override object DoCalculate (object l, object r)
- {
- throw Assert.Unreachable;
- }
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- public static Instruction Create(Type type) {
- // Boxed enums can be unboxed as their underlying types:
- switch ((type.IsEnum() ? Enum.GetUnderlyingType(type) : type).GetTypeCode()) {
- case TypeCode.Boolean: return _Boolean ?? (_Boolean = new NotEqualBoolean());
- case TypeCode.SByte: return _SByte ?? (_SByte = new NotEqualSByte());
- case TypeCode.Byte: return _Byte ?? (_Byte = new NotEqualByte());
- case TypeCode.Char: return _Char ?? (_Char = new NotEqualChar());
- case TypeCode.String: return _String ?? (_String = new NotEqualString());
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new NotEqualInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new NotEqualInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new NotEqualInt64());
-
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new NotEqualInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new NotEqualInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new NotEqualInt64());
-
- case TypeCode.Single: return _Single ?? (_Single = new NotEqualSingle());
- case TypeCode.Double: return _Double ?? (_Double = new NotEqualDouble());
-
- case TypeCode.Object:
- if (!type.IsValueType()) {
- return _Reference ?? (_Reference = new NotEqualReference());
- }
- // TODO: Nullable<T>
- throw new NotImplementedException();
-
- default:
- throw new NotImplementedException();
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- // Boxed enums can be unboxed as their underlying types:
- switch ((type.IsEnum() ? Enum.GetUnderlyingType(type) : type).GetTypeCode()) {
- case TypeCode.Boolean: return _BooleanLifted ?? (_BooleanLifted = new NotEqualBoolean() { LiftedToNull = true });
- case TypeCode.SByte: return _SByteLifted ?? (_SByteLifted = new NotEqualSByte() { LiftedToNull = true });
- case TypeCode.Byte: return _ByteLifted ?? (_ByteLifted = new NotEqualByte() { LiftedToNull = true });
- case TypeCode.Char: return _CharLifted ?? (_CharLifted = new NotEqualChar() { LiftedToNull = true });
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new NotEqualInt16() { LiftedToNull = true });
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new NotEqualInt32() { LiftedToNull = true });
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new NotEqualInt64() { LiftedToNull = true });
-
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new NotEqualInt16() { LiftedToNull = true });
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new NotEqualInt32() { LiftedToNull = true });
- case TypeCode.UInt64: return _UInt64Lifted ?? (_UInt64Lifted = new NotEqualInt64() { LiftedToNull = true });
-
- case TypeCode.Single: return _SingleLifted ?? (_SingleLifted = new NotEqualSingle() { LiftedToNull = true });
- case TypeCode.Double: return _DoubleLifted ?? (_DoubleLifted = new NotEqualDouble() { LiftedToNull = true });
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "NotEqual()";
- }
- }
-}
-
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NotInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NotInstruction.cs
deleted file mode 100644
index e1eb3d8bd11..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NotInstruction.cs
+++ /dev/null
@@ -1,191 +0,0 @@
-//
-// NotInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class NotInstruction : Instruction {
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Boolean;
- private static Instruction _Int16Lifted, _Int32Lifted, _Int64Lifted, _UInt16Lifted, _UInt32Lifted, _UInt64Lifted, _BooleanLifted;
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- private NotInstruction() {
- }
-
- internal sealed class NotBoolean : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- frame.Push((bool)frame.Pop() ? ScriptingRuntimeHelpers.False : ScriptingRuntimeHelpers.True);
- return 1;
- }
- }
-
- internal sealed class NotInt32 : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int32)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = ScriptingRuntimeHelpers.Int32ToObject(~v);
- return 1;
- }
- }
-
- internal sealed class NotInt16 : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int16)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Int16)(~v);
- return 1;
- }
- }
-
- internal sealed class NotInt64 : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int64)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Int64)(~v);
- return 1;
- }
- }
-
- internal sealed class NotUInt16 : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt64)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (UInt64)(~v);
- return 1;
- }
- }
-
- internal sealed class NotUInt32 : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt32)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (UInt32)(~v);
- return 1;
- }
- }
-
- internal sealed class NotUInt64 : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt64)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (UInt64)(~v);
- return 1;
- }
- }
-
- internal sealed class NotBooleanLifted : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Boolean?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Boolean?)(!v);
- return 1;
- }
- }
-
- internal sealed class NotInt32Lifted : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int32?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Int32?)(~v);
- return 1;
- }
- }
-
- internal sealed class NotInt16Lifted : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int16?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Int16?)(~v);
- return 1;
- }
- }
-
- internal sealed class NotInt64Lifted : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (Int64?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (Int64?)(~v);
- return 1;
- }
- }
-
- internal sealed class NotUInt16Lifted : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt64?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (UInt64?)(~v);
- return 1;
- }
- }
-
- internal sealed class NotUInt32Lifted : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt32?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (UInt32?)(~v);
- return 1;
- }
- }
-
- internal sealed class NotUInt64Lifted : NotInstruction {
- public override int Run(InterpretedFrame frame) {
- var v = (UInt64?)frame.Data[frame.StackIndex - 1];
- frame.Data[frame.StackIndex - 1] = (UInt64?)(~v);
- return 1;
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new NotInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new NotInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new NotInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new NotUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new NotUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new NotUInt64());
- case TypeCode.Boolean: return _Boolean ?? (_Boolean = new NotBoolean());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new NotInt16Lifted());
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new NotInt32Lifted());
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new NotInt64Lifted());
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new NotUInt16Lifted());
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new NotUInt32Lifted());
- case TypeCode.UInt64: return _UInt64Lifted ?? (_UInt64Lifted = new NotUInt64Lifted());
- case TypeCode.Boolean: return _BooleanLifted ?? (_BooleanLifted = new NotBooleanLifted());
-
- default:
- throw Assert.Unreachable;
- }
- }
- public override string ToString() {
- return "Not()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NumericConvertInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NumericConvertInstruction.cs
deleted file mode 100644
index 7406f6babee..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NumericConvertInstruction.cs
+++ /dev/null
@@ -1,254 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class NumericConvertInstruction : Instruction {
- internal readonly TypeCode _from, _to;
-
- protected NumericConvertInstruction(TypeCode from, TypeCode to) {
- _from = from;
- _to = to;
- }
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- public override string ToString() {
- return InstructionName + "(" + _from + "->" + _to + ")";
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
- public sealed class Unchecked : NumericConvertInstruction {
- public override string InstructionName { get { return "UncheckedConvert"; } }
-
- public Unchecked(TypeCode from, TypeCode to)
- : base(from, to) {
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Push(Convert(frame.Pop()));
- return +1;
- }
-
- private object Convert(object obj) {
- switch (_from) {
- case TypeCode.Byte: return ConvertInt32((Byte)obj);
- case TypeCode.SByte: return ConvertInt32((SByte)obj);
- case TypeCode.Int16: return ConvertInt32((Int16)obj);
- case TypeCode.Char: return ConvertInt32((Char)obj);
- case TypeCode.Int32: return ConvertInt32((Int32)obj);
- case TypeCode.Int64: return ConvertInt64((Int64)obj);
- case TypeCode.UInt16: return ConvertInt32((UInt16)obj);
- case TypeCode.UInt32: return ConvertInt64((UInt32)obj);
- case TypeCode.UInt64: return ConvertUInt64((UInt64)obj);
- case TypeCode.Single: return ConvertDouble((Single)obj);
- case TypeCode.Double: return ConvertDouble((Double)obj);
- default: throw Assert.Unreachable;
- }
- }
-
- private object ConvertInt32(int obj) {
- unchecked {
- switch (_to) {
- case TypeCode.Byte: return (Byte)obj;
- case TypeCode.SByte: return (SByte)obj;
- case TypeCode.Int16: return (Int16)obj;
- case TypeCode.Char: return (Char)obj;
- case TypeCode.Int32: return (Int32)obj;
- case TypeCode.Int64: return (Int64)obj;
- case TypeCode.UInt16: return (UInt16)obj;
- case TypeCode.UInt32: return (UInt32)obj;
- case TypeCode.UInt64: return (UInt64)obj;
- case TypeCode.Single: return (Single)obj;
- case TypeCode.Double: return (Double)obj;
- default: throw Assert.Unreachable;
- }
- }
- }
-
- private object ConvertInt64(Int64 obj) {
- unchecked {
- switch (_to) {
- case TypeCode.Byte: return (Byte)obj;
- case TypeCode.SByte: return (SByte)obj;
- case TypeCode.Int16: return (Int16)obj;
- case TypeCode.Char: return (Char)obj;
- case TypeCode.Int32: return (Int32)obj;
- case TypeCode.Int64: return (Int64)obj;
- case TypeCode.UInt16: return (UInt16)obj;
- case TypeCode.UInt32: return (UInt32)obj;
- case TypeCode.UInt64: return (UInt64)obj;
- case TypeCode.Single: return (Single)obj;
- case TypeCode.Double: return (Double)obj;
- default: throw Assert.Unreachable;
- }
- }
- }
-
- private object ConvertUInt64(UInt64 obj) {
- unchecked {
- switch (_to) {
- case TypeCode.Byte: return (Byte)obj;
- case TypeCode.SByte: return (SByte)obj;
- case TypeCode.Int16: return (Int16)obj;
- case TypeCode.Char: return (Char)obj;
- case TypeCode.Int32: return (Int32)obj;
- case TypeCode.Int64: return (Int64)obj;
- case TypeCode.UInt16: return (UInt16)obj;
- case TypeCode.UInt32: return (UInt32)obj;
- case TypeCode.UInt64: return (UInt64)obj;
- case TypeCode.Single: return (Single)obj;
- case TypeCode.Double: return (Double)obj;
- default: throw Assert.Unreachable;
- }
- }
- }
-
- private object ConvertDouble(Double obj) {
- unchecked {
- switch (_to) {
- case TypeCode.Byte: return (Byte)obj;
- case TypeCode.SByte: return (SByte)obj;
- case TypeCode.Int16: return (Int16)obj;
- case TypeCode.Char: return (Char)obj;
- case TypeCode.Int32: return (Int32)obj;
- case TypeCode.Int64: return (Int64)obj;
- case TypeCode.UInt16: return (UInt16)obj;
- case TypeCode.UInt32: return (UInt32)obj;
- case TypeCode.UInt64: return (UInt64)obj;
- case TypeCode.Single: return (Single)obj;
- case TypeCode.Double: return (Double)obj;
- default: throw Assert.Unreachable;
- }
- }
- }
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
- public sealed class Checked : NumericConvertInstruction {
- public override string InstructionName { get { return "CheckedConvert"; } }
-
- public Checked(TypeCode from, TypeCode to)
- : base(from, to) {
- }
-
- public override int Run(InterpretedFrame frame) {
- frame.Push(Convert(frame.Pop()));
- return +1;
- }
-
- private object Convert(object obj) {
- switch (_from) {
- case TypeCode.Byte: return ConvertInt32((Byte)obj);
- case TypeCode.SByte: return ConvertInt32((SByte)obj);
- case TypeCode.Int16: return ConvertInt32((Int16)obj);
- case TypeCode.Char: return ConvertInt32((Char)obj);
- case TypeCode.Int32: return ConvertInt32((Int32)obj);
- case TypeCode.Int64: return ConvertInt64((Int64)obj);
- case TypeCode.UInt16: return ConvertInt32((UInt16)obj);
- case TypeCode.UInt32: return ConvertInt64((UInt32)obj);
- case TypeCode.UInt64: return ConvertUInt64((UInt64)obj);
- case TypeCode.Single: return ConvertDouble((Single)obj);
- case TypeCode.Double: return ConvertDouble((Double)obj);
- default: throw Assert.Unreachable;
- }
- }
-
- private object ConvertInt32(int obj) {
- checked {
- switch (_to) {
- case TypeCode.Byte: return (Byte)obj;
- case TypeCode.SByte: return (SByte)obj;
- case TypeCode.Int16: return (Int16)obj;
- case TypeCode.Char: return (Char)obj;
- case TypeCode.Int32: return (Int32)obj;
- case TypeCode.Int64: return (Int64)obj;
- case TypeCode.UInt16: return (UInt16)obj;
- case TypeCode.UInt32: return (UInt32)obj;
- case TypeCode.UInt64: return (UInt64)obj;
- case TypeCode.Single: return (Single)obj;
- case TypeCode.Double: return (Double)obj;
- default: throw Assert.Unreachable;
- }
- }
- }
-
- private object ConvertInt64(Int64 obj) {
- checked {
- switch (_to) {
- case TypeCode.Byte: return (Byte)obj;
- case TypeCode.SByte: return (SByte)obj;
- case TypeCode.Int16: return (Int16)obj;
- case TypeCode.Char: return (Char)obj;
- case TypeCode.Int32: return (Int32)obj;
- case TypeCode.Int64: return (Int64)obj;
- case TypeCode.UInt16: return (UInt16)obj;
- case TypeCode.UInt32: return (UInt32)obj;
- case TypeCode.UInt64: return (UInt64)obj;
- case TypeCode.Single: return (Single)obj;
- case TypeCode.Double: return (Double)obj;
- default: throw Assert.Unreachable;
- }
- }
- }
-
- private object ConvertUInt64(UInt64 obj) {
- checked {
- switch (_to) {
- case TypeCode.Byte: return (Byte)obj;
- case TypeCode.SByte: return (SByte)obj;
- case TypeCode.Int16: return (Int16)obj;
- case TypeCode.Char: return (Char)obj;
- case TypeCode.Int32: return (Int32)obj;
- case TypeCode.Int64: return (Int64)obj;
- case TypeCode.UInt16: return (UInt16)obj;
- case TypeCode.UInt32: return (UInt32)obj;
- case TypeCode.UInt64: return (UInt64)obj;
- case TypeCode.Single: return (Single)obj;
- case TypeCode.Double: return (Double)obj;
- default: throw Assert.Unreachable;
- }
- }
- }
-
- private object ConvertDouble(Double obj) {
- checked {
- switch (_to) {
- case TypeCode.Byte: return (Byte)obj;
- case TypeCode.SByte: return (SByte)obj;
- case TypeCode.Int16: return (Int16)obj;
- case TypeCode.Char: return (Char)obj;
- case TypeCode.Int32: return (Int32)obj;
- case TypeCode.Int64: return (Int64)obj;
- case TypeCode.UInt16: return (UInt16)obj;
- case TypeCode.UInt32: return (UInt32)obj;
- case TypeCode.UInt64: return (UInt64)obj;
- case TypeCode.Single: return (Single)obj;
- case TypeCode.Double: return (Double)obj;
- default: throw Assert.Unreachable;
- }
- }
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/OrInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/OrInstruction.cs
deleted file mode 100644
index bf72dbf9537..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/OrInstruction.cs
+++ /dev/null
@@ -1,176 +0,0 @@
-//
-// OrInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class OrInstruction : ArithmeticInstruction {
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Boolean;
- private static Instruction _Int16Lifted, _Int32Lifted, _Int64Lifted, _UInt16Lifted, _UInt32Lifted, _UInt64Lifted, _BooleanLifted;
-
- private OrInstruction() {
- }
-
- internal sealed class OrInt32 : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return ScriptingRuntimeHelpers.Int32ToObject((Int32)l | (Int32)r);
- }
- }
-
- internal sealed class OrInt16 : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int16)((Int16)l | (Int16)r);
- }
- }
-
- internal sealed class OrInt64 : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64)((Int64)l | (Int64)r);
- }
- }
-
- internal sealed class OrUInt16 : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt16)((UInt16)l | (UInt16)r);
- }
- }
-
- internal sealed class OrUInt32 : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32)((UInt32)l | (UInt32)r);
- }
- }
-
- internal sealed class OrUInt64 : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64)((UInt64)l | (UInt64)r);
- }
- }
-
- internal sealed class OrBoolean : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Boolean)((Boolean)l | (Boolean)r);
- }
- }
-
- internal sealed class OrInt32Lifted : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int32?)((Int32?)l | (Int32?)r);
- }
- }
-
- internal sealed class OrInt16Lifted : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int16?)((Int16?)l | (Int16?)r);
- }
- }
-
- internal sealed class OrInt64Lifted : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64?)((Int64?)l | (Int64?)r);
- }
- }
-
- internal sealed class OrUInt16Lifted : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt16?)((Int16?)l | (Int16?)r);
- }
- }
-
- internal sealed class OrUInt32Lifted : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32?)((UInt32?)l | (UInt32?)r);
- }
- }
-
- internal sealed class OrUInt64Lifted : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64?)((UInt64?)l | (UInt64?)r);
- }
- }
-
- internal sealed class OrBooleanLifted : OrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Boolean?)((Boolean?)l | (Boolean?)r);
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new OrInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new OrInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new OrInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new OrUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new OrUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new OrUInt64());
- case TypeCode.Boolean: return _Boolean ?? (_Boolean = new OrBoolean());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new OrInt16Lifted());
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new OrInt32Lifted());
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new OrInt64Lifted());
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new OrUInt16Lifted());
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new OrUInt32Lifted());
- case TypeCode.UInt64: return _UInt64Lifted ?? (_UInt64Lifted = new OrUInt64Lifted());
- case TypeCode.Boolean: return _BooleanLifted ?? (_BooleanLifted = new OrBooleanLifted());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "Or()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ShlInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ShlInstruction.cs
deleted file mode 100644
index 7bb2c00c521..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ShlInstruction.cs
+++ /dev/null
@@ -1,160 +0,0 @@
-//
-// ShlInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class ShlInstruction : ArithmeticInstruction {
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64;
- private static Instruction _Int16Lifted, _Int32Lifted, _Int64Lifted, _UInt16Lifted, _UInt32Lifted, _UInt64Lifted;
-
- private ShlInstruction() {
- }
-
- internal sealed class ShlInt32 : ShlInstruction {
- protected override object Calculate (object l, object r)
- {
- return ScriptingRuntimeHelpers.Int32ToObject((Int32)l << (Int32)r);
- }
- }
-
- internal sealed class ShlInt16 : ShlInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int32)((Int16)l << (Int32)r);
- }
- }
-
- internal sealed class ShlInt64 : ShlInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64)((Int64)l << (Int32)r);
- }
- }
-
- internal sealed class ShlUInt16 : ShlInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int32)((UInt16)l << (Int32)r);
- }
- }
-
- internal sealed class ShlUInt32 : ShlInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32)((UInt32)l << (Int32)r);
- }
- }
-
- internal sealed class ShlUInt64 : ShlInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64)((UInt64)l << (Int32)r);
- }
- }
-
- internal sealed class ShlInt32Lifted : ShlInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int32?)((Int32?)l << (Int32?)r);
- }
- }
-
- internal sealed class ShlInt16Lifted : ShlInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int32)((Int16?)l << (Int32?)r);
- }
- }
-
- internal sealed class ShlInt64Lifted : ShlInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64?)((Int64?)l << (Int32?)r);
- }
- }
-
- internal sealed class ShlUInt16Lifted : ShlInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int32?)((UInt16?)l << (Int32?)r);
- }
- }
-
- internal sealed class ShlUInt32Lifted : ShlInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32?)((UInt32?)l << (Int32?)r);
- }
- }
-
- internal sealed class ShlUInt64Lifted : ShlInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64?)((UInt64?)l << (Int32?)r);
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new ShlInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new ShlInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new ShlInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new ShlUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new ShlUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new ShlUInt64());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new ShlInt16Lifted());
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new ShlInt32Lifted());
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new ShlInt64Lifted());
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new ShlUInt16Lifted());
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new ShlUInt32Lifted());
- case TypeCode.UInt64: return _UInt64Lifted ?? (_UInt64Lifted = new ShlUInt64Lifted());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "Shl()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ShrInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ShrInstruction.cs
deleted file mode 100644
index 5663f18418f..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ShrInstruction.cs
+++ /dev/null
@@ -1,160 +0,0 @@
-//
-// ShrInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class ShrInstruction : ArithmeticInstruction {
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64;
- private static Instruction _Int16Lifted, _Int32Lifted, _Int64Lifted, _UInt16Lifted, _UInt32Lifted, _UInt64Lifted;
-
- private ShrInstruction() {
- }
-
- internal sealed class ShrInt32 : ShrInstruction {
- protected override object Calculate (object l, object r)
- {
- return ScriptingRuntimeHelpers.Int32ToObject((Int32)l >> (Int32)r);
- }
- }
-
- internal sealed class ShrInt16 : ShrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int32)((Int16)l >> (Int32)r);
- }
- }
-
- internal sealed class ShrInt64 : ShrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64)((Int64)l >> (Int32)r);
- }
- }
-
- internal sealed class ShrUInt16 : ShrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int32)((UInt16)l >> (Int32)r);
- }
- }
-
- internal sealed class ShrUInt32 : ShrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32)((UInt32)l >> (Int32)r);
- }
- }
-
- internal sealed class ShrUInt64 : ShrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64)((UInt64)l >> (Int32)r);
- }
- }
-
- internal sealed class ShrInt32Lifted : ShrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int32?)((Int32?)l >> (Int32?)r);
- }
- }
-
- internal sealed class ShrInt16Lifted : ShrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int32)((Int16?)l >> (Int32?)r);
- }
- }
-
- internal sealed class ShrInt64Lifted : ShrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64?)((Int64?)l >> (Int32?)r);
- }
- }
-
- internal sealed class ShrUInt16Lifted : ShrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int32?)((UInt16?)l >> (Int32?)r);
- }
- }
-
- internal sealed class ShrUInt32Lifted : ShrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32?)((UInt32?)l >> (Int32?)r);
- }
- }
-
- internal sealed class ShrUInt64Lifted : ShrInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64?)((UInt64?)l >> (Int32?)r);
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new ShrInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new ShrInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new ShrInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new ShrUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new ShrUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new ShrUInt64());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new ShrInt16Lifted());
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new ShrInt32Lifted());
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new ShrInt64Lifted());
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new ShrUInt16Lifted());
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new ShrUInt32Lifted());
- case TypeCode.UInt64: return _UInt64Lifted ?? (_UInt64Lifted = new ShrUInt64Lifted());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "Shr()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/StackOperations.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/StackOperations.cs
deleted file mode 100644
index 6cff464f0aa..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/StackOperations.cs
+++ /dev/null
@@ -1,118 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Collections.Generic;
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Utils;
-namespace Microsoft.Scripting.Interpreter {
- internal sealed class LoadObjectInstruction : Instruction {
- private readonly object _value;
-
- internal LoadObjectInstruction(object value) {
- _value = value;
- }
-
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex++] = _value;
- return +1;
- }
-
- public override string ToString() {
- return "LoadObject(" + (_value ?? "null") + ")";
- }
- }
-
- internal sealed class LoadCachedObjectInstruction : Instruction {
- private readonly uint _index;
-
- internal LoadCachedObjectInstruction(uint index) {
- _index = index;
- }
-
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex++] = frame.Interpreter._objects[_index];
- return +1;
- }
-
- public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects) {
- return String.Format("LoadCached({0}: {1})", _index, objects[(int)_index]);
- }
-
- public override string ToString() {
- return "LoadCached(" + _index + ")";
- }
- }
-
- internal sealed class PopInstruction : Instruction {
- internal static readonly PopInstruction Instance = new PopInstruction();
-
- private PopInstruction() { }
-
- public override int ConsumedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Pop();
- return +1;
- }
-
- public override string ToString() {
- return "Pop()";
- }
- }
-
- // NOTE: Consider caching if used frequently
- internal sealed class PopNInstruction : Instruction {
- private readonly int _n;
-
- internal PopNInstruction(int n) {
- _n = n;
- }
-
- public override int ConsumedStack { get { return _n; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Pop(_n);
- return +1;
- }
-
- public override string ToString() {
- return "Pop(" + _n + ")";
- }
- }
-
- internal sealed class DupInstruction : Instruction {
- internal readonly static DupInstruction Instance = new DupInstruction();
-
- private DupInstruction() { }
-
- public override int ConsumedStack { get { return 0; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Data[frame.StackIndex] = frame.Peek();
- frame.StackIndex++;
- return +1;
- }
-
- public override string ToString() {
- return "Dup()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/SubInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/SubInstruction.cs
deleted file mode 100644
index 95fc003f0f8..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/SubInstruction.cs
+++ /dev/null
@@ -1,204 +0,0 @@
-//
-// SubInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class SubInstruction : ArithmeticInstruction {
-
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double;
-
- private SubInstruction() {
- }
-
- internal sealed class SubInt32 : SubInstruction {
- protected override object Calculate (object l, object r)
- {
- return ScriptingRuntimeHelpers.Int32ToObject(unchecked((Int32)l - (Int32)r));
- }
- }
-
- internal sealed class SubInt16 : SubInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int16)unchecked((Int16)l - (Int16)r);
- }
- }
-
- internal sealed class SubInt64 : SubInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64)unchecked((Int64)l - (Int64)r);
- }
- }
-
- internal sealed class SubUInt16 : SubInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt16)unchecked((UInt16)l - (UInt16)r);
- }
- }
-
- internal sealed class SubUInt32 : SubInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32)unchecked((UInt32)l - (UInt32)r);
- }
- }
-
- internal sealed class SubUInt64 : SubInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64)unchecked((UInt64)l - (UInt64)r);
- }
- }
-
- internal sealed class SubSingle : SubInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Single)((Single)l - (Single)r);
- }
- }
-
- internal sealed class SubDouble : SubInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Double)l - (Double)r;
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new SubInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new SubInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new SubInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new SubUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new SubUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new SubUInt64());
- case TypeCode.Single: return _Single ?? (_Single = new SubSingle());
- case TypeCode.Double: return _Double ?? (_Double = new SubDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "Sub()";
- }
- }
-
- internal abstract class SubOvfInstruction : ArithmeticInstruction {
-
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double;
-
- private SubOvfInstruction() {
- }
-
- internal sealed class SubOvfInt32 : SubOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return ScriptingRuntimeHelpers.Int32ToObject(checked((Int32)l - (Int32)r));
- }
- }
-
- internal sealed class SubOvfInt16 : SubOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((Int16)((Int16)l - (Int16)r));
- }
- }
-
- internal sealed class SubOvfInt64 : SubOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((Int64)((Int64)l - (Int64)r));
- }
- }
-
- internal sealed class SubOvfUInt16 : SubOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((UInt16)((UInt16)l - (UInt16)r));
- }
- }
-
- internal sealed class SubOvfUInt32 : SubOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((UInt32)((UInt32)l - (UInt32)r));
- }
- }
-
- internal sealed class SubOvfUInt64 : SubOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return checked((UInt64)((UInt64)l - (UInt64)r));
- }
- }
-
- internal sealed class SubOvfSingle : SubOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Single)((Single)l - (Single)r);
- }
- }
-
- internal sealed class SubOvfDouble : SubOvfInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Double)l - (Double)r;
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new SubOvfInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new SubOvfInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new SubOvfInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new SubOvfUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new SubOvfUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new SubOvfUInt64());
- case TypeCode.Single: return _Single ?? (_Single = new SubOvfSingle());
- case TypeCode.Double: return _Double ?? (_Double = new SubOvfDouble());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "SubOvf()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/TypeOperations.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/TypeOperations.cs
deleted file mode 100644
index 44354f7f41b..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/TypeOperations.cs
+++ /dev/null
@@ -1,193 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-using System.Linq;
-
-namespace Microsoft.Scripting.Interpreter {
- internal sealed class CreateDelegateInstruction : Instruction {
- private readonly LightDelegateCreator _creator;
-
- internal CreateDelegateInstruction(LightDelegateCreator delegateCreator) {
- _creator = delegateCreator;
- }
-
- public override int ConsumedStack { get { return _creator.Interpreter.ClosureSize; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- StrongBox<object>[] closure;
- if (ConsumedStack > 0) {
- closure = new StrongBox<object>[ConsumedStack];
- for (int i = closure.Length - 1; i >= 0; i--) {
- closure[i] = (StrongBox<object>)frame.Pop();
- }
- } else {
- closure = null;
- }
-
- Delegate d = _creator.CreateDelegate(closure);
-
- frame.Push(d);
- return +1;
- }
- }
-
- internal sealed class NewInstruction : Instruction {
- private readonly ConstructorInfo _constructor;
- private readonly int _argCount;
-
- public NewInstruction(ConstructorInfo constructor) {
- _constructor = constructor;
- _argCount = constructor.GetParameters().Length;
-
- }
- public override int ConsumedStack { get { return _argCount; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- object[] args = new object[_argCount];
- for (int i = _argCount - 1; i >= 0; i--) {
- args[i] = frame.Pop();
- }
-
- object ret;
- try {
- ret = _constructor.Invoke(args);
- } catch (TargetInvocationException e) {
- ExceptionHelpers.UpdateForRethrow(e.InnerException);
- throw e.InnerException;
- }
-
- frame.Push(ret);
- return +1;
- }
-
- public override string ToString() {
- return "New " + _constructor.DeclaringType.Name + "(" + _constructor + ")";
- }
- }
-
- internal sealed class DefaultValueInstruction<T> : Instruction {
- internal DefaultValueInstruction() { }
-
- public override int ConsumedStack { get { return 0; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- frame.Push(default(T));
- return +1;
- }
-
- public override string ToString() {
- return "New " + typeof(T);
- }
- }
-
- internal sealed class TypeIsInstruction<T> : Instruction {
- internal TypeIsInstruction() { }
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- // unfortunately Type.IsInstanceOfType() is 35-times slower than "is T" so we use generic code:
- frame.Push(ScriptingRuntimeHelpers.BooleanToObject(frame.Pop() is T));
- return +1;
- }
-
- public override string ToString() {
- return "TypeIs " + typeof(T).Name;
- }
- }
-
- internal sealed class TypeAsInstruction<T> : Instruction {
- internal TypeAsInstruction() { }
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- public override int Run(InterpretedFrame frame) {
- // can't use as w/o generic constraint
- object value = frame.Pop();
- if (value is T) {
- frame.Push(value);
- } else {
- frame.Push(null);
- }
- return +1;
- }
-
- public override string ToString() {
- return "TypeAs " + typeof(T).Name;
- }
- }
-
- internal sealed class TypeEqualsInstruction : Instruction {
- public static readonly TypeEqualsInstruction Instance = new TypeEqualsInstruction();
-
- public override int ConsumedStack { get { return 2; } }
- public override int ProducedStack { get { return 1; } }
-
- private TypeEqualsInstruction() {
- }
-
- public override int Run(InterpretedFrame frame) {
- object type = frame.Pop();
- object obj = frame.Pop();
- frame.Push(ScriptingRuntimeHelpers.BooleanToObject(obj != null && (object)obj.GetType() == type));
- return +1;
- }
-
- public override string InstructionName {
- get { return "TypeEquals()"; }
- }
- }
-
- internal sealed class WrapToNullableInstruction<T> : Instruction {
-
- readonly Type elementType;
- ConstructorInfo ctor;
-
- public override int ConsumedStack { get { return 1; } }
- public override int ProducedStack { get { return 1; } }
-
- internal WrapToNullableInstruction(Type elementType) {
- this.elementType = elementType;
- }
-
- public override int Run(InterpretedFrame frame) {
- var r = frame.Data[frame.StackIndex - 1];
-
- // Don't need to wrap null values
- if (r == null)
- return 1;
-
- ctor = typeof (Nullable<>).MakeGenericType (elementType).GetDeclaredConstructors ().First ();
- frame.Data[frame.StackIndex - 1] = ctor.Invoke (new [] { r });
- return 1;
- }
-
- public override string InstructionName {
- get { return "WrapTo " + typeof(T) + "?"; }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/XorInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/XorInstruction.cs
deleted file mode 100644
index 5cea8b38606..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/XorInstruction.cs
+++ /dev/null
@@ -1,176 +0,0 @@
-//
-// XorInstruction.cs:
-//
-// Authors: Marek Safar (marek.safar@gmail.com)
-//
-// Copyright 2014 Xamarin Inc
-//
-// 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.
-//
-//
-
-using System;
-using System.Diagnostics;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- internal abstract class XorInstruction : ArithmeticInstruction {
- private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Boolean;
- private static Instruction _Int16Lifted, _Int32Lifted, _Int64Lifted, _UInt16Lifted, _UInt32Lifted, _UInt64Lifted, _BooleanLifted;
-
- private XorInstruction() {
- }
-
- internal sealed class XorInt32 : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return ScriptingRuntimeHelpers.Int32ToObject((Int32)l ^ (Int32)r);
- }
- }
-
- internal sealed class XorInt16 : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int16)((Int16)l ^ (Int16)r);
- }
- }
-
- internal sealed class XorInt64 : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64)((Int64)l ^ (Int64)r);
- }
- }
-
- internal sealed class XorUInt16 : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt16)((UInt16)l ^ (UInt16)r);
- }
- }
-
- internal sealed class XorUInt32 : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32)((UInt32)l ^ (UInt32)r);
- }
- }
-
- internal sealed class XorUInt64 : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64)((UInt64)l ^ (UInt64)r);
- }
- }
-
- internal sealed class XorBoolean : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Boolean)((Boolean)l ^ (Boolean)r);
- }
- }
-
- internal sealed class XorInt32Lifted : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int32?)((Int32?)l ^ (Int32?)r);
- }
- }
-
- internal sealed class XorInt16Lifted : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int16?)((Int16?)l ^ (Int16?)r);
- }
- }
-
- internal sealed class XorInt64Lifted : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Int64?)((Int64?)l ^ (Int64?)r);
- }
- }
-
- internal sealed class XorUInt16Lifted : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt16?)((UInt16?)l ^ (UInt16?)r);
- }
- }
-
- internal sealed class XorUInt32Lifted : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt32?)((UInt32?)l ^ (UInt32?)r);
- }
- }
-
- internal sealed class XorUInt64Lifted : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return (UInt64?)((UInt64?)l ^ (UInt64?)r);
- }
- }
-
- internal sealed class XorBooleanLifted : XorInstruction {
- protected override object Calculate (object l, object r)
- {
- return (Boolean?)((Boolean?)l ^ (Boolean?)r);
- }
- }
-
- public static Instruction Create(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16 ?? (_Int16 = new XorInt16());
- case TypeCode.Int32: return _Int32 ?? (_Int32 = new XorInt32());
- case TypeCode.Int64: return _Int64 ?? (_Int64 = new XorInt64());
- case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new XorUInt16());
- case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new XorUInt32());
- case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new XorUInt64());
- case TypeCode.Boolean: return _Boolean ?? (_Boolean = new XorBoolean());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public static Instruction CreateLifted(Type type) {
- Debug.Assert(!type.IsEnum());
- switch (type.GetTypeCode()) {
- case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new XorInt16Lifted());
- case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new XorInt32Lifted());
- case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new XorInt64Lifted());
- case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new XorUInt16Lifted());
- case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new XorUInt32Lifted());
- case TypeCode.UInt64: return _UInt64Lifted ?? (_UInt64Lifted = new XorUInt64Lifted());
- case TypeCode.Boolean: return _BooleanLifted ?? (_BooleanLifted = new XorBooleanLifted());
-
- default:
- throw Assert.Unreachable;
- }
- }
-
- public override string ToString() {
- return "Xor()";
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/InterpretedFrame.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/InterpretedFrame.cs
deleted file mode 100644
index cd3a0784842..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/InterpretedFrame.cs
+++ /dev/null
@@ -1,297 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using Microsoft.Scripting.Utils;
-using Microsoft.Scripting.Runtime;
-
-namespace Microsoft.Scripting.Interpreter {
-#if CLR45
- using InterpretedFrameThreadLocal = ThreadLocal<InterpretedFrame>;
-#else
- using InterpretedFrameThreadLocal = Microsoft.Scripting.Utils.ThreadLocal<InterpretedFrame>;
-#endif
-
- public sealed class InterpretedFrame {
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
- public static readonly InterpretedFrameThreadLocal CurrentFrame = new InterpretedFrameThreadLocal();
-
- internal readonly Interpreter Interpreter;
- internal InterpretedFrame _parent;
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
- private int[] _continuations;
- private int _continuationIndex;
- private int _pendingContinuation;
- private object _pendingValue;
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
- public readonly object[] Data;
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
- public readonly StrongBox<object>[] Closure;
-
- public int StackIndex;
- public int InstructionIndex;
-
- // When a ThreadAbortException is raised from interpreted code this is the first frame that caught it.
- // No handlers within this handler re-abort the current thread when left.
- public ExceptionHandler CurrentAbortHandler;
-
- internal InterpretedFrame(Interpreter interpreter, StrongBox<object>[] closure) {
- Interpreter = interpreter;
- StackIndex = interpreter.LocalCount;
- Data = new object[StackIndex + interpreter.Instructions.MaxStackDepth];
-
- int c = interpreter.Instructions.MaxContinuationDepth;
- if (c > 0) {
- _continuations = new int[c];
- }
-
- Closure = closure;
- }
-
- public DebugInfo GetDebugInfo(int instructionIndex) {
- return DebugInfo.GetMatchingDebugInfo(Interpreter._debugInfos, instructionIndex);
- }
-
- public string Name {
- get { return Interpreter._name; }
- }
-
- #region Data Stack Operations
-
- public void Push(object value) {
- Data[StackIndex++] = value;
- }
-
- public void Push(bool value) {
- Data[StackIndex++] = value ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
- }
-
- public void Push(int value) {
- Data[StackIndex++] = ScriptingRuntimeHelpers.Int32ToObject(value);
- }
-
- public object Pop() {
- return Data[--StackIndex];
- }
-
- public object Pop(int n) {
- int si = StackIndex - n;
- StackIndex = si;
- return Data[si];
- }
-
- internal void SetStackDepth(int depth) {
- StackIndex = Interpreter.LocalCount + depth;
- }
-
- public object Peek() {
- return Data[StackIndex - 1];
- }
-
- public void Dup() {
- int i = StackIndex;
- Data[i] = Data[i - 1];
- StackIndex = i + 1;
- }
-
- #endregion
-
- #region Stack Trace
-
- public InterpretedFrame Parent {
- get { return _parent; }
- }
-
- public static bool IsInterpretedFrame(MethodBase method) {
- ContractUtils.RequiresNotNull(method, "method");
- return method.DeclaringType == typeof(Interpreter) && method.Name == "Run";
- }
-
-#if FEATURE_STACK_TRACE
- /// <summary>
- /// A single interpreted frame might be represented by multiple subsequent Interpreter.Run CLR frames.
- /// This method filters out the duplicate CLR frames.
- /// </summary>
- public static IEnumerable<StackFrame> GroupStackFrames(IEnumerable<StackFrame> stackTrace) {
- bool inInterpretedFrame = false;
- foreach (StackFrame frame in stackTrace) {
- if (InterpretedFrame.IsInterpretedFrame(frame.GetMethod())) {
- if (inInterpretedFrame) {
- continue;
- }
- inInterpretedFrame = true;
- } else {
- inInterpretedFrame = false;
- }
- yield return frame;
- }
- }
-#endif
-
- public IEnumerable<InterpretedFrameInfo> GetStackTraceDebugInfo() {
- var frame = this;
- do {
- yield return new InterpretedFrameInfo(frame.Name, frame.GetDebugInfo(frame.InstructionIndex));
- frame = frame.Parent;
- } while (frame != null);
- }
-
- internal void SaveTraceToException(Exception exception) {
- if (exception.GetData(typeof(InterpretedFrameInfo)) == null) {
- exception.SetData(typeof(InterpretedFrameInfo), new List<InterpretedFrameInfo>(GetStackTraceDebugInfo()).ToArray());
- }
- }
-
- public static InterpretedFrameInfo[] GetExceptionStackTrace(Exception exception) {
- return exception.GetData(typeof(InterpretedFrameInfo)) as InterpretedFrameInfo[];
- }
-
-#if DEBUG
- internal string[] Trace {
- get {
- var trace = new List<string>();
- var frame = this;
- do {
- trace.Add(frame.Name);
- frame = frame.Parent;
- } while (frame != null);
- return trace.ToArray();
- }
- }
-#endif
-
-#if CLR45
- internal InterpretedFrameThreadLocal Enter() {
- var currentFrame = InterpretedFrame.CurrentFrame;
- _parent = currentFrame.Value;
- currentFrame.Value = this;
- return currentFrame;
- }
-
- internal void Leave(InterpretedFrameThreadLocal currentFrame) {
- currentFrame.Value = _parent;
- }
-#else
- internal InterpretedFrameThreadLocal.StorageInfo Enter() {
- var currentFrame = InterpretedFrame.CurrentFrame.GetStorageInfo();
- _parent = currentFrame.Value;
- currentFrame.Value = this;
- return currentFrame;
- }
-
- internal void Leave(InterpretedFrameThreadLocal.StorageInfo currentFrame) {
- currentFrame.Value = _parent;
- }
-#endif
- #endregion
-
- #region Continuations
-
- public void RemoveContinuation() {
- _continuationIndex--;
- }
-
- public void PushContinuation(int continuation) {
- _continuations[_continuationIndex++] = continuation;
- }
-
- public int YieldToCurrentContinuation() {
- var target = Interpreter._labels[_continuations[_continuationIndex - 1]];
- SetStackDepth(target.StackDepth);
- return target.Index - InstructionIndex;
- }
-
- public int YieldToPendingContinuation() {
- Debug.Assert(_pendingContinuation >= 0);
-
- RuntimeLabel pendingTarget = Interpreter._labels[_pendingContinuation];
-
- // the current continuation might have higher priority (continuationIndex is the depth of the current continuation):
- if (pendingTarget.ContinuationStackDepth < _continuationIndex) {
- RuntimeLabel currentTarget = Interpreter._labels[_continuations[_continuationIndex - 1]];
- SetStackDepth(currentTarget.StackDepth);
- return currentTarget.Index - InstructionIndex;
- }
-
- SetStackDepth(pendingTarget.StackDepth);
- if (_pendingValue != Interpreter.NoValue) {
- Data[StackIndex - 1] = _pendingValue;
- }
- return pendingTarget.Index - InstructionIndex;
- }
-
- internal void PushPendingContinuation() {
- Push(_pendingContinuation);
- Push(_pendingValue);
-#if DEBUG
- _pendingContinuation = -1;
-#endif
- }
-
- internal void PopPendingContinuation() {
- _pendingValue = Pop();
- _pendingContinuation = (int)Pop();
- }
-
- private static MethodInfo _Goto;
- private static MethodInfo _VoidGoto;
-
- internal static MethodInfo GotoMethod {
- get { return _Goto ?? (_Goto = typeof(InterpretedFrame).GetMethod("Goto")); }
- }
-
- internal static MethodInfo VoidGotoMethod {
- get { return _VoidGoto ?? (_VoidGoto = typeof(InterpretedFrame).GetMethod("VoidGoto")); }
- }
-
- public int VoidGoto(int labelIndex) {
- return Goto(labelIndex, Interpreter.NoValue);
- }
-
- public int Goto(int labelIndex, object value) {
- // TODO: we know this at compile time (except for compiled loop):
- RuntimeLabel target = Interpreter._labels[labelIndex];
- if (_continuationIndex == target.ContinuationStackDepth) {
- SetStackDepth(target.StackDepth);
- if (value != Interpreter.NoValue) {
- Data[StackIndex - 1] = value;
- }
- return target.Index - InstructionIndex;
- }
-
- // if we are in the middle of executing jump we forget the previous target and replace it by a new one:
- _pendingContinuation = labelIndex;
- _pendingValue = value;
- return YieldToCurrentContinuation();
- }
-
- #endregion
-
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Interpreter.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Interpreter.cs
deleted file mode 100644
index 81c7d5b043f..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Interpreter.cs
+++ /dev/null
@@ -1,262 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Threading;
-
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-using System.Diagnostics;
-using System.Collections.Generic;
-
-namespace Microsoft.Scripting.Interpreter {
- /// <summary>
- /// A simple forth-style stack machine for executing Expression trees
- /// without the need to compile to IL and then invoke the JIT. This trades
- /// off much faster compilation time for a slower execution performance.
- /// For code that is only run a small number of times this can be a
- /// sweet spot.
- ///
- /// The core loop in the interpreter is the RunInstructions method.
- /// </summary>
- internal sealed class Interpreter {
- internal static readonly object NoValue = new object();
- internal const int RethrowOnReturn = Int32.MaxValue;
-
- // zero: sync compilation
- // negative: default
- internal readonly int _compilationThreshold;
-
- private readonly int _localCount;
- private readonly HybridReferenceDictionary<LabelTarget, BranchLabel> _labelMapping;
- private readonly Dictionary<ParameterExpression, LocalVariable> _closureVariables;
-
- private readonly InstructionArray _instructions;
- internal readonly object[] _objects;
- internal readonly RuntimeLabel[] _labels;
-
- internal readonly string _name;
- private readonly ExceptionHandler[] _handlers;
- internal readonly DebugInfo[] _debugInfos;
-
- internal Interpreter(string name, LocalVariables locals, HybridReferenceDictionary<LabelTarget, BranchLabel> labelMapping,
- InstructionArray instructions, ExceptionHandler[] handlers, DebugInfo[] debugInfos, int compilationThreshold) {
-
- _name = name;
- _localCount = locals.LocalCount;
- _closureVariables = locals.ClosureVariables;
-
- _instructions = instructions;
- _objects = instructions.Objects;
- _labels = instructions.Labels;
- _labelMapping = labelMapping;
-
- _handlers = handlers;
- _debugInfos = debugInfos;
- _compilationThreshold = compilationThreshold;
- }
-
- internal int ClosureSize {
- get {
- if (_closureVariables == null) {
- return 0;
- }
- return _closureVariables.Count;
- }
- }
-
- internal int LocalCount {
- get {
- return _localCount;
- }
- }
-
- internal bool CompileSynchronously {
- get { return _compilationThreshold <= 1; }
- }
-
- internal InstructionArray Instructions {
- get { return _instructions; }
- }
-
- internal Dictionary<ParameterExpression, LocalVariable> ClosureVariables {
- get { return _closureVariables; }
- }
-
- internal HybridReferenceDictionary<LabelTarget, BranchLabel> LabelMapping {
- get { return _labelMapping; }
- }
-
- /// <summary>
- /// Runs instructions within the given frame.
- /// </summary>
- /// <remarks>
- /// Interpreted stack frames are linked via Parent reference so that each CLR frame of this method corresponds
- /// to an interpreted stack frame in the chain. It is therefore possible to combine CLR stack traces with
- /// interpreted stack traces by aligning interpreted frames to the frames of this method.
- /// Each group of subsequent frames of Run method corresponds to a single interpreted frame.
- /// </remarks>
- [SpecialName, MethodImpl(MethodImplOptions.NoInlining)]
- public void Run(InterpretedFrame frame) {
- while (true) {
- try {
- var instructions = _instructions.Instructions;
- int index = frame.InstructionIndex;
- while (index < instructions.Length) {
- index += instructions[index].Run(frame);
- frame.InstructionIndex = index;
- }
- return;
- } catch (Exception exception) {
- switch (HandleException(frame, exception)) {
- case ExceptionHandlingResult.Rethrow: throw;
- case ExceptionHandlingResult.Continue: continue;
- case ExceptionHandlingResult.Return: return;
- }
- }
- }
- }
-
- private ExceptionHandlingResult HandleException(InterpretedFrame frame, Exception exception) {
- frame.SaveTraceToException(exception);
- ExceptionHandler handler;
- frame.InstructionIndex += GotoHandler(frame, exception, out handler);
-
- if (handler == null || handler.IsFault) {
- // run finally/fault blocks:
- Run(frame);
-
- // a finally block can throw an exception caught by a handler, which cancels the previous exception:
- if (frame.InstructionIndex == RethrowOnReturn) {
- return ExceptionHandlingResult.Rethrow;
- }
- return ExceptionHandlingResult.Return;
- }
-
-#if FEATURE_THREAD
- // stay in the current catch so that ThreadAbortException is not rethrown by CLR:
- var abort = exception as ThreadAbortException;
- if (abort != null) {
- _anyAbortException = abort;
- frame.CurrentAbortHandler = handler;
- }
-#endif
- while (true) {
- try {
- var instructions = _instructions.Instructions;
- int index = frame.InstructionIndex;
-
- while (index < instructions.Length) {
- var curInstr = instructions[index];
-
- index += curInstr.Run(frame);
- frame.InstructionIndex = index;
-
- if (curInstr is LeaveExceptionHandlerInstruction) {
- // we've completed handling of this exception
- return ExceptionHandlingResult.Continue;
- }
- }
-
- if (frame.InstructionIndex == RethrowOnReturn) {
- return ExceptionHandlingResult.Rethrow;
- }
-
- return ExceptionHandlingResult.Return;
- } catch (Exception nestedException) {
- switch (HandleException(frame, nestedException)) {
- case ExceptionHandlingResult.Rethrow: throw;
- case ExceptionHandlingResult.Continue: continue;
- case ExceptionHandlingResult.Return: return ExceptionHandlingResult.Return;
- default: throw Assert.Unreachable;
- }
- }
- }
- }
-
- enum ExceptionHandlingResult {
- Rethrow,
- Continue,
- Return
- }
-
-#if FEATURE_THREAD
- // To get to the current AbortReason object on Thread.CurrentThread
- // we need to use ExceptionState property of any ThreadAbortException instance.
- [ThreadStatic]
- private static ThreadAbortException _anyAbortException = null;
-
- internal static void AbortThreadIfRequested(InterpretedFrame frame, int targetLabelIndex) {
- var abortHandler = frame.CurrentAbortHandler;
- if (abortHandler != null && !abortHandler.IsInside(frame.Interpreter._labels[targetLabelIndex].Index)) {
- frame.CurrentAbortHandler = null;
-
- var currentThread = Thread.CurrentThread;
- if ((currentThread.ThreadState & System.Threading.ThreadState.AbortRequested) != 0) {
- Debug.Assert(_anyAbortException != null);
-
-#if FEATURE_EXCEPTION_STATE
- // The current abort reason needs to be preserved.
- currentThread.Abort(_anyAbortException.ExceptionState);
-#else
- currentThread.Abort();
-#endif
- }
- }
- }
-#else
- internal static void AbortThreadIfRequested(InterpretedFrame frame, int targetLabelIndex) {
- // nop
- }
-#endif
-
- internal ExceptionHandler GetBestHandler(int instructionIndex, Type exceptionType) {
- ExceptionHandler best = null;
- foreach (var handler in _handlers) {
- if (handler.Matches(exceptionType, instructionIndex)) {
- if (handler.IsBetterThan(best)) {
- best = handler;
- }
- }
- }
- return best;
- }
-
- internal int ReturnAndRethrowLabelIndex {
- get {
- // the last label is "return and rethrow" label:
- Debug.Assert(_labels[_labels.Length - 1].Index == RethrowOnReturn);
- return _labels.Length - 1;
- }
- }
-
- internal int GotoHandler(InterpretedFrame frame, object exception, out ExceptionHandler handler) {
- handler = GetBestHandler(frame.InstructionIndex, exception.GetType());
- if (handler == null) {
- return frame.Goto(ReturnAndRethrowLabelIndex, Interpreter.NoValue);
- } else {
- return frame.Goto(handler.LabelIndex, exception);
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightCompiler.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightCompiler.cs
deleted file mode 100644
index 779d93a1086..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightCompiler.cs
+++ /dev/null
@@ -1,1736 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-using Microsoft.Scripting.Ast;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Linq;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-#if FEATURE_REFEMIT
-using System.Reflection.Emit;
-#endif
-
-using AstUtils = Microsoft.Scripting.Ast.Utils;
-using Microsoft.Scripting.Utils;
-using Microsoft.Scripting.Runtime;
-using System.Security;
-
-namespace Microsoft.Scripting.Interpreter {
- public sealed class ExceptionHandler {
- public readonly Type ExceptionType;
- public readonly int StartIndex;
- public readonly int EndIndex;
- public readonly int LabelIndex;
- public readonly int HandlerStartIndex;
-
- public bool IsFault { get { return ExceptionType == null; } }
-
- internal ExceptionHandler(int start, int end, int labelIndex, int handlerStartIndex, Type exceptionType) {
- StartIndex = start;
- EndIndex = end;
- LabelIndex = labelIndex;
- ExceptionType = exceptionType;
- HandlerStartIndex = handlerStartIndex;
- }
-
- public bool Matches(Type exceptionType, int index) {
- if (index >= StartIndex && index < EndIndex) {
- if (ExceptionType == null || ExceptionType.IsAssignableFrom(exceptionType)) {
- return true;
- }
- }
- return false;
- }
-
- public bool IsBetterThan(ExceptionHandler other) {
- if (other == null) return true;
-
- if (StartIndex == other.StartIndex && EndIndex == other.EndIndex) {
- return HandlerStartIndex < other.HandlerStartIndex;
- }
-
- if (StartIndex > other.StartIndex) {
- Debug.Assert(EndIndex <= other.EndIndex);
- return true;
- } else if (EndIndex < other.EndIndex) {
- Debug.Assert(StartIndex == other.StartIndex);
- return true;
- } else {
- return false;
- }
- }
-
- internal bool IsInside(int index) {
- return index >= StartIndex && index < EndIndex;
- }
-
- public override string ToString() {
- return String.Format("{0} [{1}-{2}] [{3}->]",
- (IsFault ? "fault" : "catch(" + ExceptionType.Name + ")"),
- StartIndex, EndIndex,
- HandlerStartIndex
- );
- }
- }
-
- [Serializable]
- public class DebugInfo {
- // TODO: readonly
-
- public int StartLine, EndLine;
- public int Index;
- public string FileName;
- public bool IsClear;
- private static readonly DebugInfoComparer _debugComparer = new DebugInfoComparer();
-
- private class DebugInfoComparer : IComparer<DebugInfo> {
- //We allow comparison between int and DebugInfo here
- int IComparer<DebugInfo>.Compare(DebugInfo d1, DebugInfo d2) {
- if (d1.Index > d2.Index) return 1;
- else if (d1.Index == d2.Index) return 0;
- else return -1;
- }
- }
-
- public static DebugInfo GetMatchingDebugInfo(DebugInfo[] debugInfos, int index) {
- //Create a faked DebugInfo to do the search
- DebugInfo d = new DebugInfo { Index = index };
-
- //to find the closest debug info before the current index
-
- int i = Array.BinarySearch<DebugInfo>(debugInfos, d, _debugComparer);
- if (i < 0) {
- //~i is the index for the first bigger element
- //if there is no bigger element, ~i is the length of the array
- i = ~i;
- if (i == 0) {
- return null;
- }
- //return the last one that is smaller
- i = i - 1;
- }
-
- return debugInfos[i];
- }
-
- public override string ToString() {
- if (IsClear) {
- return String.Format("{0}: clear", Index);
- } else {
- return String.Format("{0}: [{1}-{2}] '{3}'", Index, StartLine, EndLine, FileName);
- }
- }
- }
-
- // TODO:
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
- [Serializable]
- public struct InterpretedFrameInfo {
- public readonly string MethodName;
-
- // TODO:
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
- public readonly DebugInfo DebugInfo;
-
- public InterpretedFrameInfo(string methodName, DebugInfo info) {
- MethodName = methodName;
- DebugInfo = info;
- }
-
- public override string ToString() {
- return MethodName + (DebugInfo != null ? ": " + DebugInfo.ToString() : null);
- }
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
- public sealed class LightCompiler {
- internal const int DefaultCompilationThreshold = 32;
-
- // zero: sync compilation
- private readonly int _compilationThreshold;
-
- private readonly InstructionList _instructions;
- private readonly LocalVariables _locals = new LocalVariables();
-
- private readonly List<ExceptionHandler> _handlers = new List<ExceptionHandler>();
-
- private readonly List<DebugInfo> _debugInfos = new List<DebugInfo>();
- private readonly HybridReferenceDictionary<LabelTarget, LabelInfo> _treeLabels = new HybridReferenceDictionary<LabelTarget, LabelInfo>();
- private LabelScopeInfo _labelBlock = new LabelScopeInfo(null, LabelScopeKind.Lambda);
-
- private readonly Stack<ParameterExpression> _exceptionForRethrowStack = new Stack<ParameterExpression>();
-
- // Set to true to force compiliation of this lambda.
- // This disables the interpreter for this lambda. We still need to
- // walk it, however, to resolve variables closed over from the parent
- // lambdas (because they may be interpreted).
- private bool _forceCompile;
-
- private readonly LightCompiler _parent;
-
- private static LocalDefinition[] EmptyLocals = new LocalDefinition[0];
-
- internal LightCompiler(int compilationThreshold) {
- _instructions = new InstructionList();
- _compilationThreshold = compilationThreshold < 0 ? DefaultCompilationThreshold : compilationThreshold;
- }
-
- private LightCompiler(LightCompiler parent)
- : this(parent._compilationThreshold) {
- _parent = parent;
- }
-
- public InstructionList Instructions {
- get { return _instructions; }
- }
-
- public LocalVariables Locals {
- get { return _locals; }
- }
-
- internal static Expression Unbox(Expression strongBoxExpression) {
- return Expression.Field(strongBoxExpression, typeof(StrongBox<object>).GetDeclaredField("Value"));
- }
-
- internal LightDelegateCreator CompileTop(LambdaExpression node) {
- foreach (var p in node.Parameters) {
- var local = _locals.DefineLocal(p, 0);
- _instructions.EmitInitializeParameter(local.Index);
- }
-
- Compile(node.Body);
-
- // pop the result of the last expression:
- if (node.Body.Type != typeof(void) && node.ReturnType == typeof(void)) {
- _instructions.EmitPop();
- }
-
- Debug.Assert(_instructions.CurrentStackDepth == (node.ReturnType != typeof(void) ? 1 : 0));
-
- return new LightDelegateCreator(MakeInterpreter(node.Name), node);
- }
-
- internal LightDelegateCreator CompileTop(LightLambdaExpression node) {
- foreach (var p in node.Parameters) {
- var local = _locals.DefineLocal(p, 0);
- _instructions.EmitInitializeParameter(local.Index);
- }
-
- Compile(node.Body);
-
- // pop the result of the last expression:
- if (node.Body.Type != typeof(void) && node.ReturnType == typeof(void)) {
- _instructions.EmitPop();
- }
-
- Debug.Assert(_instructions.CurrentStackDepth == (node.ReturnType != typeof(void) ? 1 : 0));
-
- return new LightDelegateCreator(MakeInterpreter(node.Name), node);
- }
-
- private Interpreter MakeInterpreter(string lambdaName) {
- if (_forceCompile) {
- return null;
- }
-
- var handlers = _handlers.ToArray();
- var debugInfos = _debugInfos.ToArray();
-
- return new Interpreter(lambdaName, _locals, GetBranchMapping(), _instructions.ToArray(), handlers, debugInfos, _compilationThreshold);
- }
-
-
- private void CompileConstantExpression(Expression expr) {
- var node = (ConstantExpression)expr;
- _instructions.EmitLoad(node.Value, node.Type);
- }
-
- private void CompileDefaultExpression(Expression expr) {
- CompileDefaultExpression(expr.Type);
- }
-
- private void CompileDefaultExpression(Type type) {
- if (type != typeof(void)) {
- if (type.IsValueType()) {
- object value = ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(type);
- if (value != null) {
- _instructions.EmitLoad(value);
- } else {
- _instructions.EmitDefaultValue(type);
- }
- } else {
- _instructions.EmitLoad(null);
- }
- }
- }
-
- private LocalVariable EnsureAvailableForClosure(ParameterExpression expr) {
- LocalVariable local;
- if (_locals.TryGetLocalOrClosure(expr, out local)) {
- if (!local.InClosure && !local.IsBoxed) {
- _locals.Box(expr, _instructions);
- }
- return local;
- } else if (_parent != null) {
- _parent.EnsureAvailableForClosure(expr);
- return _locals.AddClosureVariable(expr);
- } else {
- throw new InvalidOperationException("unbound variable: " + expr);
- }
- }
-
- private void EnsureVariable(ParameterExpression variable) {
- if (!_locals.ContainsVariable(variable)) {
- EnsureAvailableForClosure(variable);
- }
- }
-
- private LocalVariable ResolveLocal(ParameterExpression variable) {
- LocalVariable local;
- if (!_locals.TryGetLocalOrClosure(variable, out local)) {
- local = EnsureAvailableForClosure(variable);
- }
- return local;
- }
-
- public void CompileGetVariable(ParameterExpression variable) {
- LocalVariable local = ResolveLocal(variable);
-
- if (local.InClosure) {
- _instructions.EmitLoadLocalFromClosure(local.Index);
- } else if (local.IsBoxed) {
- _instructions.EmitLoadLocalBoxed(local.Index);
- } else {
- _instructions.EmitLoadLocal(local.Index);
- }
-
- _instructions.SetDebugCookie(variable.Name);
- }
-
- public void CompileGetBoxedVariable(ParameterExpression variable) {
- LocalVariable local = ResolveLocal(variable);
-
- if (local.InClosure) {
- _instructions.EmitLoadLocalFromClosureBoxed(local.Index);
- } else {
- Debug.Assert(local.IsBoxed);
- _instructions.EmitLoadLocal(local.Index);
- }
-
- _instructions.SetDebugCookie(variable.Name);
- }
-
- public void CompileSetVariable(ParameterExpression variable, bool isVoid) {
- LocalVariable local = ResolveLocal(variable);
-
- if (local.InClosure) {
- if (isVoid) {
- _instructions.EmitStoreLocalToClosure(local.Index);
- } else {
- _instructions.EmitAssignLocalToClosure(local.Index);
- }
- } else if (local.IsBoxed) {
- if (isVoid) {
- _instructions.EmitStoreLocalBoxed(local.Index);
- } else {
- _instructions.EmitAssignLocalBoxed(local.Index);
- }
- } else {
- if (isVoid) {
- _instructions.EmitStoreLocal(local.Index);
- } else {
- _instructions.EmitAssignLocal(local.Index);
- }
- }
-
- _instructions.SetDebugCookie(variable.Name);
- }
-
- public void CompileParameterExpression(Expression expr) {
- var node = (ParameterExpression)expr;
- CompileGetVariable(node);
- }
-
- private void CompileBlockExpression(Expression expr, bool asVoid) {
- var node = (BlockExpression)expr;
- var end = CompileBlockStart(node);
-
- var lastExpression = node.Expressions[node.Expressions.Count - 1];
- Compile(lastExpression, asVoid);
- CompileBlockEnd(end);
- }
-
- private LocalDefinition[] CompileBlockStart(BlockExpression node) {
- var start = _instructions.Count;
-
- LocalDefinition[] locals;
- var variables = node.Variables;
- if (variables.Count != 0) {
- // TODO: basic flow analysis so we don't have to initialize all
- // variables.
- locals = new LocalDefinition[variables.Count];
- int localCnt = 0;
- foreach (var variable in variables) {
- var local = _locals.DefineLocal(variable, start);
- locals[localCnt++] = local;
-
- _instructions.EmitInitializeLocal(local.Index, variable.Type);
- _instructions.SetDebugCookie(variable.Name);
- }
- } else {
- locals = EmptyLocals;
- }
-
- for (int i = 0; i < node.Expressions.Count - 1; i++) {
- CompileAsVoid(node.Expressions[i]);
- }
- return locals;
- }
-
- private void CompileBlockEnd(LocalDefinition[] locals) {
- foreach (var local in locals) {
- _locals.UndefineLocal(local, _instructions.Count);
- }
- }
-
- private void CompileIndexExpression(Expression expr) {
- var index = (IndexExpression)expr;
-
- // instance:
- if (index.Object != null) {
- Compile(index.Object);
- }
-
- // indexes, byref args not allowed.
- foreach (var arg in index.Arguments) {
- Compile(arg);
- }
-
- if (index.Indexer != null) {
- EmitCall(index.Indexer.GetGetMethod(true));
- } else if (index.Arguments.Count != 1) {
- EmitCall(index.Object.Type.GetMethod("Get", BindingFlags.Public | BindingFlags.Instance));
- } else {
- _instructions.EmitGetArrayItem(index.Object.Type);
- }
- }
-
- private void CompileIndexAssignment(BinaryExpression node, bool asVoid) {
- var index = (IndexExpression)node.Left;
-
- if (!asVoid) {
- throw new NotImplementedException();
- }
-
- // instance:
- if (index.Object != null) {
- Compile(index.Object);
- }
-
- // indexes, byref args not allowed.
- foreach (var arg in index.Arguments) {
- Compile(arg);
- }
-
- // value:
- Compile(node.Right);
-
- if (index.Indexer != null) {
- EmitCall(index.Indexer.GetSetMethod(true));
- } else if (index.Arguments.Count != 1) {
- EmitCall(index.Object.Type.GetMethod("Set", BindingFlags.Public | BindingFlags.Instance));
- } else {
- _instructions.EmitSetArrayItem(index.Object.Type);
- }
- }
-
- private void CompileMemberAssignment(BinaryExpression node, bool asVoid) {
- var member = (MemberExpression)node.Left;
-
- PropertyInfo pi = member.Member as PropertyInfo;
- if (pi != null) {
- var method = pi.GetSetMethod(true);
- Compile(member.Expression);
- Compile(node.Right);
-
- int start = _instructions.Count;
- if (!asVoid) {
- LocalDefinition local = _locals.DefineLocal(Expression.Parameter(node.Right.Type), start);
- _instructions.EmitAssignLocal(local.Index);
- EmitCall(method);
- _instructions.EmitLoadLocal(local.Index);
- _locals.UndefineLocal(local, _instructions.Count);
- } else {
- EmitCall(method);
- }
- return;
- }
-
- FieldInfo fi = member.Member as FieldInfo;
- if (fi != null) {
- if (member.Expression != null) {
- Compile(member.Expression);
- }
- Compile(node.Right);
-
- int start = _instructions.Count;
- if (!asVoid) {
- LocalDefinition local = _locals.DefineLocal(Expression.Parameter(node.Right.Type), start);
- _instructions.EmitAssignLocal(local.Index);
- _instructions.EmitStoreField(fi);
- _instructions.EmitLoadLocal(local.Index);
- _locals.UndefineLocal(local, _instructions.Count);
- } else {
- _instructions.EmitStoreField(fi);
- }
- return;
- }
-
- throw new NotImplementedException();
- }
-
- private void CompileVariableAssignment(BinaryExpression node, bool asVoid) {
- this.Compile(node.Right);
-
- var target = (ParameterExpression)node.Left;
- CompileSetVariable(target, asVoid);
- }
-
- private void CompileAssignBinaryExpression(Expression expr, bool asVoid) {
- var node = (BinaryExpression)expr;
-
- switch (node.Left.NodeType) {
- case ExpressionType.Index:
- CompileIndexAssignment(node, asVoid);
- break;
-
- case ExpressionType.MemberAccess:
- CompileMemberAssignment(node, asVoid);
- break;
-
- case ExpressionType.Parameter:
- case ExpressionType.Extension:
- CompileVariableAssignment(node, asVoid);
- break;
-
- default:
- throw new InvalidOperationException("Invalid lvalue for assignment: " + node.Left.NodeType);
- }
- }
-
- private void CompileBinaryExpression(Expression expr) {
- var node = (BinaryExpression)expr;
-
- if (node.Method != null) {
- Compile(node.Left);
- Compile(node.Right);
- EmitCall(node.Method);
- } else {
- switch (node.NodeType) {
- case ExpressionType.ArrayIndex:
- Debug.Assert(node.Right.Type == typeof(int));
- Compile(node.Left);
- Compile(node.Right);
- _instructions.EmitGetArrayItem(node.Left.Type);
- return;
-
- case ExpressionType.Add:
- case ExpressionType.AddChecked:
- case ExpressionType.Subtract:
- case ExpressionType.SubtractChecked:
- case ExpressionType.Multiply:
- case ExpressionType.MultiplyChecked:
- case ExpressionType.Divide:
- case ExpressionType.Modulo:
- CompileArithmetic(node.NodeType, node.Left, node.Right);
- return;
-
- case ExpressionType.Equal:
- CompileEqual(node.Left, node.Right, node.IsLiftedToNull);
- return;
-
- case ExpressionType.NotEqual:
- CompileNotEqual(node.Left, node.Right, node.IsLiftedToNull);
- return;
-
- case ExpressionType.LessThan:
- case ExpressionType.LessThanOrEqual:
- case ExpressionType.GreaterThan:
- case ExpressionType.GreaterThanOrEqual:
- CompileComparison(node.NodeType, node.Left, node.Right, node.IsLiftedToNull);
- return;
-
- case ExpressionType.LeftShift:
- case ExpressionType.RightShift:
- CompileShift(node.NodeType, node.Left, node.Right, node.IsLifted);
- return;
-
- case ExpressionType.And:
- case ExpressionType.Or:
- case ExpressionType.ExclusiveOr:
- CompileLogical(node.NodeType, node.Left, node.Right, node.IsLifted);
- return;
-
- default:
- throw new NotImplementedException(node.NodeType.ToString());
- }
- }
- }
-
- private void CompileEqual(Expression left, Expression right, bool liftedResult) {
- Debug.Assert(left.Type == right.Type || !left.Type.IsValueType() && !right.Type.IsValueType());
- Compile(left);
- Compile(right);
- _instructions.EmitEqual(left.Type, liftedResult);
- }
-
- private void CompileNotEqual(Expression left, Expression right, bool liftedResult) {
- Debug.Assert(left.Type == right.Type || !left.Type.IsValueType() && !right.Type.IsValueType());
- Compile(left);
- Compile(right);
- _instructions.EmitNotEqual(left.Type, liftedResult);
- }
-
- private void CompileComparison(ExpressionType nodeType, Expression left, Expression right, bool liftedResult) {
- Debug.Assert(left.Type == right.Type && TypeUtils.IsNumeric(left.Type));
-
- Compile(left);
- Compile(right);
-
- switch (nodeType) {
- case ExpressionType.LessThan: _instructions.EmitLessThan(left.Type, liftedResult); break;
- case ExpressionType.LessThanOrEqual: _instructions.EmitLessThanOrEqual(left.Type, liftedResult); break;
- case ExpressionType.GreaterThan: _instructions.EmitGreaterThan(left.Type, liftedResult); break;
- case ExpressionType.GreaterThanOrEqual: _instructions.EmitGreaterThanOrEqual(left.Type, liftedResult); break;
- default: throw Assert.Unreachable;
- }
- }
-
- private void CompileArithmetic(ExpressionType nodeType, Expression left, Expression right) {
- Debug.Assert(left.Type == right.Type && TypeUtils.IsArithmetic(left.Type));
- Compile(left);
- Compile(right);
- switch (nodeType) {
- case ExpressionType.Add: _instructions.EmitAdd(left.Type, false); break;
- case ExpressionType.AddChecked: _instructions.EmitAdd(left.Type, true); break;
- case ExpressionType.Subtract: _instructions.EmitSub(left.Type, false); break;
- case ExpressionType.SubtractChecked: _instructions.EmitSub(left.Type, true); break;
- case ExpressionType.Multiply: _instructions.EmitMul(left.Type, false); break;
- case ExpressionType.MultiplyChecked: _instructions.EmitMul(left.Type, true); break;
- case ExpressionType.Divide: _instructions.EmitDiv(left.Type); break;
- case ExpressionType.Modulo: _instructions.EmitMod(left.Type); break;
- default: throw Assert.Unreachable;
- }
- }
-
- private void CompileShift(ExpressionType nodeType, Expression left, Expression right, bool lifted) {
- Debug.Assert(right.Type == typeof (int) || right.Type == typeof (int?));
- Compile(left);
- Compile(right);
- switch (nodeType) {
- case ExpressionType.LeftShift: _instructions.EmitShl(TypeUtils.GetNonNullableType (left.Type), lifted); break;
- case ExpressionType.RightShift: _instructions.EmitShr(TypeUtils.GetNonNullableType (left.Type), lifted); break;
- default: throw Assert.Unreachable;
- }
- }
-
- private void CompileLogical(ExpressionType nodeType, Expression left, Expression right, bool lifted) {
- Debug.Assert(left.Type == right.Type); // && TypeUtils.IsIntegerOrBool(left.Type));
- Compile(left);
- Compile(right);
- switch (nodeType) {
- case ExpressionType.And: _instructions.EmitAnd(TypeUtils.GetNonNullableType (left.Type), lifted); break;
- case ExpressionType.Or: _instructions.EmitOr(TypeUtils.GetNonNullableType (left.Type), lifted); break;
- case ExpressionType.ExclusiveOr: _instructions.EmitExclusiveOr(TypeUtils.GetNonNullableType (left.Type), lifted); break;
- default: throw Assert.Unreachable;
- }
- }
-
- private void CompileConvertUnaryExpression(Expression expr) {
- var node = (UnaryExpression)expr;
- if (node.Method != null) {
- Compile(node.Operand);
-
- if (node.IsLifted)
- throw new NotImplementedException ();
-
- // We should be able to ignore Int32ToObject
- if (node.Method != Runtime.ScriptingRuntimeHelpers.Int32ToObjectMethod) {
- EmitCall(node.Method);
- }
- } else if (node.Type == typeof(void)) {
- CompileAsVoid(node.Operand);
- } else {
- Compile(node.Operand);
- CompileConvertToType(node.Operand.Type, node.Type, node.NodeType == ExpressionType.ConvertChecked);
- }
- }
-
- private void CompileConvertToType(Type typeFrom, Type typeTo, bool isChecked) {
- Debug.Assert(typeFrom != typeof(void) && typeTo != typeof(void));
-
- if (TypeUtils.AreEquivalent(typeTo, typeFrom)) {
- return;
- }
-
- if (TypeUtils.IsNullableType (typeTo)) {
- typeFrom = TypeUtils.GetNonNullableType (typeFrom);
- typeTo = TypeUtils.GetNonNullableType (typeTo);
-
- var nullValue = _instructions.MakeLabel();
- var end = _instructions.MakeLabel();
-
- _instructions.EmitDup ();
- _instructions.EmitBranchNull(nullValue);
- CompileConvertToType (typeFrom, typeTo, isChecked);
- _instructions.EmitWrap (typeTo);
- _instructions.MarkLabel(nullValue);
- return;
- }
-
- if (TypeUtils.IsNullableType (typeFrom)) {
- if (typeTo.IsClass)
- return;
-
- // TODO: should throw same exception as (int)(int?)null
- throw new NotImplementedException ();
- }
-
- TypeCode from = typeFrom.GetTypeCode();
- TypeCode to = typeTo.GetTypeCode();
- if (TypeUtils.IsNumeric(from) && TypeUtils.IsNumeric(to)) {
- if (isChecked) {
- _instructions.EmitNumericConvertChecked(from, to);
- } else {
- _instructions.EmitNumericConvertUnchecked(from, to);
- }
- return;
- }
-
- // TODO: Conversions to a super-class or implemented interfaces are no-op.
- // A conversion to a non-implemented interface or an unrelated class, etc. should fail.
- return;
- }
-
- private void CompileNegateExpression(UnaryExpression node, bool @checked, bool lifted) {
- Compile(node.Operand);
- _instructions.EmitNegate(TypeUtils.GetNonNullableType (node.Type), @checked, lifted);
- }
-
- private void CompileNotExpression(UnaryExpression node, bool lifted) {
- Compile(node.Operand);
- _instructions.EmitNot(TypeUtils.GetNonNullableType (node.Type), lifted);
- }
-
- private void CompileUnaryExpression(Expression expr) {
- var node = (UnaryExpression)expr;
-
- if (node.Method != null) {
- Compile(node.Operand);
- EmitCall(node.Method);
- } else {
- switch (node.NodeType) {
- case ExpressionType.ArrayLength:
- Compile(node.Operand);
- _instructions.EmitGetArrayLength (node.Type);
- return;
- case ExpressionType.Negate:
- CompileNegateExpression(node, false, node.IsLifted);
- return;
- case ExpressionType.NegateChecked:
- CompileNegateExpression(node, true, node.IsLifted);
- return;
- case ExpressionType.Not:
- CompileNotExpression(node, node.IsLifted);
- return;
- case ExpressionType.UnaryPlus:
- // unary plus is a nop:
- Compile(node.Operand);
- return;
- case ExpressionType.TypeAs:
- CompileTypeAsExpression(node);
- return;
- default:
- throw new NotImplementedException(node.NodeType.ToString());
- }
- }
- }
-
- private void CompileAndAlsoBinaryExpression(Expression expr) {
- CompileLogicalBinaryExpression(expr, true);
- }
-
- private void CompileOrElseBinaryExpression(Expression expr) {
- CompileLogicalBinaryExpression(expr, false);
- }
-
- private void CompileLogicalBinaryExpression(Expression expr, bool andAlso) {
- var node = (BinaryExpression)expr;
- if (node.Method != null) {
- throw new NotImplementedException();
- }
-
- Debug.Assert(node.Left.Type == node.Right.Type);
-
- if (node.Left.Type == typeof(bool)) {
- var elseLabel = _instructions.MakeLabel();
- var endLabel = _instructions.MakeLabel();
- Compile(node.Left);
- if (andAlso) {
- _instructions.EmitBranchFalse(elseLabel);
- } else {
- _instructions.EmitBranchTrue(elseLabel);
- }
- Compile(node.Right);
- _instructions.EmitBranch(endLabel, false, true);
- _instructions.MarkLabel(elseLabel);
- _instructions.EmitLoad(!andAlso);
- _instructions.MarkLabel(endLabel);
- return;
- }
-
- Debug.Assert(node.Left.Type == typeof(bool?));
- throw new NotImplementedException();
- }
-
- private void CompileConditionalExpression(Expression expr, bool asVoid) {
- var node = (ConditionalExpression)expr;
- Compile(node.Test);
-
- if (node.IfTrue == AstUtils.Empty()) {
- var endOfFalse = _instructions.MakeLabel();
- _instructions.EmitBranchTrue(endOfFalse);
- Compile(node.IfFalse, asVoid);
- _instructions.MarkLabel(endOfFalse);
- } else {
- var endOfTrue = _instructions.MakeLabel();
- _instructions.EmitBranchFalse(endOfTrue);
- Compile(node.IfTrue, asVoid);
-
- if (node.IfFalse != AstUtils.Empty()) {
- var endOfFalse = _instructions.MakeLabel();
- _instructions.EmitBranch(endOfFalse, false, !asVoid);
- _instructions.MarkLabel(endOfTrue);
- Compile(node.IfFalse, asVoid);
- _instructions.MarkLabel(endOfFalse);
- } else {
- _instructions.MarkLabel(endOfTrue);
- }
- }
- }
-
- #region Loops
-
- private void CompileLoopExpression(Expression expr) {
- var node = (LoopExpression)expr;
- var enterLoop = new EnterLoopInstruction(node, _locals, _compilationThreshold, _instructions.Count);
-
- PushLabelBlock(LabelScopeKind.Statement);
- LabelInfo breakLabel = DefineLabel(node.BreakLabel);
- LabelInfo continueLabel = DefineLabel(node.ContinueLabel);
-
- _instructions.MarkLabel(continueLabel.GetLabel(this));
-
- // emit loop body:
- _instructions.Emit(enterLoop);
- CompileAsVoid(node.Body);
-
- // emit loop branch:
- _instructions.EmitBranch(continueLabel.GetLabel(this), expr.Type != typeof(void), false);
-
- _instructions.MarkLabel(breakLabel.GetLabel(this));
-
- PopLabelBlock(LabelScopeKind.Statement);
-
- enterLoop.FinishLoop(_instructions.Count);
- }
-
- #endregion
-
- private void CompileSwitchExpression(Expression expr) {
- var node = (SwitchExpression)expr;
-
- // Currently only supports int test values, with no method
- if (node.SwitchValue.Type != typeof(int) || node.Comparison != null) {
- throw new NotImplementedException();
- }
-
- // Test values must be constant
- if (!node.Cases.All(c => c.TestValues.All(t => t is ConstantExpression))) {
- throw new NotImplementedException();
- }
- LabelInfo end = DefineLabel(null);
- bool hasValue = node.Type != typeof(void);
-
- Compile(node.SwitchValue);
- var caseDict = new Dictionary<int, int>();
- int switchIndex = _instructions.Count;
- _instructions.EmitSwitch(caseDict);
-
- if (node.DefaultBody != null) {
- Compile(node.DefaultBody);
- } else {
- Debug.Assert(!hasValue);
- }
- _instructions.EmitBranch(end.GetLabel(this), false, hasValue);
-
- for (int i = 0; i < node.Cases.Count; i++) {
- var switchCase = node.Cases[i];
-
- int caseOffset = _instructions.Count - switchIndex;
- foreach (ConstantExpression testValue in switchCase.TestValues) {
- caseDict[(int)testValue.Value] = caseOffset;
- }
-
- Compile(switchCase.Body);
-
- if (i < node.Cases.Count - 1) {
- _instructions.EmitBranch(end.GetLabel(this), false, hasValue);
- }
- }
-
- _instructions.MarkLabel(end.GetLabel(this));
- }
-
- private void CompileLabelExpression(Expression expr) {
- var node = (LabelExpression)expr;
-
- // If we're an immediate child of a block, our label will already
- // be defined. If not, we need to define our own block so this
- // label isn't exposed except to its own child expression.
- LabelInfo label = null;
-
- if (_labelBlock.Kind == LabelScopeKind.Block) {
- _labelBlock.TryGetLabelInfo(node.Target, out label);
-
- // We're in a block but didn't find our label, try switch
- if (label == null && _labelBlock.Parent.Kind == LabelScopeKind.Switch) {
- _labelBlock.Parent.TryGetLabelInfo(node.Target, out label);
- }
-
- // if we're in a switch or block, we should've found the label
- Debug.Assert(label != null);
- }
-
- if (label == null) {
- label = DefineLabel(node.Target);
- }
-
- if (node.DefaultValue != null) {
- if (node.Target.Type == typeof(void)) {
- CompileAsVoid(node.DefaultValue);
- } else {
- Compile(node.DefaultValue);
- }
- }
-
- _instructions.MarkLabel(label.GetLabel(this));
- }
-
- private void CompileGotoExpression(Expression expr) {
- var node = (GotoExpression)expr;
- var labelInfo = ReferenceLabel(node.Target);
-
- if (node.Value != null) {
- Compile(node.Value);
- }
-
- _instructions.EmitGoto(labelInfo.GetLabel(this), node.Type != typeof(void), node.Value != null && node.Value.Type != typeof(void));
- }
-
- public BranchLabel GetBranchLabel(LabelTarget target) {
- return ReferenceLabel(target).GetLabel(this);
- }
-
- public void PushLabelBlock(LabelScopeKind type) {
- _labelBlock = new LabelScopeInfo(_labelBlock, type);
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")]
- public void PopLabelBlock(LabelScopeKind kind) {
- Debug.Assert(_labelBlock != null && _labelBlock.Kind == kind);
- _labelBlock = _labelBlock.Parent;
- }
-
- private LabelInfo EnsureLabel(LabelTarget node) {
- LabelInfo result;
- if (!_treeLabels.TryGetValue(node, out result)) {
- _treeLabels[node] = result = new LabelInfo(node);
- }
- return result;
- }
-
- private LabelInfo ReferenceLabel(LabelTarget node) {
- LabelInfo result = EnsureLabel(node);
- result.Reference(_labelBlock);
- return result;
- }
-
- internal LabelInfo DefineLabel(LabelTarget node) {
- if (node == null) {
- return new LabelInfo(null);
- }
- LabelInfo result = EnsureLabel(node);
- result.Define(_labelBlock);
- return result;
- }
-
- private bool TryPushLabelBlock(Expression node) {
- // Anything that is "statement-like" -- e.g. has no associated
- // stack state can be jumped into, with the exception of try-blocks
- // We indicate this by a "Block"
- //
- // Otherwise, we push an "Expression" to indicate that it can't be
- // jumped into
- switch (node.NodeType) {
- default:
- if (_labelBlock.Kind != LabelScopeKind.Expression) {
- PushLabelBlock(LabelScopeKind.Expression);
- return true;
- }
- return false;
- case ExpressionType.Label:
- // LabelExpression is a bit special, if it's directly in a
- // block it becomes associate with the block's scope. Same
- // thing if it's in a switch case body.
- if (_labelBlock.Kind == LabelScopeKind.Block) {
- var label = ((LabelExpression)node).Target;
- if (_labelBlock.ContainsTarget(label)) {
- return false;
- }
- if (_labelBlock.Parent.Kind == LabelScopeKind.Switch &&
- _labelBlock.Parent.ContainsTarget(label)) {
- return false;
- }
- }
- PushLabelBlock(LabelScopeKind.Statement);
- return true;
- case ExpressionType.Block:
- PushLabelBlock(LabelScopeKind.Block);
- // Labels defined immediately in the block are valid for
- // the whole block.
- if (_labelBlock.Parent.Kind != LabelScopeKind.Switch) {
- DefineBlockLabels(node);
- }
- return true;
- case ExpressionType.Switch:
- PushLabelBlock(LabelScopeKind.Switch);
- // Define labels inside of the switch cases so theyare in
- // scope for the whole switch. This allows "goto case" and
- // "goto default" to be considered as local jumps.
- var @switch = (SwitchExpression)node;
- foreach (SwitchCase c in @switch.Cases) {
- DefineBlockLabels(c.Body);
- }
- DefineBlockLabels(@switch.DefaultBody);
- return true;
-
- // Remove this when Convert(Void) goes away.
- case ExpressionType.Convert:
- if (node.Type != typeof(void)) {
- // treat it as an expression
- goto default;
- }
- PushLabelBlock(LabelScopeKind.Statement);
- return true;
-
- case ExpressionType.Conditional:
- case ExpressionType.Loop:
- case ExpressionType.Goto:
- PushLabelBlock(LabelScopeKind.Statement);
- return true;
- }
- }
-
- private void DefineBlockLabels(Expression node) {
- var block = node as BlockExpression;
- if (block == null) {
- return;
- }
-
- for (int i = 0, n = block.Expressions.Count; i < n; i++) {
- Expression e = block.Expressions[i];
-
- var label = e as LabelExpression;
- if (label != null) {
- DefineLabel(label.Target);
- }
- }
- }
-
- private HybridReferenceDictionary<LabelTarget, BranchLabel> GetBranchMapping() {
- var newLabelMapping = new HybridReferenceDictionary<LabelTarget, BranchLabel>(_treeLabels.Count);
- foreach (var kvp in _treeLabels) {
- newLabelMapping[kvp.Key] = kvp.Value.GetLabel(this);
- }
- return newLabelMapping;
- }
-
- private void CompileThrowUnaryExpression(Expression expr, bool asVoid) {
- var node = (UnaryExpression)expr;
-
- if (node.Operand == null) {
- CompileParameterExpression(_exceptionForRethrowStack.Peek());
- if (asVoid) {
- _instructions.EmitRethrowVoid();
- } else {
- _instructions.EmitRethrow();
- }
- } else {
- Compile(node.Operand);
- if (asVoid) {
- _instructions.EmitThrowVoid();
- } else {
- _instructions.EmitThrow();
- }
- }
-
- }
-
- // TODO: remove (replace by true fault support)
- private bool EndsWithRethrow(Expression expr) {
- if (expr.NodeType == ExpressionType.Throw) {
- var node = (UnaryExpression)expr;
- return node.Operand == null;
- }
-
- BlockExpression block = expr as BlockExpression;
- if (block != null) {
- return EndsWithRethrow(block.Expressions[block.Expressions.Count - 1]);
- }
- return false;
- }
-
-
- // TODO: remove (replace by true fault support)
- private void CompileAsVoidRemoveRethrow(Expression expr) {
- int stackDepth = _instructions.CurrentStackDepth;
-
- if (expr.NodeType == ExpressionType.Throw) {
- Debug.Assert(((UnaryExpression)expr).Operand == null);
- return;
- }
-
- var node = (BlockExpression)expr;
- var end = CompileBlockStart(node);
-
- CompileAsVoidRemoveRethrow(node.Expressions[node.Expressions.Count - 1]);
-
- Debug.Assert(stackDepth == _instructions.CurrentStackDepth);
-
- CompileBlockEnd(end);
- }
-
- private void CompileTryExpression(Expression expr) {
- var node = (TryExpression)expr;
-
- BranchLabel end = _instructions.MakeLabel();
- BranchLabel gotoEnd = _instructions.MakeLabel();
-
- int tryStart = _instructions.Count;
-
- BranchLabel startOfFinally = null;
- if (node.Finally != null) {
- startOfFinally = _instructions.MakeLabel();
- _instructions.EmitEnterTryFinally(startOfFinally);
- }
-
- PushLabelBlock(LabelScopeKind.Try);
- Compile(node.Body);
-
- bool hasValue = node.Body.Type != typeof(void);
- int tryEnd = _instructions.Count;
-
- // handlers jump here:
- _instructions.MarkLabel(gotoEnd);
- _instructions.EmitGoto(end, hasValue, hasValue);
-
- // keep the result on the stack:
- if (node.Handlers.Count > 0) {
- // TODO: emulates faults (replace by true fault support)
- if (node.Finally == null && node.Handlers.Count == 1) {
- var handler = node.Handlers[0];
- if (handler.Filter == null && handler.Test == typeof(Exception) && handler.Variable == null) {
- if (EndsWithRethrow(handler.Body)) {
- if (hasValue) {
- _instructions.EmitEnterExceptionHandlerNonVoid();
- } else {
- _instructions.EmitEnterExceptionHandlerVoid();
- }
-
- // at this point the stack balance is prepared for the hidden exception variable:
- int handlerLabel = _instructions.MarkRuntimeLabel();
- int handlerStart = _instructions.Count;
-
- CompileAsVoidRemoveRethrow(handler.Body);
- _instructions.EmitLeaveFault(hasValue);
- _instructions.MarkLabel(end);
-
- _handlers.Add(new ExceptionHandler(tryStart, tryEnd, handlerLabel, handlerStart, null));
- PopLabelBlock(LabelScopeKind.Try);
- return;
- }
- }
- }
-
- foreach (var handler in node.Handlers) {
- PushLabelBlock(LabelScopeKind.Catch);
-
- if (handler.Filter != null) {
- //PushLabelBlock(LabelScopeKind.Filter);
- throw new NotImplementedException();
- //PopLabelBlock(LabelScopeKind.Filter);
- }
-
- var parameter = handler.Variable ?? Expression.Parameter(handler.Test);
-
- var local = _locals.DefineLocal(parameter, _instructions.Count);
- _exceptionForRethrowStack.Push(parameter);
-
- // add a stack balancing nop instruction (exception handling pushes the current exception):
- if (hasValue) {
- _instructions.EmitEnterExceptionHandlerNonVoid();
- } else {
- _instructions.EmitEnterExceptionHandlerVoid();
- }
-
- // at this point the stack balance is prepared for the hidden exception variable:
- int handlerLabel = _instructions.MarkRuntimeLabel();
- int handlerStart = _instructions.Count;
-
- CompileSetVariable(parameter, true);
- Compile(handler.Body);
-
- _exceptionForRethrowStack.Pop();
-
- // keep the value of the body on the stack:
- Debug.Assert(hasValue == (handler.Body.Type != typeof(void)));
- _instructions.EmitLeaveExceptionHandler(hasValue, gotoEnd);
-
- _handlers.Add(new ExceptionHandler(tryStart, tryEnd, handlerLabel, handlerStart, handler.Test));
-
- PopLabelBlock(LabelScopeKind.Catch);
-
- _locals.UndefineLocal(local, _instructions.Count);
- }
-
- if (node.Fault != null) {
- throw new NotImplementedException();
- }
- }
-
- if (node.Finally != null) {
- PushLabelBlock(LabelScopeKind.Finally);
-
- _instructions.MarkLabel(startOfFinally);
- _instructions.EmitEnterFinally();
- CompileAsVoid(node.Finally);
- _instructions.EmitLeaveFinally();
-
- PopLabelBlock(LabelScopeKind.Finally);
- }
-
- _instructions.MarkLabel(end);
-
- PopLabelBlock(LabelScopeKind.Try);
- }
-
- private void CompileDynamicExpression(Expression expr) {
- var node = (DynamicExpression)expr;
-
- foreach (var arg in node.Arguments) {
- Compile(arg);
- }
-
- _instructions.EmitDynamic(node.DelegateType, node.Binder);
- }
-
- private void CompileMethodCallExpression(Expression expr) {
- var node = (MethodCallExpression)expr;
-
- var parameters = node.Method.GetParameters();
-
- // TODO:
- // Support pass by reference.
- // Note that LoopCompiler needs to be updated too.
-
- // force compilation for now for ref types
- // also could be a mutable value type, Delegate.CreateDelegate and MethodInfo.Invoke both can't handle this, we
- // need to generate code.
- if (!CollectionUtils.TrueForAll(parameters, (p) => !p.ParameterType.IsByRef) ||
- (!node.Method.IsStatic && node.Method.DeclaringType.IsValueType && node.Method.DeclaringType.Assembly != typeof (object).Assembly)) {
-#if MONO_INTERPRETER
- throw new NotImplementedException ("Interpreter of ref types");
-#else
- _forceCompile = true;
-#endif
- }
-
- // CF bug workaround
- // TODO: can we do better if the delegate targets LightLambda.Run* method?
- if (PlatformAdaptationLayer.IsCompactFramework &&
- node.Method.Name == "Invoke" && typeof(Delegate).IsAssignableFrom(node.Object.Type) && !node.Method.IsStatic) {
-
- Compile(
- AstUtils.Convert(
- Expression.Call(
- node.Object,
- node.Object.Type.GetMethod("DynamicInvoke"),
- Expression.NewArrayInit(typeof(object), node.Arguments.Map((e) => AstUtils.Convert(e, typeof(object))))
- ),
- node.Type
- )
- );
-
- } else {
- if (!node.Method.IsStatic) {
- Compile(node.Object);
- }
-
- foreach (var arg in node.Arguments) {
- Compile(arg);
- }
-
- EmitCall(node.Method, parameters);
- }
- }
-
- public void EmitCall(MethodInfo method) {
- EmitCall(method, method.GetParameters());
- }
-
- public void EmitCall(MethodInfo method, ParameterInfo[] parameters) {
- Instruction instruction;
-
- try {
- instruction = CallInstruction.Create(method, parameters);
- } catch (SecurityException) {
- _forceCompile = true;
-
- _instructions.Emit(new PopNInstruction((method.IsStatic ? 0 : 1) + parameters.Length));
- if (method.ReturnType != typeof(void)) {
- _instructions.EmitLoad(null);
- }
-
- return;
- }
-
- _instructions.Emit(instruction);
- }
-
- private void CompileNewExpression(Expression expr) {
- var node = (NewExpression)expr;
-
- if (node.Constructor != null) {
- var parameters = node.Constructor.GetParameters();
- if (!CollectionUtils.TrueForAll(parameters, (p) => !p.ParameterType.IsByRef)
-#if FEATURE_LCG
- || node.Constructor.DeclaringType == typeof(DynamicMethod)
-#endif
- ) {
- _forceCompile = true;
- }
- }
-
- if (node.Constructor != null) {
- foreach (var arg in node.Arguments) {
- this.Compile(arg);
- }
- _instructions.EmitNew(node.Constructor);
- } else {
- Debug.Assert(expr.Type.IsValueType());
- _instructions.EmitDefaultValue(node.Type);
- }
- }
-
- private void CompileMemberExpression(Expression expr) {
- var node = (MemberExpression)expr;
-
- var member = node.Member;
- FieldInfo fi = member as FieldInfo;
- if (fi != null) {
- if (fi.IsLiteral) {
- _instructions.EmitLoad(fi.GetRawConstantValue(), fi.FieldType);
- } else if (fi.IsStatic) {
- if (fi.IsInitOnly) {
- _instructions.EmitLoad(fi.GetValue(null), fi.FieldType);
- } else {
- _instructions.EmitLoadField(fi);
- }
- } else {
- Compile(node.Expression);
- _instructions.EmitLoadField(fi);
- }
- return;
- }
-
- PropertyInfo pi = member as PropertyInfo;
- if (pi != null) {
- var method = pi.GetGetMethod(true);
- if (node.Expression != null) {
- Compile(node.Expression);
- }
- EmitCall(method);
- return;
- }
-
-
- throw new System.NotImplementedException();
- }
-
- private void CompileNewArrayExpression(Expression expr) {
- var node = (NewArrayExpression)expr;
-
- foreach (var arg in node.Expressions) {
- Compile(arg);
- }
-
- Type elementType = node.Type.GetElementType();
- int rank = node.Expressions.Count;
-
- if (node.NodeType == ExpressionType.NewArrayInit) {
- _instructions.EmitNewArrayInit(elementType, rank);
- } else if (node.NodeType == ExpressionType.NewArrayBounds) {
- if (rank == 1) {
- _instructions.EmitNewArray(elementType);
- } else {
- _instructions.EmitNewArrayBounds(elementType, rank);
- }
- } else {
- throw new System.NotImplementedException();
- }
- }
-
- private void CompileExtensionExpression(Expression expr) {
- var instructionProvider = expr as IInstructionProvider;
- if (instructionProvider != null) {
- instructionProvider.AddInstructions(this);
- return;
- }
-
- if (expr.CanReduce) {
- Compile(expr.Reduce());
- } else {
- throw new System.NotImplementedException();
- }
- }
-
-
- private void CompileDebugInfoExpression(Expression expr) {
- var node = (DebugInfoExpression)expr;
- int start = _instructions.Count;
- var info = new DebugInfo()
- {
- Index = start,
- FileName = node.Document.FileName,
- StartLine = node.StartLine,
- EndLine = node.EndLine,
- IsClear = node.IsClear
- };
- _debugInfos.Add(info);
- }
-
- private void CompileRuntimeVariablesExpression(Expression expr) {
- // Generates IRuntimeVariables for all requested variables
- var node = (RuntimeVariablesExpression)expr;
- foreach (var variable in node.Variables) {
- EnsureAvailableForClosure(variable);
- CompileGetBoxedVariable(variable);
- }
-
- _instructions.EmitNewRuntimeVariables(node.Variables.Count);
- }
-
-
- private void CompileLambdaExpression(Expression expr) {
- var node = (LambdaExpression)expr;
- var compiler = new LightCompiler(this);
- var creator = compiler.CompileTop(node);
-
- if (compiler._locals.ClosureVariables != null) {
- foreach (ParameterExpression variable in compiler._locals.ClosureVariables.Keys) {
- CompileGetBoxedVariable(variable);
- }
- }
- _instructions.EmitCreateDelegate(creator);
- }
-
- private void CompileQuotedLambdaExpression(Expression expr) {
- _instructions.EmitStore (expr);
- }
-
- private void CompileCoalesceBinaryExpression(Expression expr) {
- var node = (BinaryExpression)expr;
-
- if (TypeUtils.IsNullableType(node.Left.Type)) {
- throw new NotImplementedException();
- } else if (node.Conversion != null) {
- throw new NotImplementedException();
- } else {
- var leftNotNull = _instructions.MakeLabel();
- Compile(node.Left);
- _instructions.EmitCoalescingBranch(leftNotNull);
- _instructions.EmitPop();
- Compile(node.Right);
- _instructions.MarkLabel(leftNotNull);
- }
- }
-
- private void CompileInvocationExpression(Expression expr) {
- var node = (InvocationExpression)expr;
-
- // TODO: LambdaOperand optimization (see compiler)
- if (typeof(LambdaExpression).IsAssignableFrom(node.Expression.Type)) {
- throw new System.NotImplementedException();
- }
-
- // TODO: do not create a new Call Expression
- if (PlatformAdaptationLayer.IsCompactFramework) {
- // Workaround for a bug in Compact Framework
- Compile(
- AstUtils.Convert(
- Expression.Call(
- node.Expression,
- node.Expression.Type.GetMethod("DynamicInvoke"),
- Expression.NewArrayInit(typeof(object), node.Arguments.Map((e) => AstUtils.Convert(e, typeof(object))))
- ),
- node.Type
- )
- );
- } else {
- CompileMethodCallExpression(Expression.Call(node.Expression, node.Expression.Type.GetMethod("Invoke"), node.Arguments));
- }
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")]
- private void CompileListInitExpression(Expression expr) {
- throw new System.NotImplementedException();
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")]
- private void CompileMemberInitExpression(Expression expr) {
- throw new System.NotImplementedException();
- }
-
- private void CompileQuoteUnaryExpression(Expression expr) {
- var qe = (UnaryExpression)expr;
- CompileQuotedLambdaExpression (qe.Operand);
- }
-
- private void CompileUnboxUnaryExpression(Expression expr) {
- var node = (UnaryExpression)expr;
- // unboxing is a nop:
- Compile(node.Operand);
- }
-
- private void CompileTypeEqualExpression(Expression expr) {
- Debug.Assert(expr.NodeType == ExpressionType.TypeEqual);
- var node = (TypeBinaryExpression)expr;
-
- Compile(node.Expression);
- _instructions.EmitLoad(node.TypeOperand);
- _instructions.EmitTypeEquals();
- }
-
- private void CompileTypeAsExpression(UnaryExpression node) {
- Compile(node.Operand);
- _instructions.EmitTypeAs(node.Type);
- }
-
- private void CompileTypeIsExpression(Expression expr) {
- Debug.Assert(expr.NodeType == ExpressionType.TypeIs);
- var node = (TypeBinaryExpression)expr;
-
- Compile(node.Expression);
- if (node.Expression.Type == typeof (void)) {
- _instructions.Emit (InstructionFactory<bool>.Factory.DefaultValue ());
- return;
- }
-
- // use TypeEqual for sealed types:
- if (node.TypeOperand.IsSealed()) {
- _instructions.EmitLoad(node.TypeOperand);
- _instructions.EmitTypeEquals();
- } else {
- _instructions.EmitTypeIs(node.TypeOperand);
- }
- }
-
- private void CompileReducibleExpression(Expression expr) {
- switch (expr.NodeType) {
- case ExpressionType.PreIncrementAssign:
- _instructions.EmitIncrement (expr.Type);
- break;
- default:
- throw Assert.Unreachable;
- }
- }
-
- internal void Compile(Expression expr, bool asVoid) {
- if (asVoid) {
- CompileAsVoid(expr);
- } else {
- Compile(expr);
- }
- }
-
- internal void CompileAsVoid(Expression expr) {
- bool pushLabelBlock = TryPushLabelBlock(expr);
- int startingStackDepth = _instructions.CurrentStackDepth;
- switch (expr.NodeType) {
- case ExpressionType.Assign:
- CompileAssignBinaryExpression(expr, true);
- break;
-
- case ExpressionType.Block:
- CompileBlockExpression(expr, true);
- break;
-
- case ExpressionType.Throw:
- CompileThrowUnaryExpression(expr, true);
- break;
-
- case ExpressionType.Constant:
- case ExpressionType.Default:
- case ExpressionType.Parameter:
- // no-op
- break;
-
- default:
- CompileNoLabelPush(expr);
- if (expr.Type != typeof(void)) {
- _instructions.EmitPop();
- }
- break;
- }
- Debug.Assert(_instructions.CurrentStackDepth == startingStackDepth);
- if (pushLabelBlock) {
- PopLabelBlock(_labelBlock.Kind);
- }
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- private void CompileNoLabelPush(Expression expr) {
- int startingStackDepth = _instructions.CurrentStackDepth;
- switch (expr.NodeType) {
- case ExpressionType.Add: CompileBinaryExpression(expr); break;
- case ExpressionType.AddChecked: CompileBinaryExpression(expr); break;
- case ExpressionType.And: CompileBinaryExpression(expr); break;
- case ExpressionType.AndAlso: CompileAndAlsoBinaryExpression(expr); break;
- case ExpressionType.ArrayLength: CompileUnaryExpression(expr); break;
- case ExpressionType.ArrayIndex: CompileBinaryExpression(expr); break;
- case ExpressionType.Call: CompileMethodCallExpression(expr); break;
- case ExpressionType.Coalesce: CompileCoalesceBinaryExpression(expr); break;
- case ExpressionType.Conditional: CompileConditionalExpression(expr, expr.Type == typeof(void)); break;
- case ExpressionType.Constant: CompileConstantExpression(expr); break;
- case ExpressionType.Convert: CompileConvertUnaryExpression(expr); break;
- case ExpressionType.ConvertChecked: CompileConvertUnaryExpression(expr); break;
- case ExpressionType.Divide: CompileBinaryExpression(expr); break;
- case ExpressionType.Equal: CompileBinaryExpression(expr); break;
- case ExpressionType.ExclusiveOr: CompileBinaryExpression(expr); break;
- case ExpressionType.GreaterThan: CompileBinaryExpression(expr); break;
- case ExpressionType.GreaterThanOrEqual: CompileBinaryExpression(expr); break;
- case ExpressionType.Invoke: CompileInvocationExpression(expr); break;
- case ExpressionType.Lambda: CompileLambdaExpression(expr); break;
- case ExpressionType.LeftShift: CompileBinaryExpression(expr); break;
- case ExpressionType.LessThan: CompileBinaryExpression(expr); break;
- case ExpressionType.LessThanOrEqual: CompileBinaryExpression(expr); break;
- case ExpressionType.ListInit: CompileListInitExpression(expr); break;
- case ExpressionType.MemberAccess: CompileMemberExpression(expr); break;
- case ExpressionType.MemberInit: CompileMemberInitExpression(expr); break;
- case ExpressionType.Modulo: CompileBinaryExpression(expr); break;
- case ExpressionType.Multiply: CompileBinaryExpression(expr); break;
- case ExpressionType.MultiplyChecked: CompileBinaryExpression(expr); break;
- case ExpressionType.Negate: CompileUnaryExpression(expr); break;
- case ExpressionType.UnaryPlus: CompileUnaryExpression(expr); break;
- case ExpressionType.NegateChecked: CompileUnaryExpression(expr); break;
- case ExpressionType.New: CompileNewExpression(expr); break;
- case ExpressionType.NewArrayInit: CompileNewArrayExpression(expr); break;
- case ExpressionType.NewArrayBounds: CompileNewArrayExpression(expr); break;
- case ExpressionType.Not: CompileUnaryExpression(expr); break;
- case ExpressionType.NotEqual: CompileBinaryExpression(expr); break;
- case ExpressionType.Or: CompileBinaryExpression(expr); break;
- case ExpressionType.OrElse: CompileOrElseBinaryExpression(expr); break;
- case ExpressionType.Parameter: CompileParameterExpression(expr); break;
- case ExpressionType.Power: CompileBinaryExpression(expr); break;
- case ExpressionType.Quote: CompileQuoteUnaryExpression(expr); break;
- case ExpressionType.RightShift: CompileBinaryExpression(expr); break;
- case ExpressionType.Subtract: CompileBinaryExpression(expr); break;
- case ExpressionType.SubtractChecked: CompileBinaryExpression(expr); break;
- case ExpressionType.TypeAs: CompileUnaryExpression(expr); break;
- case ExpressionType.TypeIs: CompileTypeIsExpression(expr); break;
- case ExpressionType.Assign: CompileAssignBinaryExpression(expr, expr.Type == typeof(void)); break;
- case ExpressionType.Block: CompileBlockExpression(expr, expr.Type == typeof(void)); break;
- case ExpressionType.DebugInfo: CompileDebugInfoExpression(expr); break;
- case ExpressionType.Decrement: CompileUnaryExpression(expr); break;
- case ExpressionType.Dynamic: CompileDynamicExpression(expr); break;
- case ExpressionType.Default: CompileDefaultExpression(expr); break;
- case ExpressionType.Extension: CompileExtensionExpression(expr); break;
- case ExpressionType.Goto: CompileGotoExpression(expr); break;
- case ExpressionType.Increment: CompileUnaryExpression(expr); break;
- case ExpressionType.Index: CompileIndexExpression(expr); break;
- case ExpressionType.Label: CompileLabelExpression(expr); break;
- case ExpressionType.RuntimeVariables: CompileRuntimeVariablesExpression(expr); break;
- case ExpressionType.Loop: CompileLoopExpression(expr); break;
- case ExpressionType.Switch: CompileSwitchExpression(expr); break;
- case ExpressionType.Throw: CompileThrowUnaryExpression(expr, expr.Type == typeof(void)); break;
- case ExpressionType.Try: CompileTryExpression(expr); break;
- case ExpressionType.Unbox: CompileUnboxUnaryExpression(expr); break;
- case ExpressionType.TypeEqual: CompileTypeEqualExpression(expr); break;
- case ExpressionType.OnesComplement: CompileUnaryExpression(expr); break;
- case ExpressionType.IsTrue: CompileUnaryExpression(expr); break;
- case ExpressionType.IsFalse: CompileUnaryExpression(expr); break;
- case ExpressionType.AddAssign:
- case ExpressionType.AndAssign:
- case ExpressionType.DivideAssign:
- case ExpressionType.ExclusiveOrAssign:
- case ExpressionType.LeftShiftAssign:
- case ExpressionType.ModuloAssign:
- case ExpressionType.MultiplyAssign:
- case ExpressionType.OrAssign:
- case ExpressionType.PowerAssign:
- case ExpressionType.RightShiftAssign:
- case ExpressionType.SubtractAssign:
- case ExpressionType.AddAssignChecked:
- case ExpressionType.MultiplyAssignChecked:
- case ExpressionType.SubtractAssignChecked:
- case ExpressionType.PreIncrementAssign:
- case ExpressionType.PreDecrementAssign:
- case ExpressionType.PostIncrementAssign:
- case ExpressionType.PostDecrementAssign:
- CompileReducibleExpression(expr); break;
- default: throw Assert.Unreachable;
- };
- Debug.Assert(_instructions.CurrentStackDepth == startingStackDepth + (expr.Type == typeof(void) ? 0 : 1));
- }
-
- public void Compile(Expression expr) {
- bool pushLabelBlock = TryPushLabelBlock(expr);
- CompileNoLabelPush(expr);
- if (pushLabelBlock) {
- PopLabelBlock(_labelBlock.Kind);
- }
- }
-
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs
deleted file mode 100644
index c636a17050d..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs
+++ /dev/null
@@ -1,198 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-using Microsoft.Scripting.Ast;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using Microsoft.Scripting.Generation;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
-
- /// <summary>
- /// Manages creation of interpreted delegates. These delegates will get
- /// compiled if they are executed often enough.
- /// </summary>
- internal sealed class LightDelegateCreator {
- // null if we are forced to compile
- private readonly Interpreter _interpreter;
- private readonly Expression _lambda;
-
-#if !MONO_INTERPRETER
- // Adaptive compilation support:
- private Type _compiledDelegateType;
- private Delegate _compiled;
- private readonly object _compileLock = new object();
-#endif
- internal LightDelegateCreator(Interpreter interpreter, LambdaExpression lambda) {
- Assert.NotNull(lambda);
- _interpreter = interpreter;
- _lambda = lambda;
- }
-
- internal LightDelegateCreator(Interpreter interpreter, LightLambdaExpression lambda) {
- Assert.NotNull(lambda);
- _interpreter = interpreter;
- _lambda = lambda;
- }
-
- internal Interpreter Interpreter {
- get { return _interpreter; }
- }
-
- private bool HasClosure {
- get { return _interpreter != null && _interpreter.ClosureSize > 0; }
- }
-#if !MONO_INTERPRETER
- internal bool HasCompiled {
- get { return _compiled != null; }
- }
-
- /// <summary>
- /// true if the compiled delegate has the same type as the lambda;
- /// false if the type was changed for interpretation.
- /// </summary>
- internal bool SameDelegateType {
- get { return _compiledDelegateType == DelegateType; }
- }
-#endif
- internal Delegate CreateDelegate() {
- return CreateDelegate(null);
- }
-
- internal Delegate CreateDelegate(StrongBox<object>[] closure) {
-#if !MONO_INTERPRETER
- if (_compiled != null) {
- // If the delegate type we want is not a Func/Action, we can't
- // use the compiled code directly. So instead just fall through
- // and create an interpreted LightLambda, which will pick up
- // the compiled delegate on its first run.
- //
- // Ideally, we would just rebind the compiled delegate using
- // Delegate.CreateDelegate. Unfortunately, it doesn't work on
- // dynamic methods.
- if (SameDelegateType) {
- return CreateCompiledDelegate(closure);
- }
- }
-
- if (_interpreter == null) {
- // We can't interpret, so force a compile
- Compile(null);
- Delegate compiled = CreateCompiledDelegate(closure);
- Debug.Assert(compiled.GetType() == DelegateType);
- return compiled;
- }
-#endif
- // Otherwise, we'll create an interpreted LightLambda
- return new LightLambda(this, closure, _interpreter._compilationThreshold).MakeDelegate(DelegateType);
- }
-
- private Type DelegateType {
- get {
- LambdaExpression le = _lambda as LambdaExpression;
- if (le != null) {
- return le.Type;
- }
-
- return ((LightLambdaExpression)_lambda).Type;
- }
- }
-
-#if !MONO_INTERPRETER
- /// <summary>
- /// Used by LightLambda to get the compiled delegate.
- /// </summary>
- internal Delegate CreateCompiledDelegate(StrongBox<object>[] closure) {
- Debug.Assert(HasClosure == (closure != null));
-
- if (HasClosure) {
- // We need to apply the closure to get the actual delegate.
- var applyClosure = (Func<StrongBox<object>[], Delegate>)_compiled;
- return applyClosure(closure);
- }
- return _compiled;
- }
-
- /// <summary>
- /// Create a compiled delegate for the LightLambda, and saves it so
- /// future calls to Run will execute the compiled code instead of
- /// interpreting.
- /// </summary>
- internal void Compile(object state) {
- if (_compiled != null) {
- return;
- }
-
- // Compilation is expensive, we only want to do it once.
- lock (_compileLock) {
- if (_compiled != null) {
- return;
- }
-
- PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Interpreted lambda compiled");
-
- // Interpreter needs a standard delegate type.
- // So change the lambda's delegate type to Func<...> or
- // Action<...> so it can be called from the LightLambda.Run
- // methods.
- LambdaExpression lambda = (_lambda as LambdaExpression) ?? (LambdaExpression)((LightLambdaExpression)_lambda).Reduce();
- if (_interpreter != null) {
- _compiledDelegateType = GetFuncOrAction(lambda);
- lambda = Expression.Lambda(_compiledDelegateType, lambda.Body, lambda.Name, lambda.Parameters);
- }
-
- if (HasClosure) {
- _compiled = LightLambdaClosureVisitor.BindLambda(lambda, _interpreter.ClosureVariables);
- } else {
- _compiled = lambda.Compile();
- }
- }
- }
-
- private static Type GetFuncOrAction(LambdaExpression lambda) {
- Type delegateType;
- bool isVoid = lambda.ReturnType == typeof(void);
-
- if (isVoid && lambda.Parameters.Count == 2 &&
- lambda.Parameters[0].IsByRef && lambda.Parameters[1].IsByRef) {
- return typeof(ActionRef<,>).MakeGenericType(lambda.Parameters.Map(p => p.Type));
- } else {
- Type[] types = lambda.Parameters.Map(p => p.IsByRef ? p.Type.MakeByRefType() : p.Type);
- if (isVoid) {
- if (Expression.TryGetActionType(types, out delegateType)) {
- return delegateType;
- }
- } else {
- types = types.AddLast(lambda.ReturnType);
- if (Expression.TryGetFuncType(types, out delegateType)) {
- return delegateType;
- }
- }
- return lambda.Type;
- }
- }
-#endif
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.Generated.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.Generated.cs
deleted file mode 100644
index 1c376ff6f2c..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.Generated.cs
+++ /dev/null
@@ -1,756 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-
-using System;
-using System.Runtime.CompilerServices;
-using System.Reflection;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- public partial class LightLambda {
- #region Generated LightLambda Run Methods
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_run_methods from: generate_dynamic_instructions.py
-
- internal const int MaxParameters = 16;
- internal TRet Run0<TRet>() {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<TRet>)_compiled)();
- }
-#endif
- var frame = MakeFrame();
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid0() {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action)_compiled)();
- return;
- }
-#endif
- var frame = MakeFrame();
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun0<TRet>(LightLambda lambda) {
- return new Func<TRet>(lambda.Run0<TRet>);
- }
- internal static Delegate MakeRunVoid0(LightLambda lambda) {
- return new Action(lambda.RunVoid0);
- }
- internal TRet Run1<T0,TRet>(T0 arg0) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,TRet>)_compiled)(arg0);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid1<T0>(T0 arg0) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0>)_compiled)(arg0);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun1<T0,TRet>(LightLambda lambda) {
- return new Func<T0,TRet>(lambda.Run1<T0,TRet>);
- }
- internal static Delegate MakeRunVoid1<T0>(LightLambda lambda) {
- return new Action<T0>(lambda.RunVoid1<T0>);
- }
- internal TRet Run2<T0,T1,TRet>(T0 arg0,T1 arg1) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,TRet>)_compiled)(arg0, arg1);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid2<T0,T1>(T0 arg0,T1 arg1) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1>)_compiled)(arg0, arg1);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun2<T0,T1,TRet>(LightLambda lambda) {
- return new Func<T0,T1,TRet>(lambda.Run2<T0,T1,TRet>);
- }
- internal static Delegate MakeRunVoid2<T0,T1>(LightLambda lambda) {
- return new Action<T0,T1>(lambda.RunVoid2<T0,T1>);
- }
- internal TRet Run3<T0,T1,T2,TRet>(T0 arg0,T1 arg1,T2 arg2) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,T2,TRet>)_compiled)(arg0, arg1, arg2);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid3<T0,T1,T2>(T0 arg0,T1 arg1,T2 arg2) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1,T2>)_compiled)(arg0, arg1, arg2);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun3<T0,T1,T2,TRet>(LightLambda lambda) {
- return new Func<T0,T1,T2,TRet>(lambda.Run3<T0,T1,T2,TRet>);
- }
- internal static Delegate MakeRunVoid3<T0,T1,T2>(LightLambda lambda) {
- return new Action<T0,T1,T2>(lambda.RunVoid3<T0,T1,T2>);
- }
- internal TRet Run4<T0,T1,T2,T3,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,T2,T3,TRet>)_compiled)(arg0, arg1, arg2, arg3);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid4<T0,T1,T2,T3>(T0 arg0,T1 arg1,T2 arg2,T3 arg3) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1,T2,T3>)_compiled)(arg0, arg1, arg2, arg3);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun4<T0,T1,T2,T3,TRet>(LightLambda lambda) {
- return new Func<T0,T1,T2,T3,TRet>(lambda.Run4<T0,T1,T2,T3,TRet>);
- }
- internal static Delegate MakeRunVoid4<T0,T1,T2,T3>(LightLambda lambda) {
- return new Action<T0,T1,T2,T3>(lambda.RunVoid4<T0,T1,T2,T3>);
- }
- internal TRet Run5<T0,T1,T2,T3,T4,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,T2,T3,T4,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid5<T0,T1,T2,T3,T4>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1,T2,T3,T4>)_compiled)(arg0, arg1, arg2, arg3, arg4);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun5<T0,T1,T2,T3,T4,TRet>(LightLambda lambda) {
- return new Func<T0,T1,T2,T3,T4,TRet>(lambda.Run5<T0,T1,T2,T3,T4,TRet>);
- }
- internal static Delegate MakeRunVoid5<T0,T1,T2,T3,T4>(LightLambda lambda) {
- return new Action<T0,T1,T2,T3,T4>(lambda.RunVoid5<T0,T1,T2,T3,T4>);
- }
- internal TRet Run6<T0,T1,T2,T3,T4,T5,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,T2,T3,T4,T5,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid6<T0,T1,T2,T3,T4,T5>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1,T2,T3,T4,T5>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun6<T0,T1,T2,T3,T4,T5,TRet>(LightLambda lambda) {
- return new Func<T0,T1,T2,T3,T4,T5,TRet>(lambda.Run6<T0,T1,T2,T3,T4,T5,TRet>);
- }
- internal static Delegate MakeRunVoid6<T0,T1,T2,T3,T4,T5>(LightLambda lambda) {
- return new Action<T0,T1,T2,T3,T4,T5>(lambda.RunVoid6<T0,T1,T2,T3,T4,T5>);
- }
- internal TRet Run7<T0,T1,T2,T3,T4,T5,T6,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,T2,T3,T4,T5,T6,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid7<T0,T1,T2,T3,T4,T5,T6>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1,T2,T3,T4,T5,T6>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun7<T0,T1,T2,T3,T4,T5,T6,TRet>(LightLambda lambda) {
- return new Func<T0,T1,T2,T3,T4,T5,T6,TRet>(lambda.Run7<T0,T1,T2,T3,T4,T5,T6,TRet>);
- }
- internal static Delegate MakeRunVoid7<T0,T1,T2,T3,T4,T5,T6>(LightLambda lambda) {
- return new Action<T0,T1,T2,T3,T4,T5,T6>(lambda.RunVoid7<T0,T1,T2,T3,T4,T5,T6>);
- }
- internal TRet Run8<T0,T1,T2,T3,T4,T5,T6,T7,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid8<T0,T1,T2,T3,T4,T5,T6,T7>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1,T2,T3,T4,T5,T6,T7>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun8<T0,T1,T2,T3,T4,T5,T6,T7,TRet>(LightLambda lambda) {
- return new Func<T0,T1,T2,T3,T4,T5,T6,T7,TRet>(lambda.Run8<T0,T1,T2,T3,T4,T5,T6,T7,TRet>);
- }
- internal static Delegate MakeRunVoid8<T0,T1,T2,T3,T4,T5,T6,T7>(LightLambda lambda) {
- return new Action<T0,T1,T2,T3,T4,T5,T6,T7>(lambda.RunVoid8<T0,T1,T2,T3,T4,T5,T6,T7>);
- }
- internal TRet Run9<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid9<T0,T1,T2,T3,T4,T5,T6,T7,T8>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun9<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>(LightLambda lambda) {
- return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>(lambda.Run9<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>);
- }
- internal static Delegate MakeRunVoid9<T0,T1,T2,T3,T4,T5,T6,T7,T8>(LightLambda lambda) {
- return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8>(lambda.RunVoid9<T0,T1,T2,T3,T4,T5,T6,T7,T8>);
- }
- internal TRet Run10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- frame.Data[9] = arg9;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- frame.Data[9] = arg9;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>(LightLambda lambda) {
- return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>(lambda.Run10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>);
- }
- internal static Delegate MakeRunVoid10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>(LightLambda lambda) {
- return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>(lambda.RunVoid10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>);
- }
- internal TRet Run11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- frame.Data[9] = arg9;
- frame.Data[10] = arg10;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- frame.Data[9] = arg9;
- frame.Data[10] = arg10;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>(LightLambda lambda) {
- return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>(lambda.Run11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>);
- }
- internal static Delegate MakeRunVoid11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(LightLambda lambda) {
- return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(lambda.RunVoid11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>);
- }
- internal TRet Run12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- frame.Data[9] = arg9;
- frame.Data[10] = arg10;
- frame.Data[11] = arg11;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- frame.Data[9] = arg9;
- frame.Data[10] = arg10;
- frame.Data[11] = arg11;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>(LightLambda lambda) {
- return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>(lambda.Run12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>);
- }
- internal static Delegate MakeRunVoid12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>(LightLambda lambda) {
- return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>(lambda.RunVoid12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>);
- }
- internal TRet Run13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- frame.Data[9] = arg9;
- frame.Data[10] = arg10;
- frame.Data[11] = arg11;
- frame.Data[12] = arg12;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- frame.Data[9] = arg9;
- frame.Data[10] = arg10;
- frame.Data[11] = arg11;
- frame.Data[12] = arg12;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>(LightLambda lambda) {
- return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>(lambda.Run13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>);
- }
- internal static Delegate MakeRunVoid13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>(LightLambda lambda) {
- return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>(lambda.RunVoid13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>);
- }
- internal TRet Run14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- frame.Data[9] = arg9;
- frame.Data[10] = arg10;
- frame.Data[11] = arg11;
- frame.Data[12] = arg12;
- frame.Data[13] = arg13;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- frame.Data[9] = arg9;
- frame.Data[10] = arg10;
- frame.Data[11] = arg11;
- frame.Data[12] = arg12;
- frame.Data[13] = arg13;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>(LightLambda lambda) {
- return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>(lambda.Run14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>);
- }
- internal static Delegate MakeRunVoid14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>(LightLambda lambda) {
- return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>(lambda.RunVoid14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>);
- }
- internal TRet Run15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13,T14 arg14) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14);
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- frame.Data[9] = arg9;
- frame.Data[10] = arg10;
- frame.Data[11] = arg11;
- frame.Data[12] = arg12;
- frame.Data[13] = arg13;
- frame.Data[14] = arg14;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- return (TRet)frame.Pop();
- }
-
- internal void RunVoid15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13,T14 arg14) {
-#if !MONO_INTERPRETER
- if (_compiled != null || TryGetCompiled()) {
- ((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14);
- return;
- }
-#endif
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- frame.Data[2] = arg2;
- frame.Data[3] = arg3;
- frame.Data[4] = arg4;
- frame.Data[5] = arg5;
- frame.Data[6] = arg6;
- frame.Data[7] = arg7;
- frame.Data[8] = arg8;
- frame.Data[9] = arg9;
- frame.Data[10] = arg10;
- frame.Data[11] = arg11;
- frame.Data[12] = arg12;
- frame.Data[13] = arg13;
- frame.Data[14] = arg14;
- var current = frame.Enter();
- try { _interpreter.Run(frame); } finally { frame.Leave(current); }
- }
-
- internal static Delegate MakeRun15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>(LightLambda lambda) {
- return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>(lambda.Run15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>);
- }
- internal static Delegate MakeRunVoid15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>(LightLambda lambda) {
- return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>(lambda.RunVoid15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>);
- }
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.cs
deleted file mode 100644
index bc9e01ee46a..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.cs
+++ /dev/null
@@ -1,280 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_TASKS
-using System.Threading.Tasks;
-#endif
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Reflection;
-#if FEATURE_REFEMIT
-using System.Reflection.Emit;
-#endif
-using System.Runtime.CompilerServices;
-using System.Security;
-using System.Threading;
-
-using Microsoft.Scripting.Generation;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-using AstUtils = Microsoft.Scripting.Ast.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
-
- public sealed class LightLambdaCompileEventArgs : EventArgs {
- public Delegate Compiled { get; private set; }
-
- internal LightLambdaCompileEventArgs(Delegate compiled) {
- Compiled = compiled;
- }
- }
-
- public partial class LightLambda {
- private readonly StrongBox<object>[] _closure;
- private readonly Interpreter _interpreter;
- private static readonly CacheDict<Type, Func<LightLambda, Delegate>> _runCache = new CacheDict<Type, Func<LightLambda, Delegate>>(100);
-
- // Adaptive compilation support
- private readonly LightDelegateCreator _delegateCreator;
-#if MONO_INTERPRETER
- const Delegate _compiled = null;
-#else
- private Delegate _compiled;
-#endif
- private int _compilationThreshold;
-
-#if !MONO_INTERPRETER
- /// <summary>
- /// Provides notification that the LightLambda has been compiled.
- /// </summary>
- public event EventHandler<LightLambdaCompileEventArgs> Compile;
-#endif
-
- internal LightLambda(LightDelegateCreator delegateCreator, StrongBox<object>[] closure, int compilationThreshold) {
- _delegateCreator = delegateCreator;
- _closure = closure;
- _interpreter = delegateCreator.Interpreter;
- _compilationThreshold = compilationThreshold;
- }
-
- private static Func<LightLambda, Delegate> GetRunDelegateCtor(Type delegateType) {
- lock (_runCache) {
- Func<LightLambda, Delegate> fastCtor;
- if (_runCache.TryGetValue(delegateType, out fastCtor)) {
- return fastCtor;
- }
- return MakeRunDelegateCtor(delegateType);
- }
- }
-
- private static Func<LightLambda, Delegate> MakeRunDelegateCtor(Type delegateType) {
- var method = delegateType.GetMethod("Invoke");
- var paramInfos = method.GetParameters();
- Type[] paramTypes;
- string name = "Run";
-
- if (paramInfos.Length >= MaxParameters) {
- return null;
- }
-
- if (method.ReturnType == typeof(void)) {
- name += "Void";
- paramTypes = new Type[paramInfos.Length];
- } else {
- paramTypes = new Type[paramInfos.Length + 1];
- paramTypes[paramTypes.Length - 1] = method.ReturnType;
- }
-
- MethodInfo runMethod;
-
- if (method.ReturnType == typeof(void) && paramTypes.Length == 2 &&
- paramInfos[0].ParameterType.IsByRef && paramInfos[1].ParameterType.IsByRef) {
- runMethod = typeof(LightLambda).GetMethod("RunVoidRef2", BindingFlags.NonPublic | BindingFlags.Instance);
- paramTypes[0] = paramInfos[0].ParameterType.GetElementType();
- paramTypes[1] = paramInfos[1].ParameterType.GetElementType();
- } else if (method.ReturnType == typeof(void) && paramTypes.Length == 0) {
- runMethod = typeof(LightLambda).GetMethod("RunVoid0", BindingFlags.NonPublic | BindingFlags.Instance);
- } else {
- for (int i = 0; i < paramInfos.Length; i++) {
- paramTypes[i] = paramInfos[i].ParameterType;
- if (paramTypes[i].IsByRef) {
- return null;
- }
- }
-
- if (DelegateHelpers.MakeDelegate(paramTypes) == delegateType) {
- name = "Make" + name + paramInfos.Length;
-
- MethodInfo ctorMethod = typeof(LightLambda).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(paramTypes);
- return _runCache[delegateType] = (Func<LightLambda, Delegate>)ctorMethod.CreateDelegate(typeof(Func<LightLambda, Delegate>));
- }
-
- runMethod = typeof(LightLambda).GetMethod(name + paramInfos.Length, BindingFlags.NonPublic | BindingFlags.Instance);
- }
-
-#if FEATURE_LCG && !SILVERLIGHT && !WP75
- try {
- DynamicMethod dm = new DynamicMethod("FastCtor", typeof(Delegate), new[] { typeof(LightLambda) }, typeof(LightLambda), true);
- var ilgen = dm.GetILGenerator();
- ilgen.Emit(OpCodes.Ldarg_0);
- ilgen.Emit(OpCodes.Ldftn, runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod);
- ilgen.Emit(OpCodes.Newobj, delegateType.GetConstructor(new[] { typeof(object), typeof(IntPtr) }));
- ilgen.Emit(OpCodes.Ret);
- return _runCache[delegateType] = (Func<LightLambda, Delegate>)dm.CreateDelegate(typeof(Func<LightLambda, Delegate>));
- } catch (SecurityException) {
- }
-#endif
-
- // we don't have permission for restricted skip visibility dynamic methods, use the slower Delegate.CreateDelegate.
- var targetMethod = runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod;
- return _runCache[delegateType] = lambda => targetMethod.CreateDelegate(delegateType, lambda);
- }
-
- //TODO enable sharing of these custom delegates
- private Delegate CreateCustomDelegate(Type delegateType) {
- PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Synchronously compiling a custom delegate");
-
- var method = delegateType.GetMethod("Invoke");
- var paramInfos = method.GetParameters();
- var parameters = new ParameterExpression[paramInfos.Length];
- var parametersAsObject = new Expression[paramInfos.Length];
- for (int i = 0; i < paramInfos.Length; i++) {
- ParameterExpression parameter = Expression.Parameter(paramInfos[i].ParameterType, paramInfos[i].Name);
- parameters[i] = parameter;
- parametersAsObject[i] = Expression.Convert(parameter, typeof(object));
- }
-
- var data = Expression.NewArrayInit(typeof(object), parametersAsObject);
- var self = AstUtils.Constant(this);
- var runMethod = typeof(LightLambda).GetMethod("Run");
- var body = Expression.Convert(Expression.Call(self, runMethod, data), method.ReturnType);
- var lambda = Expression.Lambda(delegateType, body, parameters);
- return lambda.Compile();
- }
-
- internal Delegate MakeDelegate(Type delegateType) {
- Func<LightLambda, Delegate> fastCtor = GetRunDelegateCtor(delegateType);
- if (fastCtor != null) {
- return fastCtor(this);
- } else {
- return CreateCustomDelegate(delegateType);
- }
- }
-
- private bool TryGetCompiled() {
-#if !MONO_INTERPRETER
- // Use the compiled delegate if available.
- if (_delegateCreator.HasCompiled) {
- _compiled = _delegateCreator.CreateCompiledDelegate(_closure);
-
- // Send it to anyone who's interested.
- var compileEvent = Compile;
- if (compileEvent != null && _delegateCreator.SameDelegateType) {
- compileEvent(this, new LightLambdaCompileEventArgs(_compiled));
- }
-
- return true;
- }
-
- // Don't lock here, it's a frequently hit path.
- //
- // There could be multiple threads racing, but that is okay.
- // Two bad things can happen:
- // * We miss decrements (some thread sets the counter forward)
- // * We might enter the "if" branch more than once.
- //
- // The first is okay, it just means we take longer to compile.
- // The second we explicitly guard against inside of Compile().
- //
- // We can't miss 0. The first thread that writes -1 must have read 0 and hence start compilation.
- if (unchecked(_compilationThreshold--) == 0) {
-#if SILVERLIGHT
- if (PlatformAdaptationLayer.IsCompactFramework) {
- _compilationThreshold = Int32.MaxValue;
- return false;
- }
-#endif
- if (_interpreter.CompileSynchronously) {
- _delegateCreator.Compile(null);
- return TryGetCompiled();
- } else {
- // Kick off the compile on another thread so this one can keep going
-#if FEATURE_TASKS
- new Task(_delegateCreator.Compile, null).Start();
-#else
- ThreadPool.QueueUserWorkItem(_delegateCreator.Compile, null);
-#endif
- }
- }
-#endif
- return false;
- }
-
- private InterpretedFrame MakeFrame() {
- return new InterpretedFrame(_interpreter, _closure);
- }
-
- internal void RunVoidRef2<T0, T1>(ref T0 arg0, ref T1 arg1) {
- if (_compiled != null || TryGetCompiled()) {
- ((ActionRef<T0, T1>)_compiled)(ref arg0, ref arg1);
- return;
- }
-
- // copy in and copy out for today...
- var frame = MakeFrame();
- frame.Data[0] = arg0;
- frame.Data[1] = arg1;
- var currentFrame = frame.Enter();
- try {
- _interpreter.Run(frame);
- } finally {
- frame.Leave(currentFrame);
- arg0 = (T0)frame.Data[0];
- arg1 = (T1)frame.Data[1];
- }
- }
-
-#if !MONO_INTERPRETER
- public object Run(params object[] arguments) {
- if (_compiled != null || TryGetCompiled()) {
- try {
- return _compiled.DynamicInvoke(arguments);
- } catch (TargetInvocationException e) {
- throw ExceptionHelpers.UpdateForRethrow(e.InnerException);
- }
- }
-
- var frame = MakeFrame();
- for (int i = 0; i < arguments.Length; i++) {
- frame.Data[i] = arguments[i];
- }
- var currentFrame = frame.Enter();
- try {
- _interpreter.Run(frame);
- } finally {
- frame.Leave(currentFrame);
- }
- return frame.Pop();
- }
-#endif
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambdaClosureVisitor.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambdaClosureVisitor.cs
deleted file mode 100644
index e779e414855..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambdaClosureVisitor.cs
+++ /dev/null
@@ -1,260 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Utils;
-using AstUtils = Microsoft.Scripting.Ast.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
-
- /// <summary>
- /// Visits a LambdaExpression, replacing the constants with direct accesses
- /// to their StrongBox fields. This is very similar to what
- /// ExpressionQuoter does for LambdaCompiler.
- ///
- /// Also inserts debug information tracking similar to what the interpreter
- /// would do.
- /// </summary>
- internal sealed class LightLambdaClosureVisitor : ExpressionVisitor {
- /// <summary>
- /// Local variable mapping.
- /// </summary>
- private readonly Dictionary<ParameterExpression, LocalVariable> _closureVars;
-
- /// <summary>
- /// The variable that holds onto the StrongBox{object}[] closure from
- /// the interpreter
- /// </summary>
- private readonly ParameterExpression _closureArray;
-
- /// <summary>
- /// A stack of variables that are defined in nested scopes. We search
- /// this first when resolving a variable in case a nested scope shadows
- /// one of our variable instances.
- /// </summary>
- private readonly Stack<HashSet<ParameterExpression>> _shadowedVars = new Stack<HashSet<ParameterExpression>>();
-
- private LightLambdaClosureVisitor(Dictionary<ParameterExpression, LocalVariable> closureVariables, ParameterExpression closureArray) {
- Assert.NotNull(closureVariables, closureArray);
- _closureArray = closureArray;
- _closureVars = closureVariables;
- }
-
- /// <summary>
- /// Walks the lambda and produces a higher order function, which can be
- /// used to bind the lambda to a closure array from the interpreter.
- /// </summary>
- /// <param name="lambda">The lambda to bind.</param>
- /// <param name="closureVariables">Variables which are being accessed defined in the outer scope.</param>
- /// <returns>A delegate that can be called to produce a delegate bound to the passed in closure array.</returns>
- internal static Func<StrongBox<object>[], Delegate> BindLambda(LambdaExpression lambda, Dictionary<ParameterExpression, LocalVariable> closureVariables) {
- // 1. Create rewriter
- var closure = Expression.Parameter(typeof(StrongBox<object>[]), "closure");
- var visitor = new LightLambdaClosureVisitor(closureVariables, closure);
-
- // 2. Visit the lambda
- lambda = (LambdaExpression)visitor.Visit(lambda);
-
- // 3. Create a higher-order function which fills in the parameters
- var result = Expression.Lambda<Func<StrongBox<object>[], Delegate>>(lambda, closure);
-
- // 4. Compile it
- return result.Compile();
- }
-
- #region closures
-
- protected override Expression VisitLambda<T>(Expression<T> node) {
- _shadowedVars.Push(new HashSet<ParameterExpression>(node.Parameters));
- Expression b = Visit(node.Body);
- _shadowedVars.Pop();
- if (b == node.Body) {
- return node;
- }
- return Expression.Lambda<T>(b, node.Name, node.TailCall, node.Parameters);
- }
-
- protected override Expression VisitBlock(BlockExpression node) {
- if (node.Variables.Count > 0) {
- _shadowedVars.Push(new HashSet<ParameterExpression>(node.Variables));
- }
- var b = Visit(node.Expressions);
- if (node.Variables.Count > 0) {
- _shadowedVars.Pop();
- }
- if (b == node.Expressions) {
- return node;
- }
- return Expression.Block(node.Variables, b);
- }
-
- protected override CatchBlock VisitCatchBlock(CatchBlock node) {
- if (node.Variable != null) {
- _shadowedVars.Push(new HashSet<ParameterExpression>(new[] { node.Variable }));
- }
- Expression b = Visit(node.Body);
- Expression f = Visit(node.Filter);
- if (node.Variable != null) {
- _shadowedVars.Pop();
- }
- if (b == node.Body && f == node.Filter) {
- return node;
- }
- return Expression.MakeCatchBlock(node.Test, node.Variable, b, f);
- }
-
- protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) {
- int count = node.Variables.Count;
- var boxes = new List<Expression>();
- var vars = new List<ParameterExpression>();
- var indexes = new int[count];
- for (int i = 0; i < count; i++) {
- Expression box = GetClosureItem(node.Variables[i], false);
- if (box == null) {
- indexes[i] = vars.Count;
- vars.Add(node.Variables[i]);
- } else {
- indexes[i] = -1 - boxes.Count;
- boxes.Add(box);
- }
- }
-
- // No variables were rewritten. Just return the original node.
- if (boxes.Count == 0) {
- return node;
- }
-
- var boxesArray = Expression.NewArrayInit(typeof(IStrongBox), boxes);
-
- // All of them were rewritten. Just return the array, wrapped in a
- // read-only collection.
- if (vars.Count == 0) {
- return Expression.Invoke(
- Expression.Constant((Func<IStrongBox[], IRuntimeVariables>)RuntimeVariables.Create),
- boxesArray
- );
- }
-
- // Otherwise, we need to return an object that merges them
- Func<IRuntimeVariables, IRuntimeVariables, int[], IRuntimeVariables> helper = MergedRuntimeVariables.Create;
- return Expression.Invoke(AstUtils.Constant(helper), Expression.RuntimeVariables(vars), boxesArray, AstUtils.Constant(indexes));
- }
-
- protected override Expression VisitParameter(ParameterExpression node) {
- Expression closureItem = GetClosureItem(node, true);
- if (closureItem == null) {
- return node;
- }
- // Convert can go away if we switch to strongly typed StrongBox
- return Ast.Utils.Convert(closureItem, node.Type);
- }
-
- protected override Expression VisitBinary(BinaryExpression node) {
- if (node.NodeType == ExpressionType.Assign &&
- node.Left.NodeType == ExpressionType.Parameter) {
-
- var variable = (ParameterExpression)node.Left;
- Expression closureItem = GetClosureItem(variable, true);
- if (closureItem != null) {
- // We need to convert to object to store the value in the box.
- return Expression.Block(
- new[] { variable },
- Expression.Assign(variable, Visit(node.Right)),
- Expression.Assign(closureItem, Ast.Utils.Convert(variable, typeof(object))),
- variable
- );
- }
- }
- return base.VisitBinary(node);
- }
-
- private Expression GetClosureItem(ParameterExpression variable, bool unbox) {
- // Skip variables that are shadowed by a nested scope/lambda
- foreach (HashSet<ParameterExpression> hidden in _shadowedVars) {
- if (hidden.Contains(variable)) {
- return null;
- }
- }
-
- LocalVariable loc;
- if (!_closureVars.TryGetValue(variable, out loc)) {
- throw new InvalidOperationException("unbound variable: " + variable.Name);
- }
-
- var result = loc.LoadFromArray(null, _closureArray);
- return (unbox) ? LightCompiler.Unbox(result) : result;
- }
-
- protected override Expression VisitExtension(Expression node) {
- // Reduce extensions now so we can find embedded variables
- return Visit(node.ReduceExtensions());
- }
-
-
- #region MergedRuntimeVariables
-
- /// <summary>
- /// Provides a list of variables, supporing read/write of the values
- /// </summary>
- private sealed class MergedRuntimeVariables : IRuntimeVariables {
- private readonly IRuntimeVariables _first;
- private readonly IRuntimeVariables _second;
-
- // For reach item, the index into the first or second list
- // Positive values mean the first array, negative means the second
- private readonly int[] _indexes;
-
- private MergedRuntimeVariables(IRuntimeVariables first, IRuntimeVariables second, int[] indexes) {
- _first = first;
- _second = second;
- _indexes = indexes;
- }
-
- internal static IRuntimeVariables Create(IRuntimeVariables first, IRuntimeVariables second, int[] indexes) {
- return new MergedRuntimeVariables(first, second, indexes);
- }
-
- int IRuntimeVariables.Count {
- get { return _indexes.Length; }
- }
-
- object IRuntimeVariables.this[int index] {
- get {
- index = _indexes[index];
- return (index >= 0) ? _first[index] : _second[-1 - index];
- }
- set {
- index = _indexes[index];
- if (index >= 0) {
- _first[index] = value;
- } else {
- _second[-1 - index] = value;
- }
- }
- }
- }
- #endregion
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LocalVariables.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LocalVariables.cs
deleted file mode 100644
index d848a643002..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LocalVariables.cs
+++ /dev/null
@@ -1,266 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- public sealed class LocalVariable {
- private const int IsBoxedFlag = 1;
- private const int InClosureFlag = 2;
-
- public readonly int Index;
- private int _flags;
-
- public bool IsBoxed {
- get { return (_flags & IsBoxedFlag) != 0; }
- set {
- if (value) {
- _flags |= IsBoxedFlag;
- } else {
- _flags &= ~IsBoxedFlag;
- }
- }
- }
-
- public bool InClosure {
- get { return (_flags & InClosureFlag) != 0; }
- }
-
- public bool InClosureOrBoxed {
- get { return InClosure | IsBoxed; }
- }
-
- internal LocalVariable(int index, bool closure, bool boxed) {
- Index = index;
- _flags = (closure ? InClosureFlag : 0) | (boxed ? IsBoxedFlag : 0);
- }
-
- internal Expression LoadFromArray(Expression frameData, Expression closure) {
- Expression result = Expression.ArrayAccess(InClosure ? closure : frameData, Expression.Constant(Index));
- return IsBoxed ? Expression.Convert(result, typeof(StrongBox<object>)) : result;
- }
-
- public override string ToString() {
- return String.Format("{0}: {1} {2}", Index, IsBoxed ? "boxed" : null, InClosure ? "in closure" : null);
- }
- }
-
- public struct LocalDefinition {
- private readonly int _index;
- private readonly ParameterExpression _parameter;
-
- internal LocalDefinition(int localIndex, ParameterExpression parameter) {
- _index = localIndex;
- _parameter = parameter;
- }
-
- public int Index {
- get {
- return _index;
- }
- }
-
- public ParameterExpression Parameter {
- get {
- return _parameter;
- }
- }
-
- public override bool Equals(object obj) {
- if (obj is LocalDefinition) {
- LocalDefinition other = (LocalDefinition)obj;
- return other.Index == Index && other.Parameter == Parameter;
- }
-
- return false;
- }
-
- public override int GetHashCode() {
- if (_parameter == null) {
- return 0;
- }
- return _parameter.GetHashCode() ^ _index.GetHashCode();
- }
-
- public static bool operator ==(LocalDefinition self, LocalDefinition other) {
- return self.Index == other.Index && self.Parameter == other.Parameter;
- }
-
- public static bool operator !=(LocalDefinition self, LocalDefinition other) {
- return self.Index != other.Index || self.Parameter != other.Parameter;
- }
- }
-
- public sealed class LocalVariables {
- private readonly HybridReferenceDictionary<ParameterExpression, VariableScope> _variables = new HybridReferenceDictionary<ParameterExpression, VariableScope>();
- private Dictionary<ParameterExpression, LocalVariable> _closureVariables;
-
- private int _localCount, _maxLocalCount;
-
- internal LocalVariables() {
- }
-
- public LocalDefinition DefineLocal(ParameterExpression variable, int start) {
- ContractUtils.RequiresNotNull(variable, "variable");
- ContractUtils.Requires(start >= 0, "start", "start must be positive");
-
- LocalVariable result = new LocalVariable(_localCount++, false, false);
- _maxLocalCount = System.Math.Max(_localCount, _maxLocalCount);
-
- VariableScope existing, newScope;
- if (_variables.TryGetValue(variable, out existing)) {
- newScope = new VariableScope(result, start, existing);
- if (existing.ChildScopes == null) {
- existing.ChildScopes = new List<VariableScope>();
- }
- existing.ChildScopes.Add(newScope);
- } else {
- newScope = new VariableScope(result, start, null);
- }
-
- _variables[variable] = newScope;
- return new LocalDefinition(result.Index, variable);
- }
-
- public void UndefineLocal(LocalDefinition definition, int end) {
- var scope = _variables[definition.Parameter];
- scope.Stop = end;
- if (scope.Parent != null) {
- _variables[definition.Parameter] = scope.Parent;
- } else {
- _variables.Remove(definition.Parameter);
- }
-
- _localCount--;
- }
-
- internal void Box(ParameterExpression variable, InstructionList instructions) {
- var scope = _variables[variable];
-
- LocalVariable local = scope.Variable;
- Debug.Assert(!local.IsBoxed && !local.InClosure);
- _variables[variable].Variable.IsBoxed = true;
-
- int curChild = 0;
- for (int i = scope.Start; i < scope.Stop && i < instructions.Count; i++) {
- if (scope.ChildScopes != null && scope.ChildScopes[curChild].Start == i) {
- // skip boxing in the child scope
- var child = scope.ChildScopes[curChild];
- i = child.Stop;
-
- curChild++;
- continue;
- }
-
- instructions.SwitchToBoxed(local.Index, i);
- }
- }
-
- public int LocalCount {
- get { return _maxLocalCount; }
- }
-
- public int GetOrDefineLocal(ParameterExpression var) {
- int index = GetLocalIndex(var);
- if (index == -1) {
- return DefineLocal(var, 0).Index;
- }
- return index;
- }
-
- public int GetLocalIndex(ParameterExpression var) {
- VariableScope loc;
- return _variables.TryGetValue(var, out loc) ? loc.Variable.Index : -1;
- }
-
- public bool TryGetLocalOrClosure(ParameterExpression var, out LocalVariable local) {
- VariableScope scope;
- if (_variables.TryGetValue(var, out scope)) {
- local = scope.Variable;
- return true;
- }
- if (_closureVariables != null && _closureVariables.TryGetValue(var, out local)) {
- return true;
- }
-
- local = null;
- return false;
- }
-
- /// <summary>
- /// Gets a copy of the local variables which are defined in the current scope.
- /// </summary>
- /// <returns></returns>
- internal Dictionary<ParameterExpression, LocalVariable> CopyLocals() {
- var res = new Dictionary<ParameterExpression, LocalVariable>(_variables.Count);
- foreach (var keyValue in _variables) {
- res[keyValue.Key] = keyValue.Value.Variable;
- }
- return res;
- }
-
- /// <summary>
- /// Checks to see if the given variable is defined within the current local scope.
- /// </summary>
- internal bool ContainsVariable(ParameterExpression variable) {
- return _variables.ContainsKey(variable);
- }
-
- /// <summary>
- /// Gets the variables which are defined in an outer scope and available within the current scope.
- /// </summary>
- internal Dictionary<ParameterExpression, LocalVariable> ClosureVariables {
- get {
- return _closureVariables;
- }
- }
-
- internal LocalVariable AddClosureVariable(ParameterExpression variable) {
- if (_closureVariables == null) {
- _closureVariables = new Dictionary<ParameterExpression, LocalVariable>();
- }
- LocalVariable result = new LocalVariable(_closureVariables.Count, true, false);
- _closureVariables.Add(variable, result);
- return result;
- }
-
- /// <summary>
- /// Tracks where a variable is defined and what range of instructions it's used in
- /// </summary>
- private sealed class VariableScope {
- public readonly int Start;
- public int Stop = Int32.MaxValue;
- public readonly LocalVariable Variable;
- public readonly VariableScope Parent;
- public List<VariableScope> ChildScopes;
-
- public VariableScope(LocalVariable variable, int start, VariableScope parent) {
- Variable = variable;
- Start = start;
- Parent = parent;
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LoopCompiler.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LoopCompiler.cs
deleted file mode 100644
index acc416ea5e5..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LoopCompiler.cs
+++ /dev/null
@@ -1,323 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Ast;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Interpreter {
- using AstUtils = Microsoft.Scripting.Ast.Utils;
- using LoopFunc = Func<object[], StrongBox<object>[], InterpretedFrame, int>;
- using System.Collections.ObjectModel;
-
- internal sealed class LoopCompiler : ExpressionVisitor {
- private struct LoopVariable {
- public ExpressionAccess Access;
-
- // a variable that holds on the strong box for closure variables:
- public ParameterExpression BoxStorage;
-
- public LoopVariable(ExpressionAccess access, ParameterExpression box) {
- Access = access;
- BoxStorage = box;
- }
-
- public override string ToString() {
- return Access.ToString() + " " + BoxStorage;
- }
- }
-
- private readonly ParameterExpression _frameDataVar;
- private readonly ParameterExpression _frameClosureVar;
- private readonly ParameterExpression _frameVar;
- private readonly LabelTarget _returnLabel;
- // locals and closure variables defined outside the loop
- private readonly Dictionary<ParameterExpression, LocalVariable> _outerVariables, _closureVariables;
- private readonly LoopExpression _loop;
- private ReadOnlyCollectionBuilder<ParameterExpression> _temps;
- // tracks variables that flow in and flow out for initialization and
- private readonly Dictionary<ParameterExpression, LoopVariable> _loopVariables;
- // variables which are defined and used within the loop
- private HashSet<ParameterExpression> _loopLocals;
-
- private readonly HybridReferenceDictionary<LabelTarget, BranchLabel> _labelMapping;
- private readonly int _loopStartInstructionIndex;
- private readonly int _loopEndInstructionIndex;
-
- internal LoopCompiler(LoopExpression loop, HybridReferenceDictionary<LabelTarget, BranchLabel> labelMapping, Dictionary<ParameterExpression, LocalVariable> locals,
- Dictionary<ParameterExpression, LocalVariable> closureVariables, int loopStartInstructionIndex, int loopEndInstructionIndex) {
- _loop = loop;
- _outerVariables = locals;
- _closureVariables = closureVariables;
- _frameDataVar = Expression.Parameter(typeof(object[]));
- _frameClosureVar = Expression.Parameter(typeof(StrongBox<object>[]));
- _frameVar = Expression.Parameter(typeof(InterpretedFrame));
- _loopVariables = new Dictionary<ParameterExpression, LoopVariable>();
- _returnLabel = Expression.Label(typeof(int));
- _labelMapping = labelMapping;
- _loopStartInstructionIndex = loopStartInstructionIndex;
- _loopEndInstructionIndex = loopEndInstructionIndex;
- }
-
- internal LoopFunc CreateDelegate() {
- var loop = (LoopExpression)Visit(_loop);
- var body = new ReadOnlyCollectionBuilder<Expression>();
- var finallyClause = new ReadOnlyCollectionBuilder<Expression>();
-
- foreach (var variable in _loopVariables) {
- LocalVariable local;
- if (!_outerVariables.TryGetValue(variable.Key, out local)) {
- local = _closureVariables[variable.Key];
- }
- Expression elemRef = local.LoadFromArray(_frameDataVar, _frameClosureVar);
-
- if (local.InClosureOrBoxed) {
- var box = variable.Value.BoxStorage;
- Debug.Assert(box != null);
- body.Add(Expression.Assign(box, elemRef));
- AddTemp(box);
- } else {
- // Always initialize the variable even if it is only written to.
- // If a write-only variable is actually not assigned during execution of the loop we will still write some value back.
- // This value must be the original value, which we assign at entry.
- body.Add(Expression.Assign(variable.Key, AstUtils.Convert(elemRef, variable.Key.Type)));
-
- if ((variable.Value.Access & ExpressionAccess.Write) != 0) {
- finallyClause.Add(Expression.Assign(elemRef, AstUtils.Box(variable.Key)));
- }
-
- AddTemp(variable.Key);
- }
- }
-
- if (finallyClause.Count > 0) {
- body.Add(Expression.TryFinally(loop, Expression.Block(finallyClause)));
- } else {
- body.Add(loop);
- }
-
- body.Add(Expression.Label(_returnLabel, Expression.Constant(_loopEndInstructionIndex - _loopStartInstructionIndex)));
-
- var lambda = Expression.Lambda<LoopFunc>(
- _temps != null ? Expression.Block(_temps.ToReadOnlyCollection(), body) : Expression.Block(body),
- new[] { _frameDataVar, _frameClosureVar, _frameVar }
- );
- return lambda.Compile();
- }
-
- protected override Expression VisitExtension(Expression node) {
- // Reduce extensions before we visit them so that we operate on a plain DLR tree,
- // where we know relationships among the nodes (which nodes represent write context etc.).
- if (node.CanReduce) {
- return Visit(node.Reduce());
- }
-
- return base.VisitExtension(node);
- }
-
- #region Gotos
-
- protected override Expression VisitGoto(GotoExpression node) {
- BranchLabel label;
-
- var target = node.Target;
- var value = Visit(node.Value);
-
- // TODO: Is it possible for an inner reducible node of the loop to rely on nodes produced by reducing outer reducible nodes?
-
- // Unknown label => must be within the loop:
- if (!_labelMapping.TryGetValue(target, out label)) {
- return node.Update(target, value);
- }
-
- // Known label within the loop:
- if (label.TargetIndex >= _loopStartInstructionIndex && label.TargetIndex < _loopEndInstructionIndex) {
- return node.Update(target, value);
- }
-
- return Expression.Return(_returnLabel,
- (value != null) ?
- Expression.Call(_frameVar, InterpretedFrame.GotoMethod, Expression.Constant(label.LabelIndex), AstUtils.Box(value)) :
- Expression.Call(_frameVar, InterpretedFrame.VoidGotoMethod, Expression.Constant(label.LabelIndex)),
- node.Type
- );
- }
-
- #endregion
-
- #region Local Variables
-
- // Gather all outer variables accessed in the loop.
- // Determines which ones are read from and written to.
- // We will consider a variable as "read" if it is read anywhere in the loop even though
- // the first operation might actually always be "write". We could do better if we had CFG.
-
- protected override Expression VisitBlock(BlockExpression node) {
- var variables = ((BlockExpression)node).Variables;
- var prevLocals = EnterVariableScope(variables);
-
- var res = base.VisitBlock(node);
-
- ExitVariableScope(prevLocals);
- return res;
- }
-
- private HashSet<ParameterExpression> EnterVariableScope(ICollection<ParameterExpression> variables) {
- if (_loopLocals == null) {
- _loopLocals = new HashSet<ParameterExpression>(variables);
- return null;
- }
-
- var prevLocals = new HashSet<ParameterExpression>(_loopLocals);
- _loopLocals.UnionWith(variables);
- return prevLocals;
- }
-
- protected override CatchBlock VisitCatchBlock(CatchBlock node) {
- if (node.Variable != null) {
- var prevLocals = EnterVariableScope(new[] { node.Variable });
- var res = base.VisitCatchBlock(node);
- ExitVariableScope(prevLocals);
- return res;
- } else {
- return base.VisitCatchBlock(node);
- }
- }
-
- protected override Expression VisitLambda<T>(Expression<T> node) {
- var prevLocals = EnterVariableScope(node.Parameters);
- try {
- return base.VisitLambda<T>(node);
- } finally {
- ExitVariableScope(prevLocals);
- }
- }
-
- private void ExitVariableScope(HashSet<ParameterExpression> prevLocals) {
- _loopLocals = prevLocals;
- }
-
- protected override Expression VisitBinary(BinaryExpression node) {
- // reduce compound assignments:
- if (node.CanReduce) {
- return Visit(node.Reduce());
- }
- Debug.Assert(!node.NodeType.IsReadWriteAssignment());
-
- var param = node.Left as ParameterExpression;
- if (param != null && node.NodeType == ExpressionType.Assign) {
- var left = VisitVariable(param, ExpressionAccess.Write);
- var right = Visit(node.Right);
-
- // left parameter is a boxed variable:
- if (left.Type != param.Type) {
- Debug.Assert(left.Type == typeof(object));
-
- Expression rightVar;
- if (right.NodeType != ExpressionType.Parameter) {
- // { left.Value = (object)(rightVar = right), rightVar }
- rightVar = AddTemp(Expression.Parameter(right.Type));
- right = Expression.Assign(rightVar, right);
- } else {
- // { left.Value = (object)right, right }
- rightVar = right;
- }
-
- return Expression.Block(
- node.Update(left, Expression.Convert(right, left.Type)),
- rightVar
- );
- } else {
- return node.Update(left, right);
- }
-
- } else {
- return base.VisitBinary(node);
- }
- }
-
- protected override Expression VisitUnary(UnaryExpression node) {
- // reduce inplace increment/decrement:
- if (node.CanReduce) {
- return Visit(node.Reduce());
- }
- Debug.Assert(!node.NodeType.IsReadWriteAssignment());
- return base.VisitUnary(node);
- }
-
- // TODO: if we supported ref/out parameter we would need to override
- // MethodCallExpression, VisitDynamic and VisitNew
-
- protected override Expression VisitParameter(ParameterExpression node) {
- return VisitVariable(node, ExpressionAccess.Read);
- }
-
- private Expression VisitVariable(ParameterExpression node, ExpressionAccess access) {
- ParameterExpression box;
- LoopVariable existing;
- LocalVariable loc;
-
- if (_loopLocals.Contains(node)) {
- // local to the loop - not propagated in or out
- return node;
- } else if (_loopVariables.TryGetValue(node, out existing)) {
- // existing outer variable that we are already tracking
- box = existing.BoxStorage;
- _loopVariables[node] = new LoopVariable(existing.Access | access, box);
- } else if (_outerVariables.TryGetValue(node, out loc) ||
- (_closureVariables != null && _closureVariables.TryGetValue(node, out loc))) {
- // not tracking this variable yet, but defined in outer scope and seen for the 1st time
- box = loc.InClosureOrBoxed ? Expression.Parameter(typeof(StrongBox<object>), node.Name) : null;
- _loopVariables[node] = new LoopVariable(access, box);
- } else {
- // node is a variable defined in a nested lambda -> skip
- return node;
- }
-
- if (box != null) {
- if ((access & ExpressionAccess.Write) != 0) {
- // compound assignments were reduced:
- Debug.Assert((access & ExpressionAccess.Read) == 0);
-
- // box.Value = (object)rhs
- return LightCompiler.Unbox(box);
- } else {
- // (T)box.Value
- return Expression.Convert(LightCompiler.Unbox(box), node.Type);
- }
- }
-
- return node;
- }
-
- private ParameterExpression AddTemp(ParameterExpression variable) {
- if (_temps == null) {
- _temps = new ReadOnlyCollectionBuilder<ParameterExpression>();
- }
-
- _temps.Add(variable);
- return variable;
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/RuntimeVariables.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/RuntimeVariables.cs
deleted file mode 100644
index e8b8e98520c..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/RuntimeVariables.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Runtime.CompilerServices;
-
-namespace Microsoft.Scripting.Interpreter {
- internal sealed class RuntimeVariables : IRuntimeVariables {
- private readonly IStrongBox[] _boxes;
-
- private RuntimeVariables(IStrongBox[] boxes) {
- _boxes = boxes;
- }
-
- int IRuntimeVariables.Count {
- get {
- return _boxes.Length;
- }
- }
-
- object IRuntimeVariables.this[int index] {
- get {
- return _boxes[index].Value;
- }
- set {
- _boxes[index].Value = value;
- }
- }
-
- internal static IRuntimeVariables Create(IStrongBox[] boxes) {
- return new RuntimeVariables(boxes);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Math/BigIntegerV4.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Math/BigIntegerV4.cs
deleted file mode 100644
index 303eb7521b6..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Math/BigIntegerV4.cs
+++ /dev/null
@@ -1,614 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-#if FEATURE_NUMERICS
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Text;
-using Microsoft.Scripting.Utils;
-using BigInt = System.Numerics.BigInteger;
-
-namespace Microsoft.Scripting.Math {
- /// <summary>
- /// arbitrary precision integers
- /// </summary>
- [Serializable]
- public sealed class BigInteger : IFormattable, IComparable, IEquatable<BigInteger> {
- internal readonly BigInt Value;
-
- [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
- public static readonly BigInteger Zero = new BigInteger((BigInt)0);
- [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
- public static readonly BigInteger One = new BigInteger((BigInt)1);
-
- public BigInteger(BigInt value) {
- Value = value;
- }
-
- [CLSCompliant(false)]
- public static BigInteger Create(ulong v) {
- return new BigInteger(new BigInt(v));
- }
-
- [CLSCompliant(false)]
- public static BigInteger Create(uint v) {
- return new BigInteger(new BigInt(v));
- }
-
- public static BigInteger Create(long v) {
- return new BigInteger(new BigInt(v));
- }
-
- public static BigInteger Create(int v) {
- return new BigInteger(new BigInt(v));
- }
-
- public static BigInteger Create(decimal v) {
- return new BigInteger(new BigInt(v));
- }
-
- public static BigInteger Create(byte[] v) {
- return new BigInteger(v);
- }
-
- public static BigInteger Create(double v) {
- return new BigInteger(new BigInt(v));
- }
-
- public static implicit operator BigInteger(byte i) {
- return new BigInteger((BigInt)i);
- }
-
- [CLSCompliant(false)]
- public static implicit operator BigInteger(sbyte i) {
- return new BigInteger((BigInt)i);
- }
-
- public static implicit operator BigInteger(short i) {
- return new BigInteger((BigInt)i);
- }
-
- [CLSCompliant(false)]
- public static implicit operator BigInteger(ushort i) {
- return new BigInteger((BigInt)i);
- }
-
- [CLSCompliant(false)]
- public static implicit operator BigInteger(uint i) {
- return new BigInteger((BigInt)i);
- }
-
- public static implicit operator BigInteger(int i) {
- return new BigInteger((BigInt)i);
- }
-
- [CLSCompliant(false)]
- public static implicit operator BigInteger(ulong i) {
- return new BigInteger((BigInt)i);
- }
-
- public static implicit operator BigInteger(long i) {
- return new BigInteger((BigInt)i);
- }
-
- public static implicit operator BigInteger(decimal self) {
- return new BigInteger((BigInt)self);
- }
-
- public static explicit operator BigInteger(double self) {
- return new BigInteger((BigInt)self);
- }
-
- public static explicit operator BigInteger(float self) {
- return new BigInteger((BigInt)self);
- }
-
- public static explicit operator double(BigInteger self) {
- return (double)self.Value;
- }
-
- public static explicit operator float(BigInteger self) {
- return (float)self.Value;
- }
-
- public static explicit operator decimal(BigInteger self) {
- return (decimal)self.Value;
- }
-
- public static explicit operator byte(BigInteger self) {
- return (byte)self.Value;
- }
-
- [CLSCompliant(false)]
- public static explicit operator sbyte(BigInteger self) {
- return (sbyte)self.Value;
- }
-
- [CLSCompliant(false)]
- public static explicit operator UInt16(BigInteger self) {
- return (UInt16)self.Value;
- }
-
- public static explicit operator Int16(BigInteger self) {
- return (Int16)self.Value;
- }
-
- [CLSCompliant(false)]
- public static explicit operator UInt32(BigInteger self) {
- return (UInt32)self.Value;
- }
-
- public static explicit operator Int32(BigInteger self) {
- return (Int32)self.Value;
- }
-
- public static explicit operator Int64(BigInteger self) {
- return (Int64)self.Value;
- }
-
- [CLSCompliant(false)]
- public static explicit operator UInt64(BigInteger self) {
- return (UInt64)self.Value;
- }
-
- public static implicit operator BigInteger(BigInt value) {
- return new BigInteger(value);
- }
-
- public static implicit operator BigInt(BigInteger value) {
- return value.Value;
- }
-
- public BigInteger(BigInteger copy) {
- if (object.ReferenceEquals(copy, null)) {
- throw new ArgumentNullException("copy");
- }
- Value = copy.Value;
- }
-
- public BigInteger(byte[] data) {
- ContractUtils.RequiresNotNull(data, "data");
-
- Value = new BigInt(data);
- }
-
- public BigInteger(int sign, byte[] data) {
- ContractUtils.RequiresNotNull(data, "data");
- ContractUtils.Requires(sign >= -1 && sign <= +1, "sign");
-
- Value = new BigInt(data);
- if (sign < 0) {
- Value = -Value;
- }
- }
-
- [CLSCompliant(false)]
- public BigInteger(int sign, uint[] data) {
- ContractUtils.RequiresNotNull(data, "data");
- ContractUtils.Requires(sign >= -1 && sign <= +1, "sign");
- int length = GetLength(data);
- ContractUtils.Requires(length == 0 || sign != 0, "sign");
- if (length == 0) {
- Value = 0;
- return;
- }
-
- bool highest = (data[length - 1] & 0x80000000) != 0;
- byte[] bytes = new byte[length * 4 + (highest ? 1 : 0)];
- int j = 0;
- for (int i = 0; i < length; i++) {
- ulong w = data[i];
- bytes[j++] = (byte)(w & 0xff);
- bytes[j++] = (byte)((w >> 8) & 0xff);
- bytes[j++] = (byte)((w >> 16) & 0xff);
- bytes[j++] = (byte)((w >> 24) & 0xff);
- }
-
- Value = new BigInt(bytes);
- if (sign < 0) {
- Value = -Value;
- }
- }
-
- [CLSCompliant(false)]
- public uint[] GetWords() {
- return Value.GetWords();
- }
-
- public int GetBitCount() {
- return Value.GetBitCount();
- }
-
- public int GetWordCount() {
- return Value.GetWordCount();
- }
-
- public int GetByteCount() {
- return Value.GetByteCount();
- }
-
- /// <summary>
- /// Return the sign of this BigInteger: -1, 0, or 1.
- /// </summary>
- public int Sign {
- get {
- return Value.Sign;
- }
- }
-
- public bool AsInt64(out long ret) {
- if (Value >= Int64.MinValue && Value <= Int64.MaxValue) {
- ret = (long)Value;
- return true;
- }
- ret = 0;
- return false;
- }
-
- [CLSCompliant(false)]
- public bool AsUInt32(out uint ret) {
- if (Value >= UInt32.MinValue && Value <= UInt32.MaxValue) {
- ret = (UInt32)Value;
- return true;
- }
- ret = 0;
- return false;
- }
-
- [CLSCompliant(false)]
- public bool AsUInt64(out ulong ret) {
- if (Value >= UInt64.MinValue && Value <= UInt64.MaxValue) {
- ret = (UInt64)Value;
- return true;
- }
- ret = 0;
- return false;
- }
-
- public bool AsInt32(out int ret) {
- if (Value >= Int32.MinValue && Value <= Int32.MaxValue) {
- ret = (Int32)Value;
- return true;
- }
- ret = 0;
- return false;
- }
-
- [CLSCompliant(false)]
- public uint ToUInt32() {
- return (uint)Value;
- }
-
- public int ToInt32() {
- return (int)Value;
- }
-
- public decimal ToDecimal() {
- return (decimal)Value;
- }
-
- [CLSCompliant(false)]
- public ulong ToUInt64() {
- return (ulong)Value;
- }
-
- public long ToInt64() {
- return (long)Value;
- }
-
- private static int GetLength(uint[] data) {
- int ret = data.Length - 1;
- while (ret >= 0 && data[ret] == 0) ret--;
- return ret + 1;
- }
-
- public static int Compare(BigInteger x, BigInteger y) {
- return BigInt.Compare(x.Value, y.Value);
- }
-
- public static bool operator ==(BigInteger x, int y) {
- return x.Value == y;
- }
-
- public static bool operator !=(BigInteger x, int y) {
- return x.Value != y;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] // TODO: fix
- public static bool operator ==(BigInteger x, double y) {
- if (object.ReferenceEquals(x, null)) {
- throw new ArgumentNullException("x");
- }
-
- // we can hold all double values, but not all double values
- // can hold BigInteger values, and we may lose precision. Convert
- // the double to a big int, then compare.
-
- if ((y % 1) != 0) return false; // not a whole number, can't be equal
-
- return x.Value == (BigInt)y;
- }
-
- public static bool operator ==(double x, BigInteger y) {
- return y == x;
- }
-
- public static bool operator !=(BigInteger x, double y) {
- return !(x == y);
- }
-
- public static bool operator !=(double x, BigInteger y) {
- return !(x == y);
- }
-
-
- public static bool operator ==(BigInteger x, BigInteger y) {
- return Compare(x, y) == 0;
- }
-
- public static bool operator !=(BigInteger x, BigInteger y) {
- return Compare(x, y) != 0;
- }
- public static bool operator <(BigInteger x, BigInteger y) {
- return Compare(x, y) < 0;
- }
- public static bool operator <=(BigInteger x, BigInteger y) {
- return Compare(x, y) <= 0;
- }
- public static bool operator >(BigInteger x, BigInteger y) {
- return Compare(x, y) > 0;
- }
- public static bool operator >=(BigInteger x, BigInteger y) {
- return Compare(x, y) >= 0;
- }
-
- public static BigInteger Add(BigInteger x, BigInteger y) {
- return x + y;
- }
-
- public static BigInteger operator +(BigInteger x, BigInteger y) {
- return new BigInteger(x.Value + y.Value);
- }
-
- public static BigInteger Subtract(BigInteger x, BigInteger y) {
- return x - y;
- }
-
- public static BigInteger operator -(BigInteger x, BigInteger y) {
- return new BigInteger(x.Value - y.Value);
- }
-
- public static BigInteger Multiply(BigInteger x, BigInteger y) {
- return x * y;
- }
-
- public static BigInteger operator *(BigInteger x, BigInteger y) {
- return new BigInteger(x.Value * y.Value);
- }
-
- public static BigInteger Divide(BigInteger x, BigInteger y) {
- return x / y;
- }
-
- public static BigInteger operator /(BigInteger x, BigInteger y) {
- BigInteger dummy;
- return DivRem(x, y, out dummy);
- }
-
- public static BigInteger Mod(BigInteger x, BigInteger y) {
- return x % y;
- }
-
- public static BigInteger operator %(BigInteger x, BigInteger y) {
- BigInteger ret;
- DivRem(x, y, out ret);
- return ret;
- }
-
- public static BigInteger DivRem(BigInteger x, BigInteger y, out BigInteger remainder) {
- BigInt rem;
- BigInt result = BigInt.DivRem(x.Value, y.Value, out rem);
- remainder = new BigInteger(rem);
- return new BigInteger(result);
- }
-
- public static BigInteger BitwiseAnd(BigInteger x, BigInteger y) {
- return x & y;
- }
-
- public static BigInteger operator &(BigInteger x, BigInteger y) {
- return new BigInteger(x.Value & y.Value);
- }
-
- public static BigInteger BitwiseOr(BigInteger x, BigInteger y) {
- return x | y;
- }
-
- public static BigInteger operator |(BigInteger x, BigInteger y) {
- return new BigInteger(x.Value | y.Value);
- }
-
- public static BigInteger Xor(BigInteger x, BigInteger y) {
- return x ^ y;
- }
-
- public static BigInteger operator ^(BigInteger x, BigInteger y) {
- return new BigInteger(x.Value ^ y.Value);
- }
-
- public static BigInteger LeftShift(BigInteger x, int shift) {
- return x << shift;
- }
-
- public static BigInteger operator <<(BigInteger x, int shift) {
- return new BigInteger(x.Value << shift);
- }
-
- public static BigInteger RightShift(BigInteger x, int shift) {
- return x >> shift;
- }
-
- public static BigInteger operator >>(BigInteger x, int shift) {
- return new BigInteger(x.Value >> shift);
- }
-
- public static BigInteger Negate(BigInteger x) {
- return -x;
- }
-
- public static BigInteger operator -(BigInteger x) {
- return new BigInteger(-x.Value);
- }
-
- public BigInteger OnesComplement() {
- return ~this;
- }
-
- public static BigInteger operator ~(BigInteger x) {
- return new BigInteger(~x.Value);
- }
-
- public BigInteger Abs() {
- return new BigInteger(BigInt.Abs(Value));
- }
-
- public BigInteger Power(int exp) {
- return new BigInteger(BigInt.Pow(Value, exp));
- }
-
- public BigInteger ModPow(int power, BigInteger mod) {
- return new BigInteger(BigInt.ModPow(Value, power, mod.Value));
- }
-
- public BigInteger ModPow(BigInteger power, BigInteger mod) {
- return new BigInteger(BigInt.ModPow(Value, power.Value, mod.Value));
- }
-
- public BigInteger Square() {
- return this * this;
- }
-
-#if !SILVERLIGHT
- public static BigInteger Parse(string str) {
- return new BigInteger(BigInt.Parse(str));
- }
-#endif
-
- public override string ToString() {
- return ToString(10);
- }
-
- public string ToString(int @base) {
- return MathUtils.BigIntegerToString(GetWords(), Sign, @base, false);
- }
-
- public string ToString(string format) {
- return Value.ToString(format);
- }
-
- public override int GetHashCode() {
- return Value.GetHashCode();
- }
-
- public override bool Equals(object obj) {
- return Equals(obj as BigInteger);
- }
-
- public bool Equals(BigInteger other) {
- if (object.ReferenceEquals(other, null)) return false;
- return this == other;
- }
-
- public bool IsNegative() {
- return Value.Sign < 0;
- }
-
- public bool IsZero() {
- return Value.Sign == 0;
- }
-
- public bool IsPositive() {
- return Value.Sign > 0;
- }
-
- public bool IsEven {
- get { return Value.IsEven; }
- }
-
- public bool IsPowerOfTwo {
- get {
- return Value.IsPowerOfTwo;
- }
- }
-
- public double Log(Double newBase) {
- return BigInt.Log(Value, newBase);
- }
-
- /// <summary>
- /// Calculates the natural logarithm of the BigInteger.
- /// </summary>
- public double Log() {
- return BigInt.Log(Value);
- }
-
- /// <summary>
- /// Calculates log base 10 of a BigInteger.
- /// </summary>
- public double Log10() {
- return BigInt.Log10(Value);
- }
-
-#region IComparable Members
-
- public int CompareTo(object obj) {
- if (obj == null) {
- return 1;
- }
- BigInteger o = obj as BigInteger;
- if (object.ReferenceEquals(o, null)) {
- throw new ArgumentException("expected integer");
- }
- return Compare(this, o);
- }
-
- #endregion
-
- /// <summary>
- /// Return the value of this BigInteger as a little-endian twos-complement
- /// byte array, using the fewest number of bytes possible. If the value is zero,
- /// return an array of one byte whose element is 0x00.
- /// </summary>
- public byte[] ToByteArray() {
- return Value.ToByteArray();
- }
-
- public string ToString(IFormatProvider provider) {
- return Value.ToString(provider);
- }
-
-#region IFormattable Members
-
- string IFormattable.ToString(string format, IFormatProvider formatProvider) {
- return Value.ToString(format, formatProvider);
- }
-
- #endregion
- }
-}
-#endif
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Math/Complex64.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Math/Complex64.cs
deleted file mode 100644
index 6a57c23f15a..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Math/Complex64.cs
+++ /dev/null
@@ -1,280 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using Microsoft.Scripting.Utils;
-
-#if FEATURE_NUMERICS
-using BigInt = System.Numerics.BigInteger;
-#endif
-
-namespace Microsoft.Scripting.Math {
-
-#if !MONO_INTERPRETER
- /// <summary>
- /// Implementation of the complex number data type.
- /// </summary>
- [Serializable]
- public struct Complex64 {
- public static readonly Complex64 Zero = new Complex64(0.0, 0.0);
- public static readonly Complex64 One = new Complex64(1.0, 0.0);
- public static readonly Complex64 ImaginaryOne = new Complex64(0.0, 1.0);
-
- private readonly double real, imag;
-
- public static Complex64 MakeImaginary(double imag) {
- return new Complex64(0.0, imag);
- }
-
- public static Complex64 MakeReal(double real) {
- return new Complex64(real, 0.0);
- }
-
- public static Complex64 Make(double real, double imag) {
- return new Complex64(real, imag);
- }
-
- public Complex64(double real)
- : this(real, 0.0) {
- }
-
- public Complex64(double real, double imag) {
- this.real = real;
- this.imag = imag;
- }
-
- public bool IsZero {
- get {
- return real == 0.0 && imag == 0.0;
- }
- }
-
- public double Real {
- get {
- return real;
- }
- }
-
- public double Imag {
- get {
- return imag;
- }
- }
-
- public Complex64 Conjugate() {
- return new Complex64(real, -imag);
- }
-
-
- public override string ToString() {
- if (real == 0.0) return imag.ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "j";
- else if (imag < 0.0) return string.Format(System.Globalization.CultureInfo.InvariantCulture.NumberFormat, "({0}{1}j)", real, imag);
- else return string.Format(System.Globalization.CultureInfo.InvariantCulture.NumberFormat, "({0}+{1}j)", real, imag);
- }
-
- public static implicit operator Complex64(bool b) {
- return b ? One : Zero;
- }
-
- public static implicit operator Complex64(int i) {
- return MakeReal(i);
- }
-
- [CLSCompliant(false)]
- public static implicit operator Complex64(uint i) {
- return MakeReal(i);
- }
-
- public static implicit operator Complex64(short i) {
- return MakeReal(i);
- }
-
- [CLSCompliant(false)]
- public static implicit operator Complex64(ushort i) {
- return MakeReal(i);
- }
-
- public static implicit operator Complex64(long l) {
- return MakeReal(l);
- }
- [CLSCompliant(false)]
- public static implicit operator Complex64(ulong i) {
- return MakeReal(i);
- }
-
- [CLSCompliant(false)]
- public static implicit operator Complex64(sbyte i) {
- return MakeReal(i);
- }
-
- public static implicit operator Complex64(byte i) {
- return MakeReal(i);
- }
-
- public static implicit operator Complex64(float f) {
- return MakeReal(f);
- }
-
- public static implicit operator Complex64(double d) {
- return MakeReal(d);
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] // TODO: fix
- public static implicit operator Complex64(BigInteger i) {
- ContractUtils.RequiresNotNull(i, "i");
-
- // throws an overflow exception if we can't handle the value.
- return MakeReal((double)i);
- }
-
-#if FEATURE_NUMERICS
- public static implicit operator Complex64(BigInt i) {
- // throws an overflow exception if we can't handle the value.
- return MakeReal((double)i);
- }
-#endif
-
- public static bool operator ==(Complex64 x, Complex64 y) {
- return x.real == y.real && x.imag == y.imag;
- }
-
- public static bool operator !=(Complex64 x, Complex64 y) {
- return x.real != y.real || x.imag != y.imag;
- }
-
- public static Complex64 Add(Complex64 x, Complex64 y) {
- return x + y;
- }
-
- public static Complex64 operator +(Complex64 x, Complex64 y) {
- return new Complex64(x.real + y.real, x.imag + y.imag);
- }
-
- public static Complex64 Subtract(Complex64 x, Complex64 y) {
- return x - y;
- }
-
- public static Complex64 operator -(Complex64 x, Complex64 y) {
- return new Complex64(x.real - y.real, x.imag - y.imag);
- }
-
- public static Complex64 Multiply(Complex64 x, Complex64 y) {
- return x * y;
- }
-
- public static Complex64 operator *(Complex64 x, Complex64 y) {
- return new Complex64(x.real * y.real - x.imag * y.imag, x.real * y.imag + x.imag * y.real);
- }
-
- public static Complex64 Divide(Complex64 x, Complex64 y) {
- return x / y;
- }
-
- public static Complex64 operator /(Complex64 a, Complex64 b) {
- if (b.IsZero) {
- throw new DivideByZeroException("complex division by zero");
- }
-
- double real, imag, den, r;
-
- if (System.Math.Abs(b.real) >= System.Math.Abs(b.imag)) {
- r = b.imag / b.real;
- den = b.real + r * b.imag;
- real = (a.real + a.imag * r) / den;
- imag = (a.imag - a.real * r) / den;
- } else {
- r = b.real / b.imag;
- den = b.imag + r * b.real;
- real = (a.real * r + a.imag) / den;
- imag = (a.imag * r - a.real) / den;
- }
-
- return new Complex64(real, imag);
- }
-
- public static Complex64 Negate(Complex64 x) {
- return -x;
- }
-
- public static Complex64 operator -(Complex64 x) {
- return new Complex64(-x.real, -x.imag);
- }
-
- public static Complex64 Plus(Complex64 x) {
- return +x;
- }
-
- public static Complex64 operator +(Complex64 x) {
- return x;
- }
-
- [Obsolete("Deprecated - consider using MS.Scripting.Utils.MathUtils.Hypot")]
- public static double Hypot(double x, double y) {
- return MathUtils.Hypot(x, y);
- }
-
- public double Abs() {
- return MathUtils.Hypot(real, imag);
- }
-
- public Complex64 Power(Complex64 y) {
- double c = y.real;
- double d = y.imag;
- int power = (int)c;
-
- if (power == c && power >= 0 && d == .0) {
- Complex64 result = One;
- if (power == 0) return result;
- Complex64 factor = this;
- while (power != 0) {
- if ((power & 1) != 0) {
- result = result * factor;
- }
- factor = factor * factor;
- power >>= 1;
- }
- return result;
- } else if (IsZero) {
- return y.IsZero ? One : Zero;
- } else {
- double a = real;
- double b = imag;
- double powers = a * a + b * b;
- double arg = System.Math.Atan2(b, a);
- double mul = System.Math.Pow(powers, c / 2) * System.Math.Exp(-d * arg);
- double common = c * arg + .5 * d * System.Math.Log(powers);
- return new Complex64(mul * System.Math.Cos(common), mul * System.Math.Sin(common));
- }
- }
-
- public override int GetHashCode() {
- // The Object.GetHashCode function needs to be consistent with the Object.Equals function.
- // Languages that build on top of this may have a more flexible equality function and
- // so may not be able to use this hash function directly.
- // For example, Python allows that c=Complex64(1.5, 0), f = 1.5f, c==f.
- // so then the hash(f) == hash(c). Since the python (and other languages) can define an arbitrary
- // hash(float) function, the language may need to define a matching hash(complex) function for
- // the cases where the float and complex numbers overlap.
- return (int)real + (int)imag * 1000003;
- }
-
- public override bool Equals(object obj) {
- if (!(obj is Complex64)) return false;
- return this == ((Complex64)obj);
- }
- }
-#endif
-
-} \ No newline at end of file
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Properties/AssemblyInfo.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Properties/AssemblyInfo.cs
deleted file mode 100644
index 76977f57cd2..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Security;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("Microsoft.Scripting")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Microsoft")]
-[assembly: AssemblyProduct("Microsoft.Scripting")]
-[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-[assembly: CLSCompliant(true)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("1bbee69c-30c5-41df-8912-b81da6d658c2")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Revision and Build Numbers
-// by using the '*' as shown below:
-#if !CLR2 && !SILVERLIGHT && !WIN8 && !ANDROID && !WP75
-[assembly: System.Security.SecurityRules(SecurityRuleSet.Level1)]
-#endif
-[assembly: SecurityTransparent]
-
-[assembly: System.Resources.NeutralResourcesLanguage("en-US")]
-[assembly: InternalsVisibleTo("TestInternalDLR, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c10ce00dd2e0ce5046d68183d3ad035b47e92bf0ce7bcf8a03a217ca5d0b0c7db973fdf97579b52b502a23d4069dbf043389e1ab65a1d6c508a9837f3e2350f15e05cc63c0fc4b0410867a51919090e4c33f80203e9b0035b21c32bae20f98b068f90d99a50133a5336480d94039b176519f5fd8524765f33be43da65c4b68ba")]
-
-#if !SILVERLIGHT
-[assembly: AssemblyVersion("1.1.0.30")]
-[assembly: AssemblyFileVersion("1.1.0.30")]
-[assembly: AssemblyInformationalVersion("1.1")]
-#endif
-
-#if !SILVERLIGHT && !WP75
-[assembly: AllowPartiallyTrustedCallers]
-[assembly: TypeForwardedTo(typeof(Microsoft.Scripting.Runtime.DynamicStackFrame))]
-#endif
-
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Properties/GlobalSuppressions.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Properties/GlobalSuppressions.cs
deleted file mode 100644
index 253f679b7e6..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Properties/GlobalSuppressions.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-// This file is used by Code Analysis to maintain SuppressMessage
-// attributes that are applied to this project.
-// Project-level suppressions either have no target or are given
-// a specific target and scoped to a namespace, type, member, etc.
-//
-// To add a suppression to this file, right-click the message in the
-// Error List, point to "Suppress Message(s)", and click
-// "In Project Suppression File".
-// You do not need to add suppressions to this file manually.
-
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Dynamic.SR.#GetObject(System.String)")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Dynamic.SR.#GetString(System.String,System.Boolean&)")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Dynamic.SR.#Resources")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Dynamic.Error.#ArgumentNull(System.String)")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Dynamic.Error.#ArgumentOutOfRange(System.String)")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Dynamic.Error.#NotImplemented()")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Dynamic.Error.#NotSupported()")]
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ArgumentArray.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ArgumentArray.cs
deleted file mode 100644
index b6484afc31d..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ArgumentArray.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Dynamic;
-using System.Reflection;
-using Microsoft.Scripting.Utils;
-
-namespace Microsoft.Scripting.Runtime {
- using AstUtils = Microsoft.Scripting.Ast.Utils;
-
- /// <summary>
- /// Wraps all arguments passed to a dynamic site with more arguments than can be accepted by a Func/Action delegate.
- /// The binder generating a rule for such a site should unwrap the arguments first and then perform a binding to them.
- /// </summary>
- public sealed class ArgumentArray {
- private readonly object[] _arguments;
-
- // the index of the first item _arguments that represents an argument:
- private readonly int _first;
-
- // the number of items in _arguments that represent the arguments:
- private readonly int _count;
-
- internal ArgumentArray(object[] arguments, int first, int count) {
- _arguments = arguments;
- _first = first;
- _count = count;
- }
-
- public int Count {
- get { return _count; }
- }
-
- public object GetArgument(int index) {
- ContractUtils.RequiresArrayIndex(_arguments, index, "index");
- return _arguments[_first + index];
- }
-
- public DynamicMetaObject GetMetaObject(Expression parameter, int index) {
- return DynamicMetaObject.Create(
- GetArgument(index),
- Expression.Call(
- _GetArgMethod,
- AstUtils.Convert(parameter, typeof(ArgumentArray)),
- AstUtils.Constant(index)
- )
- );
- }
-
- [CLSCompliant(false)]
- public static object GetArg(ArgumentArray array, int index) {
- return array._arguments[array._first + index];
- }
-
- private static readonly MethodInfo _GetArgMethod = new Func<ArgumentArray, int, object>(GetArg).GetMethodInfo();
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/DynamicNull.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/DynamicNull.cs
deleted file mode 100644
index 378bea4d090..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/DynamicNull.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-namespace Microsoft.Scripting.Runtime {
- /// <summary>
- /// Represents the type of a null value.
- /// </summary>
- public sealed class DynamicNull {
- /// <summary>
- /// Private constructor is never called since 'null' is the only valid instance.
- /// </summary>
- private DynamicNull() { }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ExceptionHelpers.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ExceptionHelpers.cs
deleted file mode 100644
index 43350e7611e..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ExceptionHelpers.cs
+++ /dev/null
@@ -1,79 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Threading;
-using Microsoft.Scripting.Actions;
-using Microsoft.Scripting.Generation;
-
-namespace Microsoft.Scripting.Runtime {
- public static class ExceptionHelpers {
-#if FEATURE_STACK_TRACE
- private const string prevStackTraces = "PreviousStackTraces";
-
- /// <summary>
- /// Updates an exception before it's getting re-thrown so
- /// we can present a reasonable stack trace to the user.
- /// </summary>
- public static Exception UpdateForRethrow(Exception rethrow) {
-#if !SILVERLIGHT
- List<StackTrace> prev;
-
- // we don't have any dynamic stack trace data, capture the data we can
- // from the raw exception object.
- StackTrace st = new StackTrace(rethrow, true);
-
- if (!TryGetAssociatedStackTraces(rethrow, out prev)) {
- prev = new List<StackTrace>();
- AssociateStackTraces(rethrow, prev);
- }
-
- prev.Add(st);
-
-#endif
- return rethrow;
- }
-
- /// <summary>
- /// Returns all the stack traces associates with an exception
- /// </summary>
- public static IList<StackTrace> GetExceptionStackTraces(Exception rethrow) {
- List<StackTrace> result;
- return TryGetAssociatedStackTraces(rethrow, out result) ? result : null;
- }
-
- private static void AssociateStackTraces(Exception e, List<StackTrace> traces) {
- e.Data[prevStackTraces] = traces;
- }
-
- private static bool TryGetAssociatedStackTraces(Exception e, out List<StackTrace> traces) {
- traces = e.Data[prevStackTraces] as List<StackTrace>;
- return traces != null;
- }
-#else
- public static Exception UpdateForRethrow(Exception rethrow) {
- return rethrow;
- }
-#endif
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ScriptingRuntimeHelpers.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ScriptingRuntimeHelpers.cs
deleted file mode 100644
index f7fc8b33eda..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ScriptingRuntimeHelpers.cs
+++ /dev/null
@@ -1,261 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Actions;
-using Microsoft.Scripting.Generation;
-using Microsoft.Scripting.Utils;
-using Microsoft.Scripting.Interpreter;
-
-namespace Microsoft.Scripting.Runtime {
- /// <summary>
- /// These are some generally useful helper methods. Currently the only methods are those to
- /// cached boxed representations of commonly used primitive types so that they can be shared.
- /// This is useful to most dynamic languages that use object as a universal type.
- ///
- /// The methods in RuntimeHelepers are caleld by the generated code. From here the methods may
- /// dispatch to other parts of the runtime to get bulk of the work done, but the entry points
- /// should be here.
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
- public static partial class ScriptingRuntimeHelpers {
- private const int MIN_CACHE = -100;
- private const int MAX_CACHE = 1000;
- private static readonly object[] cache = MakeCache();
-
- /// <summary>
- /// A singleton boxed boolean true.
- /// </summary>
- public static readonly object True = true;
-
- /// <summary>
- ///A singleton boxed boolean false.
- /// </summary>
- public static readonly object False = false;
-
- internal static readonly MethodInfo BooleanToObjectMethod = typeof(ScriptingRuntimeHelpers).GetMethod("BooleanToObject");
- internal static readonly MethodInfo Int32ToObjectMethod = typeof(ScriptingRuntimeHelpers).GetMethod("Int32ToObject");
-
- private static object[] MakeCache() {
- object[] result = new object[MAX_CACHE - MIN_CACHE];
-
- for (int i = 0; i < result.Length; i++) {
- result[i] = (object)(i + MIN_CACHE);
- }
-
- return result;
- }
-
-#if DEBUG
- public static void NoteException(Exception e) {
- PerfTrack.NoteEvent(PerfTrack.Categories.Exceptions, "LightEH Missed: " + e.GetType());
- }
-#endif
-
- /// <summary>
- /// Gets a singleton boxed value for the given integer if possible, otherwise boxes the integer.
- /// </summary>
- /// <param name="value">The value to box.</param>
- /// <returns>The boxed value.</returns>
- public static object Int32ToObject(Int32 value) {
- // caches improves pystone by ~5-10% on MS .Net 1.1, this is a very integer intense app
- // TODO: investigate if this still helps perf. There's evidence that it's harmful on
- // .NET 3.5 and 4.0
- if (value < MAX_CACHE && value >= MIN_CACHE) {
- return cache[value - MIN_CACHE];
- }
- return (object)value;
- }
-
- private static readonly string[] chars = MakeSingleCharStrings();
-
- private static string[] MakeSingleCharStrings() {
- string[] result = new string[255];
-
- for (char ch = (char)0; ch < result.Length; ch++) {
- result[ch] = new string(ch, 1);
- }
-
- return result;
- }
-
- public static object BooleanToObject(bool value) {
- return value ? True : False;
- }
-
- public static string CharToString(char ch) {
- if (ch < 255) return chars[ch];
- return new string(ch, 1);
- }
-
- internal static object GetPrimitiveDefaultValue(Type type) {
- switch (type.GetTypeCode()) {
- case TypeCode.Boolean: return ScriptingRuntimeHelpers.False;
- case TypeCode.SByte: return default(SByte);
- case TypeCode.Byte: return default(Byte);
- case TypeCode.Char: return default(Char);
- case TypeCode.Int16: return default(Int16);
- case TypeCode.Int32: return ScriptingRuntimeHelpers.Int32ToObject(0);
- case TypeCode.Int64: return default(Int64);
- case TypeCode.UInt16: return default(UInt16);
- case TypeCode.UInt32: return default(UInt32);
- case TypeCode.UInt64: return default(UInt64);
- case TypeCode.Single: return default(Single);
- case TypeCode.Double: return default(Double);
-#if FEATURE_DBNULL
- case TypeCode.DBNull: return default(DBNull);
-#endif
- case TypeCode.DateTime: return default(DateTime);
- case TypeCode.Decimal: return default(Decimal);
- default: return null;
- }
- }
-
- public static ArgumentTypeException SimpleTypeError(string message) {
- return new ArgumentTypeException(message);
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // TODO: fix
- public static Exception CannotConvertError(Type toType, object value) {
- return SimpleTypeError(String.Format("Cannot convert {0}({1}) to {2}", CompilerHelpers.GetType(value).Name, value, toType.Name));
- }
-
- public static Exception SimpleAttributeError(string message) {
- //TODO: localize
- return new MissingMemberException(message);
- }
-
- public static object ReadOnlyAssignError(bool field, string fieldName) {
- if (field) {
- throw Error.FieldReadonly(fieldName);
- } else {
- throw Error.PropertyReadonly(fieldName);
- }
- }
-
- /// <summary>
- /// Helper method to create an instance. Work around for Silverlight where Activator.CreateInstance
- /// is SecuritySafeCritical.
- ///
- /// TODO: Why can't we just emit the right thing for default(T)?
- /// It's always null for reference types and it's well defined for value types
- /// </summary>
- public static T CreateInstance<T>() {
- return default(T);
- }
-
- // TODO: can't we just emit a new array?
- public static T[] CreateArray<T>(int args) {
- return new T[args];
- }
-
- /// <summary>
- /// EventInfo.EventHandlerType getter is marked SecuritySafeCritical in CoreCLR
- /// This method is to get to the property without using Reflection
- /// </summary>
- /// <param name="eventInfo"></param>
- /// <returns></returns>
- public static Type GetEventHandlerType(EventInfo eventInfo) {
- ContractUtils.RequiresNotNull(eventInfo, "eventInfo");
- return eventInfo.EventHandlerType;
- }
-
- public static IList<string> GetStringMembers(IList<object> members) {
- List<string> res = new List<string>();
- foreach (object o in members) {
- string str = o as string;
- if (str != null) {
- res.Add(str);
- }
- }
- return res;
- }
-#if !MONO_INTERPRETER
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // TODO: fix
- public static void SetEvent(EventTracker eventTracker, object value) {
- EventTracker et = value as EventTracker;
- if (et != null) {
- if (et != eventTracker) {
- throw Error.UnexpectedEvent(eventTracker.DeclaringType.Name,
- eventTracker.Name,
- et.DeclaringType.Name,
- et.Name);
- }
- return;
- }
-
- BoundMemberTracker bmt = value as BoundMemberTracker;
- if (bmt == null) {
- throw Error.ExpectedBoundEvent(CompilerHelpers.GetType(value).Name);
- }
- if (bmt.BoundTo.MemberType != TrackerTypes.Event) throw Error.ExpectedBoundEvent(bmt.BoundTo.MemberType.ToString());
-
- if (bmt.BoundTo != eventTracker) throw Error.UnexpectedEvent(
- eventTracker.DeclaringType.Name,
- eventTracker.Name,
- bmt.BoundTo.DeclaringType.Name,
- bmt.BoundTo.Name);
- }
-#endif
- // TODO: just emit this in the generated code
- public static bool CheckDictionaryMembers(IDictionary dict, string[] names) {
- if (dict.Count != names.Length) return false;
-
- foreach (string name in names) {
- if (!dict.Contains(name)) {
- return false;
- }
- }
- return true;
- }
-
- // TODO: just emit this in the generated code
- [Obsolete("use MakeIncorrectBoxTypeError instead")]
- public static T IncorrectBoxType<T>(object received) {
- throw Error.UnexpectedType("StrongBox<" + typeof(T).Name + ">", CompilerHelpers.GetType(received).Name);
- }
-
- public static Exception MakeIncorrectBoxTypeError(Type type, object received) {
- return Error.UnexpectedType("StrongBox<" + type.Name + ">", CompilerHelpers.GetType(received).Name);
- }
-
- /// <summary>
- /// Provides the test to see if an interpreted call site should switch over to being compiled.
- /// </summary>
- public static bool InterpretedCallSiteTest(bool restrictionResult, object bindingInfo) {
- if (restrictionResult) {
- CachedBindingInfo bindInfo = (CachedBindingInfo)bindingInfo;
- if (bindInfo.CompilationThreshold >= 0) {
- // still interpreting...
- bindInfo.CompilationThreshold--;
- return true;
- }
-#if SILVERLIGHT
- if (PlatformAdaptationLayer.IsCompactFramework) {
- bindInfo.CompilationThreshold = Int32.MaxValue;
- return true;
- }
-#endif
- return bindInfo.CheckCompiled();
- }
- return false;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ArrayUtils.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ArrayUtils.cs
deleted file mode 100644
index 4262c15b0de..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ArrayUtils.cs
+++ /dev/null
@@ -1,354 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Text;
-
-namespace Microsoft.Scripting.Utils {
- public static class ArrayUtils {
- internal sealed class FunctorComparer<T> : IComparer<T> {
- private readonly Comparison<T> _comparison;
-
- public FunctorComparer(Comparison<T> comparison) {
- Assert.NotNull(comparison);
- _comparison = comparison;
- }
-
- public int Compare(T x, T y) {
- return _comparison(x, y);
- }
- }
-
- // Emitted:
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
- public static readonly string[] EmptyStrings = new string[0];
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
- public static readonly object[] EmptyObjects = new object[0];
-
- public static IComparer<T> ToComparer<T>(Comparison<T> comparison) {
- return new FunctorComparer<T>(comparison);
- }
-
- public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] input, Func<TInput, TOutput> conv) {
- ContractUtils.RequiresNotNull(input, "input");
- ContractUtils.RequiresNotNull(conv, "conv");
-
- TOutput[] res = new TOutput[input.Length];
- for (int i = 0; i < input.Length; i++) {
- res[i] = conv(input[i]);
- }
-
- return res;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "1#")] // TODO: fix
- public static void PrintTable(StringBuilder output, string[,] table) {
- ContractUtils.RequiresNotNull(output, "output");
- ContractUtils.RequiresNotNull(table, "table");
-
- int max_width = 0;
- for (int i = 0; i < table.GetLength(0); i++) {
- if (table[i, 0].Length > max_width) {
- max_width = table[i, 0].Length;
- }
- }
-
- for (int i = 0; i < table.GetLength(0); i++) {
- output.Append(" ");
- output.Append(table[i, 0]);
-
- for (int j = table[i, 0].Length; j < max_width + 1; j++) {
- output.Append(' ');
- }
-
- output.AppendLine(table[i, 1]);
- }
- }
-
- public static T[] Copy<T>(T[] array) {
- return (array.Length > 0) ? (T[])array.Clone() : array;
- }
-
- /// <summary>
- /// Converts a generic ICollection of T into an array of T.
- ///
- /// If the collection is already an array of T the original collection is returned.
- /// </summary>
- public static T[] ToArray<T>(ICollection<T> list) {
- return (list as T[]) ?? MakeArray(list);
- }
-
- /// <summary>
- /// Converts a generic ICollection of T into an array of R using a given conversion.
- ///
- /// If the collection is already an array of R the original collection is returned.
- /// </summary>
- public static TResult[] ToArray<TElement, TResult>(ICollection<TElement> list, Func<TElement, TResult> convertor) {
- TResult[] res = list as TResult[];
- if (res == null) {
- res = new TResult[list.Count];
- int i = 0;
- foreach (TElement obj in list) {
- res[i++] = convertor(obj);
- }
- }
- return res;
- }
-
- public static T[] MakeArray<T>(ICollection<T> list) {
- if (list.Count == 0) {
- return new T[0];
- }
-
- T[] res = new T[list.Count];
- list.CopyTo(res, 0);
- return res;
- }
-
- public static T[] MakeArray<T>(ICollection<T> elements, int reservedSlotsBefore, int reservedSlotsAfter) {
- if (reservedSlotsAfter < 0) throw new ArgumentOutOfRangeException("reservedSlotsAfter");
- if (reservedSlotsBefore < 0) throw new ArgumentOutOfRangeException("reservedSlotsBefore");
-
- if (elements == null) {
- return new T[reservedSlotsBefore + reservedSlotsAfter];
- }
-
- T[] result = new T[reservedSlotsBefore + elements.Count + reservedSlotsAfter];
- elements.CopyTo(result, reservedSlotsBefore);
- return result;
- }
-
- public static T[] RotateRight<T>(T[] array, int count) {
- ContractUtils.RequiresNotNull(array, "array");
- if ((count < 0) || (count > array.Length)) throw new ArgumentOutOfRangeException("count");
-
- T[] result = new T[array.Length];
- // The head of the array is shifted, and the tail will be rotated to the head of the resulting array
- int sizeOfShiftedArray = array.Length - count;
- Array.Copy(array, 0, result, count, sizeOfShiftedArray);
- Array.Copy(array, sizeOfShiftedArray, result, 0, count);
- return result;
- }
-
- public static T[] ShiftRight<T>(T[] array, int count) {
- ContractUtils.RequiresNotNull(array, "array");
- if (count < 0) throw new ArgumentOutOfRangeException("count");
-
- T[] result = new T[array.Length + count];
- System.Array.Copy(array, 0, result, count, array.Length);
- return result;
- }
-
- public static T[] ShiftLeft<T>(T[] array, int count) {
- ContractUtils.RequiresNotNull(array, "array");
- if (count < 0) throw new ArgumentOutOfRangeException("count");
-
- T[] result = new T[array.Length - count];
- System.Array.Copy(array, count, result, 0, result.Length);
- return result;
- }
-
- public static T[] Insert<T>(T item, IList<T> list) {
- T[] res = new T[list.Count + 1];
- res[0] = item;
- list.CopyTo(res, 1);
- return res;
- }
-
- public static T[] Insert<T>(T item1, T item2, IList<T> list) {
- T[] res = new T[list.Count + 2];
- res[0] = item1;
- res[1] = item2;
- list.CopyTo(res, 2);
- return res;
- }
-
- public static T[] Insert<T>(T item, T[] array) {
- T[] result = ShiftRight(array, 1);
- result[0] = item;
- return result;
- }
-
- public static T[] Insert<T>(T item1, T item2, T[] array) {
- T[] result = ShiftRight(array, 2);
- result[0] = item1;
- result[1] = item2;
- return result;
- }
-
- public static T[] Append<T>(T[] array, T item) {
- System.Array.Resize<T>(ref array, (array == null) ? 1 : array.Length + 1);
- array[array.Length - 1] = item;
- return array;
- }
-
- public static T[] AppendRange<T>(T[] array, IList<T> items) {
- return AppendRange<T>(array, items, 0);
- }
-
- public static T[] AppendRange<T>(T[] array, IList<T> items, int additionalItemCount) {
- if (additionalItemCount < 0) {
- throw new ArgumentOutOfRangeException("additionalItemCount");
- }
-
- int j = (array == null) ? 0 : array.Length;
- System.Array.Resize<T>(ref array, j + items.Count + additionalItemCount);
-
- for (int i = 0; i < items.Count; i++, j++) {
- array[j] = items[i];
- }
-
- return array;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional")] // TODO: fix
- public static T[,] Concatenate<T>(T[,] array1, T[,] array2) {
- int columnsCount = array1.GetLength(1);
- Debug.Assert(array2.GetLength(1) == columnsCount);
-
- int row1Count = array1.GetLength(0);
- int row2Count = array2.GetLength(0);
- int totalRowsCount = row1Count + row2Count;
- T[,] result = new T[totalRowsCount, columnsCount];
-
- for (int i = 0; i < row1Count; i++) {
- for (int j = 0; j < columnsCount; j++) {
- result[i, j] = array1[i, j];
- }
- }
-
- for (int i = 0; i < row2Count; i++) {
- for (int j = 0; j < columnsCount; j++) {
- result[(i + row1Count), j] = array2[i, j];
- }
- }
-
- return result;
- }
-
- public static void SwapLastTwo<T>(T[] array) {
- Debug.Assert(array != null && array.Length >= 2);
-
- T temp = array[array.Length - 1];
- array[array.Length - 1] = array[array.Length - 2];
- array[array.Length - 2] = temp;
- }
-
- public static T[] RemoveFirst<T>(IList<T> list) {
- return ShiftLeft(MakeArray(list), 1);
- }
-
- public static T[] RemoveFirst<T>(T[] array) {
- return ShiftLeft(array, 1);
- }
-
- public static T[] RemoveLast<T>(T[] array) {
- ContractUtils.RequiresNotNull(array, "array");
-
- System.Array.Resize(ref array, array.Length - 1);
- return array;
- }
-
- public static T[] RemoveAt<T>(IList<T> list, int indexToRemove) {
- return RemoveAt(MakeArray(list), indexToRemove);
- }
-
- public static T[] RemoveAt<T>(T[] array, int indexToRemove) {
- ContractUtils.RequiresNotNull(array, "array");
- ContractUtils.Requires(indexToRemove >= 0 && indexToRemove < array.Length, "index");
-
- T[] result = new T[array.Length - 1];
- if (indexToRemove > 0) {
- Array.Copy(array, 0, result, 0, indexToRemove);
- }
- int remaining = array.Length - indexToRemove - 1;
- if (remaining > 0) {
- Array.Copy(array, array.Length - remaining, result, result.Length - remaining, remaining);
- }
- return result;
- }
-
- public static T[] InsertAt<T>(IList<T> list, int index, params T[] items) {
- return InsertAt(MakeArray(list), index, items);
- }
-
- public static T[] InsertAt<T>(T[] array, int index, params T[] items) {
- ContractUtils.RequiresNotNull(array, "array");
- ContractUtils.RequiresNotNull(items, "items");
- ContractUtils.Requires(index >= 0 && index <= array.Length, "index");
-
- if (items.Length == 0) {
- return Copy(array);
- }
-
- T[] result = new T[array.Length + items.Length];
- if (index > 0) {
- Array.Copy(array, 0, result, 0, index);
- }
- Array.Copy(items, 0, result, index, items.Length);
-
- int remaining = array.Length - index;
- if (remaining > 0) {
- Array.Copy(array, array.Length - remaining, result, result.Length - remaining, remaining);
- }
- return result;
- }
-
- public static bool ValueEquals<T>(this T[] array, T[] other) {
- if (other.Length != array.Length) {
- return false;
- }
-
- for (int i = 0; i < array.Length; i++) {
- if (!Object.Equals(array[i], other[i])) {
- return false;
- }
- }
-
- return true;
- }
-
- public static int GetValueHashCode<T>(this T[] array) {
- return GetValueHashCode<T>(array, 0, array.Length);
- }
-
- public static int GetValueHashCode<T>(this T[] array, int start, int count) {
- ContractUtils.RequiresNotNull(array, "array");
- ContractUtils.RequiresArrayRange(array.Length, start, count, "start", "count");
-
- if (count == 0) {
- return 0;
- }
-
- int result = array[start].GetHashCode();
- for (int i = 1; i < count; i++) {
- result = ((result << 5) | (result >> 27)) ^ array[start + i].GetHashCode();
- }
-
- return result;
- }
-
- public static T[] Reverse<T>(this T[] array) {
- T[] res = new T[array.Length];
- for (int i = 0; i < array.Length; i++) {
- res[array.Length - i - 1] = array[i];
- }
- return res;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/Assert.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/Assert.cs
deleted file mode 100644
index adae9ddd77a..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/Assert.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#define DEBUG
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-
-namespace Microsoft.Scripting.Utils {
-
- public static class Assert {
-
- public static Exception Unreachable {
- get {
- Debug.Assert(false, "Unreachable");
- return new InvalidOperationException("Code supposed to be unreachable");
- }
- }
-
- [Conditional("DEBUG")]
- public static void NotNull(object var) {
- Debug.Assert(var != null);
- }
-
- [Conditional("DEBUG")]
- public static void NotNull(object var1, object var2) {
- Debug.Assert(var1 != null && var2 != null);
- }
-
- [Conditional("DEBUG")]
- public static void NotNull(object var1, object var2, object var3) {
- Debug.Assert(var1 != null && var2 != null && var3 != null);
- }
-
- [Conditional("DEBUG")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")]
- public static void NotNull(object var1, object var2, object var3, object var4) {
- Debug.Assert(var1 != null && var2 != null && var3 != null && var4 != null);
- }
-
- [Conditional("DEBUG")]
- public static void NotEmpty(string str) {
- Debug.Assert(!String.IsNullOrEmpty(str));
- }
-
- [Conditional("DEBUG")]
- public static void NotEmpty<T>(ICollection<T> array) {
- Debug.Assert(array != null && array.Count > 0);
- }
-
- [Conditional("DEBUG")]
- public static void NotNullItems<T>(IEnumerable<T> items) where T : class {
- Debug.Assert(items != null);
- foreach (object item in items) {
- Debug.Assert(item != null);
- }
- }
-
- [Conditional("DEBUG")]
- public static void IsTrue(Func<bool> predicate) {
- ContractUtils.RequiresNotNull(predicate, "predicate");
- Debug.Assert(predicate());
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CacheDict.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CacheDict.cs
deleted file mode 100644
index 57724cc447a..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CacheDict.cs
+++ /dev/null
@@ -1,114 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Diagnostics;
-
-namespace Microsoft.Scripting.Utils {
- /// <summary>
- /// Provides a dictionary-like object used for caches which holds onto a maximum
- /// number of elements specified at construction time.
- ///
- /// This class is not thread safe.
- /// </summary>
- public class CacheDict<TKey, TValue> {
- private readonly Dictionary<TKey, KeyInfo> _dict = new Dictionary<TKey, KeyInfo>();
- private readonly LinkedList<TKey> _list = new LinkedList<TKey>();
- private readonly int _maxSize;
-
- /// <summary>
- /// Creates a dictionary-like object used for caches.
- /// </summary>
- /// <param name="maxSize">The maximum number of elements to store.</param>
- public CacheDict(int maxSize) {
- _maxSize = maxSize;
- }
-
- /// <summary>
- /// Tries to get the value associated with 'key', returning true if it's found and
- /// false if it's not present.
- /// </summary>
- public bool TryGetValue(TKey key, out TValue value) {
- KeyInfo storedValue;
- if (_dict.TryGetValue(key, out storedValue)) {
- LinkedListNode<TKey> node = storedValue.List;
- if (node.Previous != null) {
- // move us to the head of the list...
- _list.Remove(node);
- _list.AddFirst(node);
- }
-
- value = storedValue.Value;
- return true;
- }
-
- value = default(TValue);
- return false;
- }
-
- /// <summary>
- /// Adds a new element to the cache, replacing and moving it to the front if the
- /// element is already present.
- /// </summary>
- public void Add(TKey key, TValue value) {
- KeyInfo keyInfo;
- if (_dict.TryGetValue(key, out keyInfo)) {
- // remove original entry from the linked list
- _list.Remove(keyInfo.List);
- } else if (_list.Count == _maxSize) {
- // we've reached capacity, remove the last used element...
- LinkedListNode<TKey> node = _list.Last;
- _list.RemoveLast();
- bool res = _dict.Remove(node.Value);
- Debug.Assert(res);
- }
-
- // add the new entry to the head of the list and into the dictionary
- LinkedListNode<TKey> listNode = new LinkedListNode<TKey>(key);
- _list.AddFirst(listNode);
- _dict[key] = new CacheDict<TKey, TValue>.KeyInfo(value, listNode);
- }
-
- /// <summary>
- /// Returns the value associated with the given key, or throws KeyNotFoundException
- /// if the key is not present.
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
- public TValue this[TKey key] {
- get {
- TValue res;
- if (TryGetValue(key, out res)) {
- return res;
- }
- throw new KeyNotFoundException();
- }
- set {
- Add(key, value);
- }
- }
-
- private struct KeyInfo {
- internal readonly TValue Value;
- internal readonly LinkedListNode<TKey> List;
-
- internal KeyInfo(TValue value, LinkedListNode<TKey> list) {
- Value = value;
- List = list;
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CollectionExtensions.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CollectionExtensions.cs
deleted file mode 100644
index 7eaf4000160..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CollectionExtensions.cs
+++ /dev/null
@@ -1,156 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-
-namespace Microsoft.Scripting.Utils {
- internal static class CollectionExtensions {
- /// <summary>
- /// Wraps the provided enumerable into a ReadOnlyCollection{T}
- ///
- /// Copies all of the data into a new array, so the data can't be
- /// changed after creation. The exception is if the enumerable is
- /// already a ReadOnlyCollection{T}, in which case we just return it.
- /// </summary>
- internal static ReadOnlyCollection<T> ToReadOnly<T>(this IEnumerable<T> enumerable) {
- if (enumerable == null) {
- return EmptyReadOnlyCollection<T>.Instance;
- }
-
- var roCollection = enumerable as ReadOnlyCollection<T>;
- if (roCollection != null) {
- return roCollection;
- }
-
- var collection = enumerable as ICollection<T>;
- if (collection != null) {
- int count = collection.Count;
- if (count == 0) {
- return EmptyReadOnlyCollection<T>.Instance;
- }
-
- T[] array = new T[count];
- collection.CopyTo(array, 0);
- return new ReadOnlyCollection<T>(array);
- }
-
- // ToArray trims the excess space and speeds up access
- return new ReadOnlyCollection<T>(new List<T>(enumerable).ToArray());
- }
-
- // We could probably improve the hashing here
- internal static int ListHashCode<T>(this IEnumerable<T> list) {
- var cmp = EqualityComparer<T>.Default;
- int h = 6551;
- foreach (T t in list) {
- h ^= (h << 5) ^ cmp.GetHashCode(t);
- }
- return h;
- }
-
- internal static bool ListEquals<T>(this ICollection<T> first, ICollection<T> second) {
- if (first.Count != second.Count) {
- return false;
- }
- var cmp = EqualityComparer<T>.Default;
- var f = first.GetEnumerator();
- var s = second.GetEnumerator();
- while (f.MoveNext()) {
- s.MoveNext();
-
- if (!cmp.Equals(f.Current, s.Current)) {
- return false;
- }
- }
- return true;
- }
-
- // Name needs to be different so it doesn't conflict with Enumerable.Select
- internal static U[] Map<T, U>(this ICollection<T> collection, Func<T, U> select) {
- int count = collection.Count;
- U[] result = new U[count];
- count = 0;
- foreach (T t in collection) {
- result[count++] = select(t);
- }
- return result;
- }
-
- internal static T[] RemoveFirst<T>(this T[] array) {
- T[] result = new T[array.Length - 1];
- Array.Copy(array, 1, result, 0, result.Length);
- return result;
- }
-
- internal static T[] RemoveLast<T>(this T[] array) {
- T[] result = new T[array.Length - 1];
- Array.Copy(array, 0, result, 0, result.Length);
- return result;
- }
-
- internal static T[] AddFirst<T>(this IList<T> list, T item) {
- T[] res = new T[list.Count + 1];
- res[0] = item;
- list.CopyTo(res, 1);
- return res;
- }
-
- internal static T[] AddLast<T>(this IList<T> list, T item) {
- T[] res = new T[list.Count + 1];
- list.CopyTo(res, 0);
- res[list.Count] = item;
- return res;
- }
-
- internal static T[] RemoveAt<T>(this T[] array, int indexToRemove) {
- Debug.Assert(array != null);
- Debug.Assert(indexToRemove >= 0 && indexToRemove < array.Length);
-
- T[] result = new T[array.Length - 1];
- if (indexToRemove > 0) {
- Array.Copy(array, 0, result, 0, indexToRemove);
- }
- int remaining = array.Length - indexToRemove - 1;
- if (remaining > 0) {
- Array.Copy(array, array.Length - remaining, result, result.Length - remaining, remaining);
- }
- return result;
- }
-
- internal static T[] RotateRight<T>(this T[] array, int count) {
- Debug.Assert(count >= 0 && count <= array.Length);
-
- T[] result = new T[array.Length];
- // The head of the array is shifted, and the tail will be rotated to the head of the resulting array
- int sizeOfShiftedArray = array.Length - count;
- Array.Copy(array, 0, result, count, sizeOfShiftedArray);
- Array.Copy(array, sizeOfShiftedArray, result, 0, count);
- return result;
- }
- }
-
-
- internal static class EmptyReadOnlyCollection<T> {
- internal static ReadOnlyCollection<T> Instance = new ReadOnlyCollection<T>(new T[0]);
- }
- // TODO: Should we use this everywhere for empty arrays?
- // my thought is, probably more hassle than its worth
- internal static class EmptyArray<T> {
- internal static T[] Instance = new T[0];
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CollectionUtils.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CollectionUtils.cs
deleted file mode 100644
index dec3b4e5992..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CollectionUtils.cs
+++ /dev/null
@@ -1,322 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-
-namespace Microsoft.Scripting.Utils {
- /// <summary>
- /// Allows wrapping of proxy types (like COM RCWs) to expose their IEnumerable functionality
- /// which is supported after casting to IEnumerable, even though Reflection will not indicate
- /// IEnumerable as a supported interface
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1010:CollectionsShouldImplementGenericInterface")] // TODO
- public class EnumerableWrapper : IEnumerable {
- private IEnumerable _wrappedObject;
- public EnumerableWrapper(IEnumerable o) {
- _wrappedObject = o;
- }
-
- public IEnumerator GetEnumerator() {
- return _wrappedObject.GetEnumerator();
- }
- }
-
- public static class CollectionUtils {
-#if !FEATURE_VARIANCE
- public static IEnumerable<T> Cast<S, T>(this IEnumerable<S> sequence) where S : T {
- foreach (var item in sequence) {
- yield return (T)item;
- }
- }
-#else
- public static IEnumerable<T> Cast<S, T>(this IEnumerable<S> sequence) where S : T {
- return (IEnumerable<T>)sequence;
- }
-#endif
-
- public static IEnumerable<TSuper> ToCovariant<T, TSuper>(IEnumerable<T> enumerable)
- where T : TSuper {
-#if FEATURE_VARIANCE
- return (IEnumerable<TSuper>)enumerable;
-#else
- return new CovariantConvertor<T, TSuper>(enumerable);
-#endif
- }
-
- public static void AddRange<T>(ICollection<T> collection, IEnumerable<T> items) {
- ContractUtils.RequiresNotNull(collection, "collection");
- ContractUtils.RequiresNotNull(items, "items");
-
- List<T> list = collection as List<T>;
- if (list != null) {
- list.AddRange(items);
- } else {
- foreach (T item in items) {
- collection.Add(item);
- }
- }
- }
-
- public static void AddRange<T>(this IList<T> list, IEnumerable<T> items) {
- foreach (var item in items) {
- list.Add(item);
- }
- }
-
- public static IEnumerable<T> ToEnumerable<T>(IEnumerable enumerable) {
- foreach (T item in enumerable) {
- yield return item;
- }
- }
-
- public static IEnumerator<TSuper> ToCovariant<T, TSuper>(IEnumerator<T> enumerator)
- where T : TSuper {
-
- ContractUtils.RequiresNotNull(enumerator, "enumerator");
-
- while (enumerator.MoveNext()) {
- yield return enumerator.Current;
- }
- }
-
- private class CovariantConvertor<T, TSuper> : IEnumerable<TSuper> where T : TSuper {
- private IEnumerable<T> _enumerable;
-
- public CovariantConvertor(IEnumerable<T> enumerable) {
- ContractUtils.RequiresNotNull(enumerable, "enumerable");
- _enumerable = enumerable;
- }
-
- public IEnumerator<TSuper> GetEnumerator() {
- return CollectionUtils.ToCovariant<T, TSuper>(_enumerable.GetEnumerator());
- }
-
- IEnumerator IEnumerable.GetEnumerator() {
- return GetEnumerator();
- }
- }
-
- public static IDictionaryEnumerator ToDictionaryEnumerator(IEnumerator<KeyValuePair<object, object>> enumerator) {
- return new DictionaryEnumerator(enumerator);
- }
-
- private sealed class DictionaryEnumerator : IDictionaryEnumerator {
- private readonly IEnumerator<KeyValuePair<object, object>> _enumerator;
-
- public DictionaryEnumerator(IEnumerator<KeyValuePair<object, object>> enumerator) {
- _enumerator = enumerator;
- }
-
- public DictionaryEntry Entry {
- get { return new DictionaryEntry(_enumerator.Current.Key, _enumerator.Current.Value); }
- }
-
- public object Key {
- get { return _enumerator.Current.Key; }
- }
-
- public object Value {
- get { return _enumerator.Current.Value; }
- }
-
- public object Current {
- get { return Entry; }
- }
-
- public bool MoveNext() {
- return _enumerator.MoveNext();
- }
-
- public void Reset() {
- _enumerator.Reset();
- }
- }
-
- public static List<T> MakeList<T>(T item) {
- List<T> result = new List<T>();
- result.Add(item);
- return result;
- }
-
- public static int CountOf<T>(IList<T> list, T item) where T : IEquatable<T> {
- if (list == null) return 0;
-
- int result = 0;
- for (int i = 0; i < list.Count; i++) {
- if (list[i].Equals(item)) {
- result++;
- }
- }
- return result;
- }
-
- public static int Max(this IEnumerable<int> values) {
- ContractUtils.RequiresNotNull(values, "values");
-
- int result = Int32.MinValue;
- foreach (var value in values) {
- if (value > result) {
- result = value;
- }
- }
- return result;
- }
-
- public static bool TrueForAll<T>(IEnumerable<T> collection, Predicate<T> predicate) {
- ContractUtils.RequiresNotNull(collection, "collection");
- ContractUtils.RequiresNotNull(predicate, "predicate");
-
- foreach (T item in collection) {
- if (!predicate(item)) return false;
- }
-
- return true;
- }
-
- public static IList<TRet> ConvertAll<T, TRet>(IList<T> collection, Func<T, TRet> predicate) {
- ContractUtils.RequiresNotNull(collection, "collection");
- ContractUtils.RequiresNotNull(predicate, "predicate");
-
- List<TRet> res = new List<TRet>(collection.Count);
- foreach (T item in collection) {
- res.Add(predicate(item));
- }
-
- return res;
- }
-
- public static List<T> GetRange<T>(IList<T> list, int index, int count) {
- ContractUtils.RequiresNotNull(list, "list");
- ContractUtils.RequiresArrayRange(list, index, count, "index", "count");
-
- List<T> result = new List<T>(count);
- int stop = index + count;
- for (int i = index; i < stop; i++) {
- result.Add(list[i]);
- }
- return result;
- }
-
- public static void InsertRange<T>(IList<T> collection, int index, IEnumerable<T> items) {
- ContractUtils.RequiresNotNull(collection, "collection");
- ContractUtils.RequiresNotNull(items, "items");
- ContractUtils.RequiresArrayInsertIndex(collection, index, "index");
-
- List<T> list = collection as List<T>;
- if (list != null) {
- list.InsertRange(index, items);
- } else {
- int i = index;
- foreach (T obj in items) {
- collection.Insert(i++, obj);
- }
- }
- }
-
- public static void RemoveRange<T>(IList<T> collection, int index, int count) {
- ContractUtils.RequiresNotNull(collection, "collection");
- ContractUtils.RequiresArrayRange(collection, index, count, "index", "count");
-
- List<T> list = collection as List<T>;
- if (list != null) {
- list.RemoveRange(index, count);
- } else {
- for (int i = index + count - 1; i >= index; i--) {
- collection.RemoveAt(i);
- }
- }
- }
-
- public static int FindIndex<T>(this IList<T> collection, Predicate<T> predicate) {
- ContractUtils.RequiresNotNull(collection, "collection");
- ContractUtils.RequiresNotNull(predicate, "predicate");
-
- for (int i = 0; i < collection.Count; i++) {
- if (predicate(collection[i])) {
- return i;
- }
- }
- return -1;
- }
-
- public static IList<T> ToSortedList<T>(this ICollection<T> collection, Comparison<T> comparison) {
- ContractUtils.RequiresNotNull(collection, "collection");
- ContractUtils.RequiresNotNull(comparison, "comparison");
-
- var array = new T[collection.Count];
- collection.CopyTo(array, 0);
- Array.Sort(array, comparison);
- return array;
- }
-
- public static T[] ToReverseArray<T>(this IList<T> list) {
- ContractUtils.RequiresNotNull(list, "list");
- T[] result = new T[list.Count];
- for (int i = 0; i < result.Length; i++) {
- result[i] = list[result.Length - 1 - i];
- }
- return result;
- }
-
-
-#if SILVERLIGHT || WIN8 || WP75
- // HashSet.CreateSetComparer not available on Silverlight
- public static IEqualityComparer<HashSet<T>> CreateSetComparer<T>() {
- return new HashSetEqualityComparer<T>();
- }
-
- class HashSetEqualityComparer<T> : IEqualityComparer<HashSet<T>> {
- private IEqualityComparer<T> _comparer;
-
- public HashSetEqualityComparer() {
- _comparer = EqualityComparer<T>.Default;
- }
-
- public bool Equals(HashSet<T> x, HashSet<T> y) {
- if (x == y) {
- return true;
- } else if (x == null || y == null || x.Count != y.Count) {
- return false;
- }
-
- foreach (T value in x) {
- if (!y.Contains(value)) {
- return false;
- }
- }
-
- return true;
- }
-
- public int GetHashCode(HashSet<T> obj) {
- int res = 6551;
- if (obj != null) {
- foreach (T t in obj) {
- res = res ^ _comparer.GetHashCode(t);
- }
- }
-
- return res;
- }
- }
-#else
- public static IEqualityComparer<HashSet<T>> CreateSetComparer<T>() {
- return HashSet<T>.CreateSetComparer();
- }
-#endif
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ContractUtils.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ContractUtils.cs
deleted file mode 100644
index 53a9ea256fd..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ContractUtils.cs
+++ /dev/null
@@ -1,233 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-
-namespace Microsoft.Scripting.Utils {
- public static class ContractUtils {
- [Conditional("DEBUG")]
- public static void Assert(bool precondition) {
- Debug.Assert(precondition);
- }
-
- public static void Requires(bool precondition) {
- if (!precondition) {
- throw new ArgumentException(Strings.MethodPreconditionViolated);
- }
- }
-
- public static void Requires(bool precondition, string paramName) {
- Utils.Assert.NotEmpty(paramName);
-
- if (!precondition) {
- throw new ArgumentException(Strings.InvalidArgumentValue, paramName);
- }
- }
-
- public static void Requires(bool precondition, string paramName, string message) {
- Utils.Assert.NotEmpty(paramName);
-
- if (!precondition) {
- throw new ArgumentException(message, paramName);
- }
- }
-
- public static void RequiresNotNull(object value, string paramName) {
- Utils.Assert.NotEmpty(paramName);
-
- if (value == null) {
- throw new ArgumentNullException(paramName);
- }
- }
-
- public static void RequiresNotEmpty(string str, string paramName) {
- RequiresNotNull(str, paramName);
- if (str.Length == 0) {
- throw new ArgumentException(Strings.NonEmptyStringRequired, paramName);
- }
- }
-
- public static void RequiresNotEmpty<T>(ICollection<T> collection, string paramName) {
- RequiresNotNull(collection, paramName);
- if (collection.Count == 0) {
- throw new ArgumentException(Strings.NonEmptyCollectionRequired, paramName);
- }
- }
-
- /// <summary>
- /// Requires the specified index to point inside the array.
- /// </summary>
- /// <exception cref="ArgumentNullException">Array is <c>null</c>.</exception>
- /// <exception cref="ArgumentOutOfRangeException">Index is outside the array.</exception>
- public static void RequiresArrayIndex<T>(IList<T> array, int index, string indexName) {
- RequiresArrayIndex(array.Count, index, indexName);
- }
-
- /// <summary>
- /// Requires the specified index to point inside the array.
- /// </summary>
- /// <exception cref="ArgumentOutOfRangeException">Index is outside the array.</exception>
- public static void RequiresArrayIndex(int arraySize, int index, string indexName) {
- Utils.Assert.NotEmpty(indexName);
- Debug.Assert(arraySize >= 0);
-
- if (index < 0 || index >= arraySize) throw new ArgumentOutOfRangeException(indexName);
- }
-
- /// <summary>
- /// Requires the specified index to point inside the array or at the end
- /// </summary>
- /// <exception cref="ArgumentNullException">Array is <c>null</c>.</exception>
- /// <exception cref="ArgumentOutOfRangeException">Index is outside the array.</exception>
- public static void RequiresArrayInsertIndex<T>(IList<T> array, int index, string indexName) {
- RequiresArrayInsertIndex(array.Count, index, indexName);
- }
-
- /// <summary>
- /// Requires the specified index to point inside the array or at the end
- /// </summary>
- /// <exception cref="ArgumentNullException">Array is <c>null</c>.</exception>
- /// <exception cref="ArgumentOutOfRangeException">Index is outside the array.</exception>
- public static void RequiresArrayInsertIndex(int arraySize, int index, string indexName) {
- Utils.Assert.NotEmpty(indexName);
- Debug.Assert(arraySize >= 0);
-
- if (index < 0 || index > arraySize) throw new ArgumentOutOfRangeException(indexName);
- }
-
- /// <summary>
- /// Requires the range [offset, offset + count] to be a subset of [0, array.Count].
- /// </summary>
- /// <exception cref="ArgumentOutOfRangeException">Offset or count are out of range.</exception>
- public static void RequiresArrayRange<T>(IList<T> array, int offset, int count, string offsetName, string countName) {
- Utils.Assert.NotNull(array);
- RequiresArrayRange(array.Count, offset, count, offsetName, countName);
- }
-
- /// <summary>
- /// Requires the range [offset, offset + count] to be a subset of [0, array.Count].
- /// </summary>
- /// <exception cref="ArgumentOutOfRangeException">Offset or count are out of range.</exception>
- public static void RequiresArrayRange(int arraySize, int offset, int count, string offsetName, string countName) {
- Utils.Assert.NotEmpty(offsetName);
- Utils.Assert.NotEmpty(countName);
- Debug.Assert(arraySize >= 0);
-
- if (count < 0) throw new ArgumentOutOfRangeException(countName);
- if (offset < 0 || arraySize - offset < count) throw new ArgumentOutOfRangeException(offsetName);
- }
-
-
- /// <summary>
- /// Requires the range [offset, offset + count] to be a subset of [0, array.Count].
- /// </summary>
- /// <exception cref="ArgumentNullException">Array is <c>null</c>.</exception>
- /// <exception cref="ArgumentOutOfRangeException">Offset or count are out of range.</exception>
- public static void RequiresListRange(IList array, int offset, int count, string offsetName, string countName) {
- Utils.Assert.NotEmpty(offsetName);
- Utils.Assert.NotEmpty(countName);
- Utils.Assert.NotNull(array);
-
- if (count < 0) throw new ArgumentOutOfRangeException(countName);
- if (offset < 0 || array.Count - offset < count) throw new ArgumentOutOfRangeException(offsetName);
- }
-
- /// <summary>
- /// Requires the range [offset, offset + count] to be a subset of [0, array.Count].
- /// </summary>
- /// <exception cref="ArgumentNullException">String is <c>null</c>.</exception>
- /// <exception cref="ArgumentOutOfRangeException">Offset or count are out of range.</exception>
- public static void RequiresArrayRange(string str, int offset, int count, string offsetName, string countName) {
- Utils.Assert.NotEmpty(offsetName);
- Utils.Assert.NotEmpty(countName);
- Utils.Assert.NotNull(str);
-
- if (count < 0) throw new ArgumentOutOfRangeException(countName);
- if (offset < 0 || str.Length - offset < count) throw new ArgumentOutOfRangeException(offsetName);
- }
-
- /// <summary>
- /// Requires the array and all its items to be non-null.
- /// </summary>
- public static void RequiresNotNullItems<T>(IList<T> array, string arrayName) {
- Utils.Assert.NotNull(arrayName);
- RequiresNotNull(array, arrayName);
-
- for (int i = 0; i < array.Count; i++) {
- if (array[i] == null) {
- throw ExceptionUtils.MakeArgumentItemNullException(i, arrayName);
- }
- }
- }
-
- /// <summary>
- /// Requires the enumerable collection and all its items to be non-null.
- /// </summary>
- public static void RequiresNotNullItems<T>(IEnumerable<T> collection, string collectionName) {
- Utils.Assert.NotNull(collectionName);
- RequiresNotNull(collection, collectionName);
-
- int i = 0;
- foreach (var item in collection) {
- if (item == null) {
- throw ExceptionUtils.MakeArgumentItemNullException(i, collectionName);
- }
- i++;
- }
- }
-
- [Conditional("FALSE")]
- public static void Invariant(bool condition) {
- Debug.Assert(condition);
- }
-
- [Conditional("FALSE")]
- public static void Invariant(bool condition, string message) {
- Debug.Assert(condition, message);
- }
-
- [Conditional("FALSE")]
- public static void Ensures(bool condition) {
- // nop
- }
-
- [Conditional("FALSE")]
- public static void Ensures(bool condition, string message) {
- // nop
- }
-
- public static T Result<T>() {
- return default(T);
- }
-
- public static T Parameter<T>(out T value) {
- value = default(T);
- return value;
- }
-
- public static T Old<T>(T value) {
- return value;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/DynamicUtils.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/DynamicUtils.cs
deleted file mode 100644
index 3c8e955c587..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/DynamicUtils.cs
+++ /dev/null
@@ -1,297 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_TASKS
-using System.Threading.Tasks;
-#endif
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using Microsoft.Scripting.Generation;
-using Microsoft.Scripting.Interpreter;
-using Microsoft.Scripting.Runtime;
-
-#if !FEATURE_DYNAMIC_EXPRESSION_VISITOR
-#if FEATURE_CORE_DLR
-namespace System.Linq.Expressions {
-#else
-namespace Microsoft.Scripting.Ast {
-#endif
- public abstract class DynamicExpressionVisitor : ExpressionVisitor {
- }
-}
-#endif
-
-namespace Microsoft.Scripting.Utils {
- using AstUtils = Microsoft.Scripting.Ast.Utils;
-
- public static class DynamicUtils {
- /// <summary>
- /// Returns the list of expressions represented by the <see cref="DynamicMetaObject"/> instances.
- /// </summary>
- /// <param name="objects">An array of <see cref="DynamicMetaObject"/> instances to extract expressions from.</param>
- /// <returns>The array of expressions.</returns>
- public static Expression[] GetExpressions(DynamicMetaObject[] objects) {
- ContractUtils.RequiresNotNull(objects, "objects");
-
- Expression[] res = new Expression[objects.Length];
- for (int i = 0; i < objects.Length; i++) {
- DynamicMetaObject mo = objects[i];
- res[i] = mo != null ? mo.Expression : null;
- }
-
- return res;
- }
-
- /// <summary>
- /// Creates an instance of <see cref="DynamicMetaObject"/> for a runtime value and the expression that represents it during the binding process.
- /// </summary>
- /// <param name="argValue">The runtime value to be represented by the <see cref="DynamicMetaObject"/>.</param>
- /// <param name="parameterExpression">An expression to represent this <see cref="DynamicMetaObject"/> during the binding process.</param>
- /// <returns>The new instance of <see cref="DynamicMetaObject"/>.</returns>
- public static DynamicMetaObject ObjectToMetaObject(object argValue, Expression parameterExpression) {
- IDynamicMetaObjectProvider ido = argValue as IDynamicMetaObjectProvider;
- if (ido != null) {
- return ido.GetMetaObject(parameterExpression);
- } else {
- return new DynamicMetaObject(parameterExpression, BindingRestrictions.Empty, argValue);
- }
- }
-
- /// <summary>
- /// Produces an interpreted binding using the given binder which falls over to a compiled
- /// binding after hitCount tries.
- ///
- /// This method should be called whenever an interpreted binding is required. Sometimes it will
- /// return a compiled binding if a previous binding was produced and it's hit count was exhausted.
- /// In this case the binder will not be called back for a new binding - the previous one will
- /// be used.
- /// </summary>
- /// <typeparam name="T">The delegate type being used for the call site</typeparam>
- /// <param name="binder">The binder used for the call site</param>
- /// <param name="compilationThreshold">The number of calls before the binder should switch to a compiled mode.</param>
- /// <param name="args">The arguments that are passed for the binding (as received in a BindDelegate call)</param>
- /// <returns>A delegate which represents the interpreted binding.</returns>
- public static T/*!*/ LightBind<T>(this DynamicMetaObjectBinder/*!*/ binder, object[]/*!*/ args, int compilationThreshold) where T : class {
- ContractUtils.RequiresNotNull(binder, "binder");
- ContractUtils.RequiresNotNull(args, "args");
-
- return GenericInterpretedBinder<T>.Instance.Bind(binder, compilationThreshold < 0 ? LightCompiler.DefaultCompilationThreshold : compilationThreshold, args);
- }
-
- private class GenericInterpretedBinder<T> where T : class {
- public static GenericInterpretedBinder<T>/*!*/ Instance = new GenericInterpretedBinder<T>();
- private readonly ReadOnlyCollection<ParameterExpression>/*!*/ _parameters;
- private readonly Expression/*!*/ _updateExpression;
-
- private GenericInterpretedBinder() {
- var invokeMethod = typeof(T).GetMethod("Invoke");
- var methodParams = invokeMethod.GetParameters();
-
- ReadOnlyCollectionBuilder<ParameterExpression> prms = new ReadOnlyCollectionBuilder<ParameterExpression>(methodParams.Length);
- ReadOnlyCollectionBuilder<Expression> invokePrms = new ReadOnlyCollectionBuilder<Expression>(methodParams.Length);
- for (int i = 0; i < methodParams.Length; i++) {
- var param = Expression.Parameter(methodParams[i].ParameterType);
- if (i == 0) {
- invokePrms.Add(Expression.Convert(param, typeof(CallSite<T>)));
- } else {
- invokePrms.Add(param);
- }
- prms.Add(param);
- }
-
- _parameters = prms.ToReadOnlyCollection();
-
- _updateExpression = Expression.Block(
- Expression.Label(CallSiteBinder.UpdateLabel),
- Expression.Invoke(
- Expression.Property(
- invokePrms[0],
- typeof(CallSite<T>).GetDeclaredProperty("Update")
- ),
- invokePrms.ToReadOnlyCollection()
- )
- );
- }
-
- public T/*!*/ Bind(DynamicMetaObjectBinder/*!*/ binder, int compilationThreshold, object[] args) {
- if (CachedBindingInfo<T>.LastInterpretedFailure != null && CachedBindingInfo<T>.LastInterpretedFailure.Binder == binder) {
- // we failed the rule because we have a compiled target available, return the compiled target
- Debug.Assert(CachedBindingInfo<T>.LastInterpretedFailure.CompiledTarget != null);
- var res = CachedBindingInfo<T>.LastInterpretedFailure.CompiledTarget;
- CachedBindingInfo<T>.LastInterpretedFailure = null;
- return res;
- }
-
- // we haven't produced a rule yet....
- var bindingInfo = new CachedBindingInfo<T>(binder, compilationThreshold);
-
- var targetMO = DynamicMetaObject.Create(args[0], _parameters[1]); // 1 is skipping CallSite
- DynamicMetaObject[] argsMO = new DynamicMetaObject[args.Length - 1];
- for (int i = 0; i < argsMO.Length; i++) {
- argsMO[i] = DynamicMetaObject.Create(args[i + 1], _parameters[i + 2]);
- }
- var binding = binder.Bind(targetMO, argsMO);
-
- return CreateDelegate(binding, bindingInfo);
- }
-
- private T/*!*/ CreateDelegate(DynamicMetaObject/*!*/ binding, CachedBindingInfo<T>/*!*/ bindingInfo) {
- return Compile(binding, bindingInfo).LightCompile(Int32.MaxValue);
- }
-
- private Expression<T>/*!*/ Compile(DynamicMetaObject/*!*/ obj, CachedBindingInfo<T>/*!*/ bindingInfo) {
- var restrictions = obj.Restrictions.ToExpression();
-
- var body = Expression.Condition(
- new InterpretedRuleHitCheckExpression(restrictions, bindingInfo),
- AstUtils.Convert(obj.Expression, _updateExpression.Type),
- _updateExpression
- );
-
- var res = Expression.Lambda<T>(
- body,
- "CallSite.Target",
- true, // always compile the rules with tail call optimization
- _parameters
- );
-
- bindingInfo.Target = res;
- return res;
- }
-
- /// <summary>
- /// Expression which reduces to the normal test but under the interpreter adds a count down
- /// check which enables compiling when the count down is reached.
- /// </summary>
- class InterpretedRuleHitCheckExpression : Expression, IInstructionProvider {
- private readonly Expression/*!*/ _test;
- private readonly CachedBindingInfo/*!*/ _bindingInfo;
-
- private static readonly MethodInfo InterpretedCallSiteTest = typeof(ScriptingRuntimeHelpers).GetMethod("InterpretedCallSiteTest");
- public InterpretedRuleHitCheckExpression(Expression/*!*/ test, CachedBindingInfo/*!*/ bindingInfo) {
- Assert.NotNull(test, bindingInfo);
-
- _test = test;
- _bindingInfo = bindingInfo;
- }
-
- public override Expression Reduce() {
- return _test;
- }
-
- protected override Expression VisitChildren(ExpressionVisitor visitor) {
- var test = visitor.Visit(_test);
- if (test != _test) {
- return new InterpretedRuleHitCheckExpression(test, _bindingInfo);
- }
- return this;
- }
-
- public override bool CanReduce {
- get { return true; }
- }
-
- public override ExpressionType NodeType {
- get { return ExpressionType.Extension; }
- }
-
- public override Type Type {
- get { return typeof(bool); }
- }
-
- #region IInstructionProvider Members
-
- public void AddInstructions(LightCompiler compiler) {
- compiler.Compile(_test);
- compiler.Instructions.EmitLoad(_bindingInfo);
- compiler.EmitCall(InterpretedCallSiteTest);
- }
-
- #endregion
- }
- }
- }
-
-
- /// <summary>
- /// Base class for storing information about the binding that a specific rule is applicable for.
- ///
- /// We have a derived generic class but this class enables us to refer to it w/o having the
- /// generic type information around.
- ///
- /// This class tracks both the count down to when we should compile. When we compile we
- /// take the Expression[T] that was used before and compile it. While this is happening
- /// we continue to allow the interpreted code to run. When the compilation is complete we
- /// store a thread static which tells us what binding failed and the current rule is no
- /// longer functional. Finally the language binder will call us again and we'll retrieve
- /// and return the compiled overload.
- /// </summary>
- abstract class CachedBindingInfo {
- public readonly DynamicMetaObjectBinder/*!*/ Binder;
- public int CompilationThreshold;
-
- public CachedBindingInfo(DynamicMetaObjectBinder binder, int compilationThreshold) {
- Binder = binder;
- CompilationThreshold = compilationThreshold;
- }
-
- public abstract bool CheckCompiled();
- }
-
- class CachedBindingInfo<T> : CachedBindingInfo where T : class {
- public T CompiledTarget;
- public Expression<T> Target;
-
- [ThreadStatic]
- public static CachedBindingInfo<T> LastInterpretedFailure;
-
- public CachedBindingInfo(DynamicMetaObjectBinder binder, int compilationThreshold)
- : base(binder, compilationThreshold) {
- }
-
- public override bool CheckCompiled() {
- if (Target != null) {
- // start compiling the target if no one else has
- var lambda = Interlocked.Exchange(ref Target, null);
- if (lambda != null) {
-#if FEATURE_TASKS
- new Task(() => { CompiledTarget = lambda.Compile(); }).Start();
-#else
- ThreadPool.QueueUserWorkItem(x => { CompiledTarget = lambda.Compile(); });
-#endif
- }
- }
-
- if (CompiledTarget != null) {
- LastInterpretedFailure = this;
- return false;
- }
-
- return true;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ExceptionFactory.Generated.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ExceptionFactory.Generated.cs
deleted file mode 100644
index 1214351549a..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ExceptionFactory.Generated.cs
+++ /dev/null
@@ -1,1050 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-
-namespace Microsoft.Scripting {
-
- internal static partial class Strings {
- private static string FormatString(string format, params object[] args) {
- return string.Format(System.Globalization.CultureInfo.CurrentCulture, format, args);
- }
- }
-
- #region Generated Microsoft.Scripting Exception Factory
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_expr_factory_scripting from: generate_exception_factory.py
-
- /// <summary>
- /// Strongly-typed and parameterized string factory.
- /// </summary>
-
- internal static partial class Strings {
- /// <summary>
- /// A string like "Cannot access member {1} declared on type {0} because the type contains generic parameters."
- /// </summary>
- internal static string InvalidOperation_ContainsGenericParameters(object p0, object p1) {
- return FormatString("Cannot access member {1} declared on type {0} because the type contains generic parameters.", p0, p1);
- }
-
- /// <summary>
- /// A string like "Type '{0}' is missing or cannot be loaded."
- /// </summary>
- internal static string MissingType(object p0) {
- return FormatString("Type '{0}' is missing or cannot be loaded.", p0);
- }
-
- /// <summary>
- /// A string like "static property "{0}" of "{1}" can only be read through a type, not an instance"
- /// </summary>
- internal static string StaticAccessFromInstanceError(object p0, object p1) {
- return FormatString("static property \"{0}\" of \"{1}\" can only be read through a type, not an instance", p0, p1);
- }
-
- /// <summary>
- /// A string like "static property "{0}" of "{1}" can only be assigned to through a type, not an instance"
- /// </summary>
- internal static string StaticAssignmentFromInstanceError(object p0, object p1) {
- return FormatString("static property \"{0}\" of \"{1}\" can only be assigned to through a type, not an instance", p0, p1);
- }
-
- /// <summary>
- /// A string like "Method precondition violated"
- /// </summary>
- internal static string MethodPreconditionViolated {
- get {
- return "Method precondition violated";
- }
- }
-
- /// <summary>
- /// A string like "Invalid argument value"
- /// </summary>
- internal static string InvalidArgumentValue {
- get {
- return "Invalid argument value";
- }
- }
-
- /// <summary>
- /// A string like "Non-empty string required"
- /// </summary>
- internal static string NonEmptyStringRequired {
- get {
- return "Non-empty string required";
- }
- }
-
- /// <summary>
- /// A string like "Non-empty collection required"
- /// </summary>
- internal static string NonEmptyCollectionRequired {
- get {
- return "Non-empty collection required";
- }
- }
-
- /// <summary>
- /// A string like "must by an Exception instance"
- /// </summary>
- internal static string MustBeExceptionInstance {
- get {
- return "must by an Exception instance";
- }
- }
-
- /// <summary>
- /// A string like "Type of test must be bool"
- /// </summary>
- internal static string TypeOfTestMustBeBool {
- get {
- return "Type of test must be bool";
- }
- }
-
- /// <summary>
- /// A string like "Type of the expression must be bool"
- /// </summary>
- internal static string TypeOfExpressionMustBeBool {
- get {
- return "Type of the expression must be bool";
- }
- }
-
- /// <summary>
- /// A string like "Empty string is not a valid path."
- /// </summary>
- internal static string EmptyStringIsInvalidPath {
- get {
- return "Empty string is not a valid path.";
- }
- }
-
- /// <summary>
- /// A string like "Invalid delegate type (Invoke method not found)."
- /// </summary>
- internal static string InvalidDelegate {
- get {
- return "Invalid delegate type (Invoke method not found).";
- }
- }
-
- /// <summary>
- /// A string like "expected only static property"
- /// </summary>
- internal static string ExpectedStaticProperty {
- get {
- return "expected only static property";
- }
- }
-
- /// <summary>
- /// A string like "Property doesn't exist on the provided type"
- /// </summary>
- internal static string PropertyDoesNotExist {
- get {
- return "Property doesn't exist on the provided type";
- }
- }
-
- /// <summary>
- /// A string like "Field doesn't exist on provided type"
- /// </summary>
- internal static string FieldDoesNotExist {
- get {
- return "Field doesn't exist on provided type";
- }
- }
-
- /// <summary>
- /// A string like "Type doesn't have constructor with a given signature"
- /// </summary>
- internal static string TypeDoesNotHaveConstructorForTheSignature {
- get {
- return "Type doesn't have constructor with a given signature";
- }
- }
-
- /// <summary>
- /// A string like "Type doesn't have a method with a given name."
- /// </summary>
- internal static string TypeDoesNotHaveMethodForName {
- get {
- return "Type doesn't have a method with a given name.";
- }
- }
-
- /// <summary>
- /// A string like "Type doesn't have a method with a given name and signature."
- /// </summary>
- internal static string TypeDoesNotHaveMethodForNameSignature {
- get {
- return "Type doesn't have a method with a given name and signature.";
- }
- }
-
- /// <summary>
- /// A string like "Count must be non-negative."
- /// </summary>
- internal static string CountCannotBeNegative {
- get {
- return "Count must be non-negative.";
- }
- }
-
- /// <summary>
- /// A string like "arrayType must be an array type"
- /// </summary>
- internal static string ArrayTypeMustBeArray {
- get {
- return "arrayType must be an array type";
- }
- }
-
- /// <summary>
- /// A string like "Either code or target must be specified."
- /// </summary>
- internal static string MustHaveCodeOrTarget {
- get {
- return "Either code or target must be specified.";
- }
- }
-
- /// <summary>
- /// A string like "Type parameter is {0}. Expected a delegate."
- /// </summary>
- internal static string TypeParameterIsNotDelegate(object p0) {
- return FormatString("Type parameter is {0}. Expected a delegate.", p0);
- }
-
- /// <summary>
- /// A string like "Cannot cast from type '{0}' to type '{1}"
- /// </summary>
- internal static string InvalidCast(object p0, object p1) {
- return FormatString("Cannot cast from type '{0}' to type '{1}", p0, p1);
- }
-
- /// <summary>
- /// A string like "unknown member type: '{0}'. "
- /// </summary>
- internal static string UnknownMemberType(object p0) {
- return FormatString("unknown member type: '{0}'. ", p0);
- }
-
- /// <summary>
- /// A string like "RuleBuilder can only be used with delegates whose first argument is CallSite."
- /// </summary>
- internal static string FirstArgumentMustBeCallSite {
- get {
- return "RuleBuilder can only be used with delegates whose first argument is CallSite.";
- }
- }
-
- /// <summary>
- /// A string like "no instance for call."
- /// </summary>
- internal static string NoInstanceForCall {
- get {
- return "no instance for call.";
- }
- }
-
- /// <summary>
- /// A string like "Missing Test."
- /// </summary>
- internal static string MissingTest {
- get {
- return "Missing Test.";
- }
- }
-
- /// <summary>
- /// A string like "Missing Target."
- /// </summary>
- internal static string MissingTarget {
- get {
- return "Missing Target.";
- }
- }
-
- /// <summary>
- /// A string like "The operation requires a non-generic type for {0}, but this represents generic types only"
- /// </summary>
- internal static string NonGenericWithGenericGroup(object p0) {
- return FormatString("The operation requires a non-generic type for {0}, but this represents generic types only", p0);
- }
-
- /// <summary>
- /// A string like "Invalid operation: '{0}'"
- /// </summary>
- internal static string InvalidOperation(object p0) {
- return FormatString("Invalid operation: '{0}'", p0);
- }
-
- /// <summary>
- /// A string like "Finally already defined."
- /// </summary>
- internal static string FinallyAlreadyDefined {
- get {
- return "Finally already defined.";
- }
- }
-
- /// <summary>
- /// A string like "Can not have fault and finally."
- /// </summary>
- internal static string CannotHaveFaultAndFinally {
- get {
- return "Can not have fault and finally.";
- }
- }
-
- /// <summary>
- /// A string like "Fault already defined."
- /// </summary>
- internal static string FaultAlreadyDefined {
- get {
- return "Fault already defined.";
- }
- }
-
- /// <summary>
- /// A string like "Cannot create default value for type {0}."
- /// </summary>
- internal static string CantCreateDefaultTypeFor(object p0) {
- return FormatString("Cannot create default value for type {0}.", p0);
- }
-
- /// <summary>
- /// A string like "Unhandled convert: {0}"
- /// </summary>
- internal static string UnhandledConvert(object p0) {
- return FormatString("Unhandled convert: {0}", p0);
- }
-
- /// <summary>
- /// A string like "{0}.{1} has no publiclly visible method."
- /// </summary>
- internal static string NoCallableMethods(object p0, object p1) {
- return FormatString("{0}.{1} has no publiclly visible method.", p0, p1);
- }
-
- /// <summary>
- /// A string like "Global/top-level local variable names must be unique."
- /// </summary>
- internal static string GlobalsMustBeUnique {
- get {
- return "Global/top-level local variable names must be unique.";
- }
- }
-
- /// <summary>
- /// A string like "Generating code from non-serializable CallSiteBinder."
- /// </summary>
- internal static string GenNonSerializableBinder {
- get {
- return "Generating code from non-serializable CallSiteBinder.";
- }
- }
-
- /// <summary>
- /// A string like "pecified path is invalid."
- /// </summary>
- internal static string InvalidPath {
- get {
- return "pecified path is invalid.";
- }
- }
-
- /// <summary>
- /// A string like "Dictionaries are not hashable."
- /// </summary>
- internal static string DictionaryNotHashable {
- get {
- return "Dictionaries are not hashable.";
- }
- }
-
- /// <summary>
- /// A string like "language already registered."
- /// </summary>
- internal static string LanguageRegistered {
- get {
- return "language already registered.";
- }
- }
-
- /// <summary>
- /// A string like "The method or operation is not implemented."
- /// </summary>
- internal static string MethodOrOperatorNotImplemented {
- get {
- return "The method or operation is not implemented.";
- }
- }
-
- /// <summary>
- /// A string like "No exception."
- /// </summary>
- internal static string NoException {
- get {
- return "No exception.";
- }
- }
-
- /// <summary>
- /// A string like "Extension type {0} must be public."
- /// </summary>
- internal static string ExtensionMustBePublic(object p0) {
- return FormatString("Extension type {0} must be public.", p0);
- }
-
- /// <summary>
- /// A string like "Already initialized."
- /// </summary>
- internal static string AlreadyInitialized {
- get {
- return "Already initialized.";
- }
- }
-
- /// <summary>
- /// A string like "CreateScopeExtension must return a scope extension."
- /// </summary>
- internal static string MustReturnScopeExtension {
- get {
- return "CreateScopeExtension must return a scope extension.";
- }
- }
-
- /// <summary>
- /// A string like "Invalid number of parameters for the service."
- /// </summary>
- internal static string InvalidParamNumForService {
- get {
- return "Invalid number of parameters for the service.";
- }
- }
-
- /// <summary>
- /// A string like "Invalid type of argument {0}; expecting {1}."
- /// </summary>
- internal static string InvalidArgumentType(object p0, object p1) {
- return FormatString("Invalid type of argument {0}; expecting {1}.", p0, p1);
- }
-
- /// <summary>
- /// A string like "Cannot change non-caching value."
- /// </summary>
- internal static string CannotChangeNonCachingValue {
- get {
- return "Cannot change non-caching value.";
- }
- }
-
- /// <summary>
- /// A string like "Field {0} is read-only"
- /// </summary>
- internal static string FieldReadonly(object p0) {
- return FormatString("Field {0} is read-only", p0);
- }
-
- /// <summary>
- /// A string like "Property {0} is read-only"
- /// </summary>
- internal static string PropertyReadonly(object p0) {
- return FormatString("Property {0} is read-only", p0);
- }
-
- /// <summary>
- /// A string like "Expected event from {0}.{1}, got event from {2}.{3}."
- /// </summary>
- internal static string UnexpectedEvent(object p0, object p1, object p2, object p3) {
- return FormatString("Expected event from {0}.{1}, got event from {2}.{3}.", p0, p1, p2, p3);
- }
-
- /// <summary>
- /// A string like "expected bound event, got {0}."
- /// </summary>
- internal static string ExpectedBoundEvent(object p0) {
- return FormatString("expected bound event, got {0}.", p0);
- }
-
- /// <summary>
- /// A string like "Expected type {0}, got {1}."
- /// </summary>
- internal static string UnexpectedType(object p0, object p1) {
- return FormatString("Expected type {0}, got {1}.", p0, p1);
- }
-
- /// <summary>
- /// A string like "can only write to member {0}."
- /// </summary>
- internal static string MemberWriteOnly(object p0) {
- return FormatString("can only write to member {0}.", p0);
- }
-
- /// <summary>
- /// A string like "No code to compile."
- /// </summary>
- internal static string NoCodeToCompile {
- get {
- return "No code to compile.";
- }
- }
-
- /// <summary>
- /// A string like "Invalid stream type: {0}."
- /// </summary>
- internal static string InvalidStreamType(object p0) {
- return FormatString("Invalid stream type: {0}.", p0);
- }
-
- /// <summary>
- /// A string like "Queue empty."
- /// </summary>
- internal static string QueueEmpty {
- get {
- return "Queue empty.";
- }
- }
-
- /// <summary>
- /// A string like "Enumeration has not started. Call MoveNext."
- /// </summary>
- internal static string EnumerationNotStarted {
- get {
- return "Enumeration has not started. Call MoveNext.";
- }
- }
-
- /// <summary>
- /// A string like "Enumeration already finished."
- /// </summary>
- internal static string EnumerationFinished {
- get {
- return "Enumeration already finished.";
- }
- }
-
- /// <summary>
- /// A string like "can't add another casing for identifier {0}"
- /// </summary>
- internal static string CantAddCasing(object p0) {
- return FormatString("can't add another casing for identifier {0}", p0);
- }
-
- /// <summary>
- /// A string like "can't add new identifier {0}"
- /// </summary>
- internal static string CantAddIdentifier(object p0) {
- return FormatString("can't add new identifier {0}", p0);
- }
-
- /// <summary>
- /// A string like "Type '{0}' doesn't provide a suitable public constructor or its implementation is faulty: {1}"
- /// </summary>
- internal static string InvalidCtorImplementation(object p0, object p1) {
- return FormatString("Type '{0}' doesn't provide a suitable public constructor or its implementation is faulty: {1}", p0, p1);
- }
-
- /// <summary>
- /// A string like "Invalid output directory."
- /// </summary>
- internal static string InvalidOutputDir {
- get {
- return "Invalid output directory.";
- }
- }
-
- /// <summary>
- /// A string like "Invalid assembly name or file extension."
- /// </summary>
- internal static string InvalidAsmNameOrExtension {
- get {
- return "Invalid assembly name or file extension.";
- }
- }
-
- /// <summary>
- /// A string like "Cannot emit constant {0} ({1})"
- /// </summary>
- internal static string CanotEmitConstant(object p0, object p1) {
- return FormatString("Cannot emit constant {0} ({1})", p0, p1);
- }
-
- /// <summary>
- /// A string like "No implicit cast from {0} to {1}"
- /// </summary>
- internal static string NoImplicitCast(object p0, object p1) {
- return FormatString("No implicit cast from {0} to {1}", p0, p1);
- }
-
- /// <summary>
- /// A string like "No explicit cast from {0} to {1}"
- /// </summary>
- internal static string NoExplicitCast(object p0, object p1) {
- return FormatString("No explicit cast from {0} to {1}", p0, p1);
- }
-
- /// <summary>
- /// A string like "name '{0}' not defined"
- /// </summary>
- internal static string NameNotDefined(object p0) {
- return FormatString("name '{0}' not defined", p0);
- }
-
- /// <summary>
- /// A string like "No default value for a given type."
- /// </summary>
- internal static string NoDefaultValue {
- get {
- return "No default value for a given type.";
- }
- }
-
- /// <summary>
- /// A string like "Specified language provider type is not registered."
- /// </summary>
- internal static string UnknownLanguageProviderType {
- get {
- return "Specified language provider type is not registered.";
- }
- }
-
- /// <summary>
- /// A string like "can't read from property"
- /// </summary>
- internal static string CantReadProperty {
- get {
- return "can't read from property";
- }
- }
-
- /// <summary>
- /// A string like "can't write to property"
- /// </summary>
- internal static string CantWriteProperty {
- get {
- return "can't write to property";
- }
- }
-
- /// <summary>
- /// A string like "Cannot create instance of {0} because it contains generic parameters"
- /// </summary>
- internal static string IllegalNew_GenericParams(object p0) {
- return FormatString("Cannot create instance of {0} because it contains generic parameters", p0);
- }
-
- /// <summary>
- /// A string like "Non-verifiable assembly generated: {0}:\nAssembly preserved as {1}\nError text:\n{2}\n"
- /// </summary>
- internal static string VerificationException(object p0, object p1, object p2) {
- return FormatString("Non-verifiable assembly generated: {0}:\nAssembly preserved as {1}\nError text:\n{2}\n", p0, p1, p2);
- }
-
- }
- /// <summary>
- /// Strongly-typed and parameterized exception factory.
- /// </summary>
-
- internal static partial class Error {
- /// <summary>
- /// ArgumentException with message like "Either code or target must be specified."
- /// </summary>
- internal static Exception MustHaveCodeOrTarget() {
- return new ArgumentException(Strings.MustHaveCodeOrTarget);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Type parameter is {0}. Expected a delegate."
- /// </summary>
- internal static Exception TypeParameterIsNotDelegate(object p0) {
- return new InvalidOperationException(Strings.TypeParameterIsNotDelegate(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Cannot cast from type '{0}' to type '{1}"
- /// </summary>
- internal static Exception InvalidCast(object p0, object p1) {
- return new InvalidOperationException(Strings.InvalidCast(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "unknown member type: '{0}'. "
- /// </summary>
- internal static Exception UnknownMemberType(object p0) {
- return new InvalidOperationException(Strings.UnknownMemberType(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "RuleBuilder can only be used with delegates whose first argument is CallSite."
- /// </summary>
- internal static Exception FirstArgumentMustBeCallSite() {
- return new InvalidOperationException(Strings.FirstArgumentMustBeCallSite);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "no instance for call."
- /// </summary>
- internal static Exception NoInstanceForCall() {
- return new InvalidOperationException(Strings.NoInstanceForCall);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Missing Test."
- /// </summary>
- internal static Exception MissingTest() {
- return new InvalidOperationException(Strings.MissingTest);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Missing Target."
- /// </summary>
- internal static Exception MissingTarget() {
- return new InvalidOperationException(Strings.MissingTarget);
- }
-
- /// <summary>
- /// TypeLoadException with message like "The operation requires a non-generic type for {0}, but this represents generic types only"
- /// </summary>
- internal static Exception NonGenericWithGenericGroup(object p0) {
- return new TypeLoadException(Strings.NonGenericWithGenericGroup(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Invalid operation: '{0}'"
- /// </summary>
- internal static Exception InvalidOperation(object p0) {
- return new ArgumentException(Strings.InvalidOperation(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Finally already defined."
- /// </summary>
- internal static Exception FinallyAlreadyDefined() {
- return new InvalidOperationException(Strings.FinallyAlreadyDefined);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Can not have fault and finally."
- /// </summary>
- internal static Exception CannotHaveFaultAndFinally() {
- return new InvalidOperationException(Strings.CannotHaveFaultAndFinally);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Fault already defined."
- /// </summary>
- internal static Exception FaultAlreadyDefined() {
- return new InvalidOperationException(Strings.FaultAlreadyDefined);
- }
-
- /// <summary>
- /// ArgumentException with message like "Cannot create default value for type {0}."
- /// </summary>
- internal static Exception CantCreateDefaultTypeFor(object p0) {
- return new ArgumentException(Strings.CantCreateDefaultTypeFor(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Unhandled convert: {0}"
- /// </summary>
- internal static Exception UnhandledConvert(object p0) {
- return new ArgumentException(Strings.UnhandledConvert(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "{0}.{1} has no publiclly visible method."
- /// </summary>
- internal static Exception NoCallableMethods(object p0, object p1) {
- return new InvalidOperationException(Strings.NoCallableMethods(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Global/top-level local variable names must be unique."
- /// </summary>
- internal static Exception GlobalsMustBeUnique() {
- return new ArgumentException(Strings.GlobalsMustBeUnique);
- }
-
- /// <summary>
- /// ArgumentException with message like "Generating code from non-serializable CallSiteBinder."
- /// </summary>
- internal static Exception GenNonSerializableBinder() {
- return new ArgumentException(Strings.GenNonSerializableBinder);
- }
-
- /// <summary>
- /// ArgumentException with message like "pecified path is invalid."
- /// </summary>
- internal static Exception InvalidPath() {
- return new ArgumentException(Strings.InvalidPath);
- }
-
- /// <summary>
- /// ArgumentTypeException with message like "Dictionaries are not hashable."
- /// </summary>
- internal static Exception DictionaryNotHashable() {
- return new ArgumentTypeException(Strings.DictionaryNotHashable);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "language already registered."
- /// </summary>
- internal static Exception LanguageRegistered() {
- return new InvalidOperationException(Strings.LanguageRegistered);
- }
-
- /// <summary>
- /// NotImplementedException with message like "The method or operation is not implemented."
- /// </summary>
- internal static Exception MethodOrOperatorNotImplemented() {
- return new NotImplementedException(Strings.MethodOrOperatorNotImplemented);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "No exception."
- /// </summary>
- internal static Exception NoException() {
- return new InvalidOperationException(Strings.NoException);
- }
-
- /// <summary>
- /// ArgumentException with message like "Extension type {0} must be public."
- /// </summary>
- internal static Exception ExtensionMustBePublic(object p0) {
- return new ArgumentException(Strings.ExtensionMustBePublic(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Already initialized."
- /// </summary>
- internal static Exception AlreadyInitialized() {
- return new InvalidOperationException(Strings.AlreadyInitialized);
- }
-
- /// <summary>
- /// InvalidImplementationException with message like "CreateScopeExtension must return a scope extension."
- /// </summary>
- internal static Exception MustReturnScopeExtension() {
- return new InvalidImplementationException(Strings.MustReturnScopeExtension);
- }
-
- /// <summary>
- /// ArgumentException with message like "Invalid number of parameters for the service."
- /// </summary>
- internal static Exception InvalidParamNumForService() {
- return new ArgumentException(Strings.InvalidParamNumForService);
- }
-
- /// <summary>
- /// ArgumentException with message like "Invalid type of argument {0}; expecting {1}."
- /// </summary>
- internal static Exception InvalidArgumentType(object p0, object p1) {
- return new ArgumentException(Strings.InvalidArgumentType(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Cannot change non-caching value."
- /// </summary>
- internal static Exception CannotChangeNonCachingValue() {
- return new ArgumentException(Strings.CannotChangeNonCachingValue);
- }
-
- /// <summary>
- /// MissingMemberException with message like "Field {0} is read-only"
- /// </summary>
- internal static Exception FieldReadonly(object p0) {
- return new MissingMemberException(Strings.FieldReadonly(p0));
- }
-
- /// <summary>
- /// MissingMemberException with message like "Property {0} is read-only"
- /// </summary>
- internal static Exception PropertyReadonly(object p0) {
- return new MissingMemberException(Strings.PropertyReadonly(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Expected event from {0}.{1}, got event from {2}.{3}."
- /// </summary>
- internal static Exception UnexpectedEvent(object p0, object p1, object p2, object p3) {
- return new ArgumentException(Strings.UnexpectedEvent(p0, p1, p2, p3));
- }
-
- /// <summary>
- /// ArgumentTypeException with message like "expected bound event, got {0}."
- /// </summary>
- internal static Exception ExpectedBoundEvent(object p0) {
- return new ArgumentTypeException(Strings.ExpectedBoundEvent(p0));
- }
-
- /// <summary>
- /// ArgumentTypeException with message like "Expected type {0}, got {1}."
- /// </summary>
- internal static Exception UnexpectedType(object p0, object p1) {
- return new ArgumentTypeException(Strings.UnexpectedType(p0, p1));
- }
-
- /// <summary>
- /// MemberAccessException with message like "can only write to member {0}."
- /// </summary>
- internal static Exception MemberWriteOnly(object p0) {
- return new MemberAccessException(Strings.MemberWriteOnly(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "No code to compile."
- /// </summary>
- internal static Exception NoCodeToCompile() {
- return new InvalidOperationException(Strings.NoCodeToCompile);
- }
-
- /// <summary>
- /// ArgumentException with message like "Invalid stream type: {0}."
- /// </summary>
- internal static Exception InvalidStreamType(object p0) {
- return new ArgumentException(Strings.InvalidStreamType(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Queue empty."
- /// </summary>
- internal static Exception QueueEmpty() {
- return new InvalidOperationException(Strings.QueueEmpty);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Enumeration has not started. Call MoveNext."
- /// </summary>
- internal static Exception EnumerationNotStarted() {
- return new InvalidOperationException(Strings.EnumerationNotStarted);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Enumeration already finished."
- /// </summary>
- internal static Exception EnumerationFinished() {
- return new InvalidOperationException(Strings.EnumerationFinished);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "can't add another casing for identifier {0}"
- /// </summary>
- internal static Exception CantAddCasing(object p0) {
- return new InvalidOperationException(Strings.CantAddCasing(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "can't add new identifier {0}"
- /// </summary>
- internal static Exception CantAddIdentifier(object p0) {
- return new InvalidOperationException(Strings.CantAddIdentifier(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Invalid output directory."
- /// </summary>
- internal static Exception InvalidOutputDir() {
- return new ArgumentException(Strings.InvalidOutputDir);
- }
-
- /// <summary>
- /// ArgumentException with message like "Invalid assembly name or file extension."
- /// </summary>
- internal static Exception InvalidAsmNameOrExtension() {
- return new ArgumentException(Strings.InvalidAsmNameOrExtension);
- }
-
- /// <summary>
- /// ArgumentException with message like "Cannot emit constant {0} ({1})"
- /// </summary>
- internal static Exception CanotEmitConstant(object p0, object p1) {
- return new ArgumentException(Strings.CanotEmitConstant(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "No implicit cast from {0} to {1}"
- /// </summary>
- internal static Exception NoImplicitCast(object p0, object p1) {
- return new ArgumentException(Strings.NoImplicitCast(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "No explicit cast from {0} to {1}"
- /// </summary>
- internal static Exception NoExplicitCast(object p0, object p1) {
- return new ArgumentException(Strings.NoExplicitCast(p0, p1));
- }
-
- /// <summary>
- /// MissingMemberException with message like "name '{0}' not defined"
- /// </summary>
- internal static Exception NameNotDefined(object p0) {
- return new MissingMemberException(Strings.NameNotDefined(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "No default value for a given type."
- /// </summary>
- internal static Exception NoDefaultValue() {
- return new ArgumentException(Strings.NoDefaultValue);
- }
-
- /// <summary>
- /// ArgumentException with message like "Specified language provider type is not registered."
- /// </summary>
- internal static Exception UnknownLanguageProviderType() {
- return new ArgumentException(Strings.UnknownLanguageProviderType);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "can't read from property"
- /// </summary>
- internal static Exception CantReadProperty() {
- return new InvalidOperationException(Strings.CantReadProperty);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "can't write to property"
- /// </summary>
- internal static Exception CantWriteProperty() {
- return new InvalidOperationException(Strings.CantWriteProperty);
- }
-
- /// <summary>
- /// ArgumentException with message like "Cannot create instance of {0} because it contains generic parameters"
- /// </summary>
- internal static Exception IllegalNew_GenericParams(object p0) {
- return new ArgumentException(Strings.IllegalNew_GenericParams(p0));
- }
-
- /// <summary>
- /// System.Security.VerificationException with message like "Non-verifiable assembly generated: {0}:\nAssembly preserved as {1}\nError text:\n{2}\n"
- /// </summary>
- internal static Exception VerificationException(object p0, object p1, object p2) {
- return new System.Security.VerificationException(Strings.VerificationException(p0, p1, p2));
- }
-
- }
-
- // *** END GENERATED CODE ***
-
- #endregion
-
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ExceptionUtils.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ExceptionUtils.cs
deleted file mode 100644
index 89449659612..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ExceptionUtils.cs
+++ /dev/null
@@ -1,111 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using System.Collections.Generic;
-using System.Threading;
-
-namespace Microsoft.Scripting.Utils {
- public static class ExceptionUtils {
- public static ArgumentOutOfRangeException MakeArgumentOutOfRangeException(string paramName, object actualValue, string message) {
-#if SILVERLIGHT || WP75 // ArgumentOutOfRangeException ctor overload
- throw new ArgumentOutOfRangeException(paramName, string.Format("{0} (actual value is '{1}')", message, actualValue));
-#else
- throw new ArgumentOutOfRangeException(paramName, actualValue, message);
-#endif
- }
-
- public static ArgumentNullException MakeArgumentItemNullException(int index, string arrayName) {
- return new ArgumentNullException(String.Format("{0}[{1}]", arrayName, index));
- }
-
-#if FEATURE_REMOTING
- public static object GetData(this Exception e, object key) {
- return e.Data[key];
- }
-
- public static void SetData(this Exception e, object key, object data) {
- e.Data[key] = data;
- }
-
- public static void RemoveData(this Exception e, object key) {
- e.Data.Remove(key);
- }
-#else
-
-#if WP75
- private static WeakDictionary<Exception, List<KeyValuePair<object, object>>> _exceptionData;
-#else
- private static ConditionalWeakTable<Exception, List<KeyValuePair<object, object>>> _exceptionData;
-#endif
-
- public static void SetData(this Exception e, object key, object value) {
- if (_exceptionData == null) {
-#if WP75
- Interlocked.CompareExchange(ref _exceptionData, new WeakDictionary<Exception, List<KeyValuePair<object, object>>>(), null);
-#else
- Interlocked.CompareExchange(ref _exceptionData, new ConditionalWeakTable<Exception, List<KeyValuePair<object, object>>>(), null);
-#endif
- }
-
- lock (_exceptionData) {
- var data = _exceptionData.GetOrCreateValue(e);
-
- int index = data.FindIndex(entry => entry.Key == key);
- if (index >= 0) {
- data[index] = new KeyValuePair<object, object>(key, value);
- } else {
- data.Add(new KeyValuePair<object, object>(key, value));
- }
- }
- }
-
- public static object GetData(this Exception e, object key) {
- if (_exceptionData == null) {
- return null;
- }
-
- lock (_exceptionData) {
- List<KeyValuePair<object, object>> data;
- if (!_exceptionData.TryGetValue(e, out data)) {
- return null;
- }
-
- return data.FirstOrDefault(entry => entry.Key == key).Value;
- }
- }
-
- public static void RemoveData(this Exception e, object key) {
- if (_exceptionData == null) {
- return;
- }
-
- lock (_exceptionData) {
- List<KeyValuePair<object, object>> data;
- if (!_exceptionData.TryGetValue(e, out data)) {
- return;
- }
-
- int index = data.FindIndex(entry => entry.Key == key);
- if (index >= 0) {
- data.RemoveAt(index);
- }
- }
- }
-#endif
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/HybridReferenceDictionary.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/HybridReferenceDictionary.cs
deleted file mode 100644
index 13b62d45f07..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/HybridReferenceDictionary.cs
+++ /dev/null
@@ -1,170 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Diagnostics;
-
-namespace Microsoft.Scripting.Utils {
- /// <summary>
- /// A hybrid dictionary which compares based upon object identity.
- /// </summary>
- class HybridReferenceDictionary<TKey, TValue> where TKey : class {
- private KeyValuePair<TKey, TValue>[] _keysAndValues;
- private Dictionary<TKey, TValue> _dict;
- private int _count;
- private const int _arraySize = 10;
-
- public HybridReferenceDictionary() {
- }
-
- public HybridReferenceDictionary(int initialCapicity) {
- if (initialCapicity > _arraySize) {
- _dict = new Dictionary<TKey, TValue>(initialCapicity);
- } else {
- _keysAndValues = new KeyValuePair<TKey, TValue>[initialCapicity];
- }
- }
-
- public bool TryGetValue(TKey key, out TValue value) {
- Debug.Assert(key != null);
-
- if (_dict != null) {
- return _dict.TryGetValue(key, out value);
- } else if (_keysAndValues != null) {
- for (int i = 0; i < _keysAndValues.Length; i++) {
- if (_keysAndValues[i].Key == key) {
- value = _keysAndValues[i].Value;
- return true;
- }
- }
- }
- value = default(TValue);
- return false;
- }
-
- public bool Remove(TKey key) {
- Debug.Assert(key != null);
-
- if (_dict != null) {
- return _dict.Remove(key);
- } else if (_keysAndValues != null) {
- for (int i = 0; i < _keysAndValues.Length; i++) {
- if (_keysAndValues[i].Key == key) {
- _keysAndValues[i] = new KeyValuePair<TKey, TValue>();
- _count--;
- return true;
- }
- }
- }
-
- return false;
- }
-
- public bool ContainsKey(TKey key) {
- Debug.Assert(key != null);
-
- if (_dict != null) {
- return _dict.ContainsKey(key);
- } else if (_keysAndValues != null) {
- for (int i = 0; i < _keysAndValues.Length; i++) {
- if (_keysAndValues[i].Key == key) {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public int Count {
- get {
- if (_dict != null) {
- return _dict.Count;
- }
- return _count;
- }
-
- }
-
- public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
- if (_dict != null) {
- return _dict.GetEnumerator();
- }
-
- return GetEnumeratorWorker();
- }
-
- private IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorWorker() {
- if (_keysAndValues != null) {
- for (int i = 0; i < _keysAndValues.Length; i++) {
- if (_keysAndValues[i].Key != null) {
- yield return _keysAndValues[i];
- }
- }
- }
- }
-
- public TValue this[TKey key] {
- get {
- Debug.Assert(key != null);
-
- TValue res;
- if (TryGetValue(key, out res)) {
- return res;
- }
-
- throw new KeyNotFoundException();
- }
- set {
- Debug.Assert(key != null);
-
- if (_dict != null) {
- _dict[key] = value;
- } else {
- int index;
- if (_keysAndValues != null) {
- index = -1;
- for (int i = 0; i < _keysAndValues.Length; i++) {
- if (_keysAndValues[i].Key == key) {
- _keysAndValues[i] = new KeyValuePair<TKey, TValue>(key, value);
- return;
- } else if (_keysAndValues[i].Key == null) {
- index = i;
- }
- }
- } else {
- _keysAndValues = new KeyValuePair<TKey, TValue>[_arraySize];
- index = 0;
- }
-
- if (index != -1) {
- _count++;
- _keysAndValues[index] = new KeyValuePair<TKey, TValue>(key, value);
- } else {
- _dict = new Dictionary<TKey, TValue>();
- for (int i = 0; i < _keysAndValues.Length; i++) {
- _dict[_keysAndValues[i].Key] = _keysAndValues[i].Value;
- }
- _keysAndValues = null;
-
- _dict[key] = value;
- }
- }
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ListEqualityComparer.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ListEqualityComparer.cs
deleted file mode 100644
index 3d04b8f27f3..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ListEqualityComparer.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Collections.Generic;
-
-namespace Microsoft.Scripting.Utils {
- // Compares two ICollection<T>'s using element equality
- internal sealed class ListEqualityComparer<T> : EqualityComparer<ICollection<T>> {
- internal static readonly ListEqualityComparer<T> Instance = new ListEqualityComparer<T>();
-
- private ListEqualityComparer() { }
-
- // EqualityComparer<T> handles null and object identity for us
- public override bool Equals(ICollection<T> x, ICollection<T> y) {
- return x.ListEquals(y);
- }
-
- public override int GetHashCode(ICollection<T> obj) {
- return obj.ListHashCode();
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/MathUtils.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/MathUtils.cs
deleted file mode 100644
index 435fb259b6b..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/MathUtils.cs
+++ /dev/null
@@ -1,1230 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_NUMERICS
-using BigInt = System.Numerics.BigInteger;
-using Complex = System.Numerics.Complex;
-#endif
-
-using System;
-using System.Text;
-using System.Collections.Generic;
-using Microsoft.Scripting.Math;
-using Microsoft.Scripting.Runtime;
-
-namespace Microsoft.Scripting.Utils {
- using Math = System.Math;
-
- public static class MathUtils {
- /// <summary>
- /// Calculates the quotient of two 32-bit signed integers rounded towards negative infinity.
- /// </summary>
- /// <param name="x">Dividend.</param>
- /// <param name="y">Divisor.</param>
- /// <returns>The quotient of the specified numbers rounded towards negative infinity, or <code>(int)Floor((double)x/(double)y)</code>.</returns>
- /// <exception cref="DivideByZeroException"><paramref name="y"/> is 0.</exception>
- /// <remarks>The caller must check for overflow (x = Int32.MinValue, y = -1)</remarks>
- public static int FloorDivideUnchecked(int x, int y) {
- int q = x / y;
-
- if (x >= 0) {
- if (y > 0) {
- return q;
- } else if (x % y == 0) {
- return q;
- } else {
- return q - 1;
- }
- } else {
- if (y > 0) {
- if (x % y == 0) {
- return q;
- } else {
- return q - 1;
- }
- } else {
- return q;
- }
- }
- }
-
- /// <summary>
- /// Calculates the quotient of two 32-bit signed integers rounded towards negative infinity.
- /// </summary>
- /// <param name="x">Dividend.</param>
- /// <param name="y">Divisor.</param>
- /// <returns>The quotient of the specified numbers rounded towards negative infinity, or <code>(int)Floor((double)x/(double)y)</code>.</returns>
- /// <exception cref="DivideByZeroException"><paramref name="y"/> is 0.</exception>
- /// <remarks>The caller must check for overflow (x = Int64.MinValue, y = -1)</remarks>
- public static long FloorDivideUnchecked(long x, long y) {
- long q = x / y;
-
- if (x >= 0) {
- if (y > 0) {
- return q;
- } else if (x % y == 0) {
- return q;
- } else {
- return q - 1;
- }
- } else {
- if (y > 0) {
- if (x % y == 0) {
- return q;
- } else {
- return q - 1;
- }
- } else {
- return q;
- }
- }
- }
-
- /// <summary>
- /// Calculates the remainder of floor division of two 32-bit signed integers.
- /// </summary>
- /// <param name="x">Dividend.</param>
- /// <param name="y">Divisor.</param>
- /// <returns>The remainder of of floor division of the specified numbers, or <code>x - (int)Floor((double)x/(double)y) * y</code>.</returns>
- /// <exception cref="DivideByZeroException"><paramref name="y"/> is 0.</exception>
- public static int FloorRemainder(int x, int y) {
- if (y == -1) return 0;
- int r = x % y;
-
- if (x >= 0) {
- if (y > 0) {
- return r;
- } else if (r == 0) {
- return 0;
- } else {
- return r + y;
- }
- } else {
- if (y > 0) {
- if (r == 0) {
- return 0;
- } else {
- return r + y;
- }
- } else {
- return r;
- }
- }
- }
-
- /// <summary>
- /// Calculates the remainder of floor division of two 32-bit signed integers.
- /// </summary>
- /// <param name="x">Dividend.</param>
- /// <param name="y">Divisor.</param>
- /// <returns>The remainder of of floor division of the specified numbers, or <code>x - (int)Floor((double)x/(double)y) * y</code>.</returns>
- /// <exception cref="DivideByZeroException"><paramref name="y"/> is 0.</exception>
- public static long FloorRemainder(long x, long y) {
- if (y == -1) return 0;
- long r = x % y;
-
- if (x >= 0) {
- if (y > 0) {
- return r;
- } else if (r == 0) {
- return 0;
- } else {
- return r + y;
- }
- } else {
- if (y > 0) {
- if (r == 0) {
- return 0;
- } else {
- return r + y;
- }
- } else {
- return r;
- }
- }
- }
-
- /// <summary>
- /// Behaves like Math.Round(value, MidpointRounding.AwayFromZero)
- /// Needed because CoreCLR doesn't support this particular overload of Math.Round
- /// </summary>
- public static double RoundAwayFromZero(double value) {
-#if !SILVERLIGHT && !WP75
- return Math.Round(value, MidpointRounding.AwayFromZero);
-#else
- if (value < 0) {
- return -RoundAwayFromZero(-value);
- }
-
- // we can assume positive value
- double result = Math.Floor(value);
- if (value - result >= 0.5) {
- result += 1.0;
- }
- return result;
-#endif
- }
-
- private static readonly double[] _RoundPowersOfTens = new double[] { 1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8, 1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15 };
-
- private static double GetPowerOf10(int precision) {
- return (precision < 16) ? _RoundPowersOfTens[precision] : Math.Pow(10, precision);
- }
-
- /// <summary>
- /// Behaves like Math.Round(value, precision, MidpointRounding.AwayFromZero)
- /// However, it works correctly on negative precisions and cases where precision is
- /// outside of the [-15, 15] range.
- ///
- /// (This function is also needed because CoreCLR lacks this overload.)
- /// </summary>
- public static double RoundAwayFromZero(double value, int precision) {
- if (double.IsInfinity(value) || double.IsNaN(value)) {
- return value;
- }
-
- if (precision >= 0) {
- if (precision > 308) {
- return value;
- }
-
- double num = GetPowerOf10(precision);
- return RoundAwayFromZero(value * num) / num;
- } else if (precision >= -308) {
- // Note: this code path could be merged with the precision >= 0 path,
- // (by extending the cache to negative powers of 10)
- // but the results seem to be more precise if we do it this way
- double num = GetPowerOf10(-precision);
- return RoundAwayFromZero(value / num) * num;
- } else {
- // Preserve the sign of the input, including +/-0.0
- return value < 0.0 || 1.0 / value < 0.0 ? -0.0 : 0.0;
- }
- }
-
- public static bool IsNegativeZero(double self) {
-#if SILVERLIGHT // BitConverter.DoubleToInt64Bits
- if ( self != 0.0 ) {
- return false;
- }
- byte[] bits = BitConverter.GetBytes(self);
- return (bits[7] == 0x80 && bits[6] == 0x00 && bits[5] == 0x00 && bits[4] == 0x00
- && bits[3] == 0x00 && bits[2] == 0x00 && bits[1] == 0x00 && bits[0] == 0x00);
-#else
- return (self == 0.0 && 1.0 / self < 0);
-#endif
- }
-
- #region Special Functions
-
- public static double Erf(double v0) {
- // Calculate the error function using the approximation method outlined in
- // W. J. Cody's "Rational Chebyshev Approximations for the Error Function"
-
- if (v0 >= 10.0) {
- return 1.0;
- } else if (v0 <= -10.0) {
- return -1.0;
- }
-
- if (v0 > 0.47 || v0 < -0.47) {
- return 1.0 - ErfComplement(v0);
- }
-
- double sq = v0 * v0;
- double numer = EvalPolynomial(sq, ErfNumerCoeffs);
- double denom = EvalPolynomial(sq, ErfDenomCoeffs);
-
- return v0 * numer / denom;
- }
-
- public static double ErfComplement(double v0) {
- if (v0 >= 30.0) {
- return 0.0;
- } else if (v0 <= -10.0) {
- return 2.0;
- }
-
- double a = Math.Abs(v0);
- if (a < 0.47) {
- return 1.0 - Erf(v0);
- }
-
- // Different approximations are required for different ranges of v0
- double res;
- if (a <= 4.0) {
- // Use the approximation method outlined in W. J. Cody's "Rational Chebyshev
- // Approximations for the Error Function"
- double numer = EvalPolynomial(a, ErfcNumerCoeffs);
- double denom = EvalPolynomial(a, ErfcDenomCoeffs);
-
- res = Math.Exp(-a * a) * numer / denom;
- } else {
- // Use the approximation method introduced by C. Tellambura and A. Annamalai
- // in "Efficient Computation of erfc(x) for Large Arguments"
- const double h = 0.5;
- const double hSquared = 0.25;
- const int nTerms = 10;
- double sq = a * a;
- res = 0.0;
- for (int i = nTerms; i > 0; i--) {
- double term = i * i * hSquared;
- res += Math.Exp(-term) / (term + sq);
- }
-
- res = h * a * Math.Exp(-sq) / Math.PI * (res * 2 + 1.0 / sq);
- }
-
- if (v0 < 0.0) {
- res = 2.0 - res;
- }
- return res;
- }
-
- public static double Gamma(double v0) {
- // Calculate the Gamma function using the Lanczos approximation
-
- if (double.IsNegativeInfinity(v0)) {
- return double.NaN;
- }
- double a = Math.Abs(v0);
-
- // Special-case integers
- if (a % 1.0 == 0.0) {
- // Gamma is undefined on non-positive integers
- if (v0 <= 0.0) {
- return double.NaN;
- }
-
- // factorial(v0 - 1)
- if (a <= 25.0) {
- if (a <= 2.0) {
- return 1.0;
- }
- a -= 1.0;
- v0 -= 1.0;
- while (--v0 > 1.0) {
- a *= v0;
- }
- return a;
- }
- }
-
- // lim(Gamma(v0)) = 1.0 / v0 as v0 approaches 0.0
- if (a < 1e-50) {
- return 1.0 / v0;
- }
-
- double res;
- if (v0 < -150.0) {
- // If Gamma(1 - v0) could overflow for large v0, use the duplication formula to
- // compute Gamma(1 - v0):
- // Gamma(x) * Gamma(x + 0,5) = sqrt(pi) * 2**(1 - 2x) * Gamma(2x)
- // ==> Gamma(1 - x) = Gamma((1-x)/2) * Gamma((2-x)/2) / (2**x * sqrt(pi))
- // Then apply the reflection formula:
- // Gamma(x) = pi / sin(pi * x) / Gamma(1 - x)
- double halfV0 = v0 / 2.0;
- res = Math.Pow(Math.PI, 1.5) / SinPi(v0);
- res *= Math.Pow(2.0, v0);
- res /= PositiveGamma(0.5 - halfV0);
- res /= PositiveGamma(1.0 - halfV0);
- } else if (v0 < 0.001) {
- // For values less than or close to zero, just use the reflection formula
- res = Math.PI / SinPi(v0);
- double v1 = 1.0 - v0;
- if (v0 == 1.0 - v1) {
- res /= PositiveGamma(v1);
- } else {
- // Computing v1 has resulted in a loss of precision. To avoid this, use the
- // recurrence relation Gamma(x + 1) = x * Gamma(x).
- res /= -v0 * PositiveGamma(-v0);
- }
- } else {
- res = PositiveGamma(v0);
- }
-
- return res;
- }
-
- public static double LogGamma(double v0) {
- // Calculate the log of the Gamma function using the Lanczos approximation
-
- if (double.IsInfinity(v0)) {
- return double.PositiveInfinity;
- }
- double a = Math.Abs(v0);
-
- // Gamma is undefined on non-positive integers
- if (v0 <= 0.0 && a % 1.0 == 0.0) {
- return double.NaN;
- }
-
- // lim(LGamma(v0)) = -log|v0| as v0 approaches 0.0
- if (a < 1e-50) {
- return -Math.Log(a);
- }
-
- double res;
- if (v0 < 0.0) {
- // For negative values, use the reflection formula:
- // Gamma(x) = pi / sin(pi * x) / Gamma(1 - x)
- // ==> LGamma(x) = log(pi / |sin(pi * x)|) - LGamma(1 - x)
- res = Math.Log(Math.PI / AbsSinPi(v0));
- res -= PositiveLGamma(1.0 - v0);
- } else {
- res = PositiveLGamma(v0);
- }
-
- return res;
- }
-
- public static double Hypot(double x, double y) {
- //
- // sqrt(x*x + y*y) == sqrt(x*x * (1 + (y*y)/(x*x))) ==
- // sqrt(x*x) * sqrt(1 + (y/x)*(y/x)) ==
- // abs(x) * sqrt(1 + (y/x)*(y/x))
- //
-
- // Handle infinities
- if (double.IsInfinity(x) || double.IsInfinity(y)) {
- return double.PositiveInfinity;
- }
-
- // First, get abs
- if (x < 0.0) x = -x;
- if (y < 0.0) y = -y;
-
- // Obvious cases
- if (x == 0.0) return y;
- if (y == 0.0) return x;
-
- // Divide smaller number by bigger number to safeguard the (y/x)*(y/x)
- if (x < y) {
- double temp = y; y = x; x = temp;
- }
-
- y /= x;
-
- // calculate abs(x) * sqrt(1 + (y/x)*(y/x))
- return x * System.Math.Sqrt(1 + y * y);
- }
-
- /// <summary>
- /// Evaluates a polynomial in v0 where the coefficients are ordered in increasing degree
- /// </summary>
- private static double EvalPolynomial(double v0, double[] coeffs) {
- double res = 0.0;
- for (int i = coeffs.Length - 1; i >= 0; i--) {
- res = checked(res * v0 + coeffs[i]);
- }
-
- return res;
- }
-
- /// <summary>
- /// Evaluates a polynomial in v0 where the coefficients are ordered in increasing degree
- /// if reverse is false, and increasing degree if reverse is true.
- /// </summary>
- private static double EvalPolynomial(double v0, double[] coeffs, bool reverse) {
- if (!reverse) {
- return EvalPolynomial(v0, coeffs);
- }
-
- double res = 0.0;
- for (int i = 0; i < coeffs.Length; i++) {
- res = checked(res * v0 + coeffs[i]);
- }
-
- return res;
- }
-
- /// <summary>
- /// A numerically precise version of sin(v0 * pi)
- /// </summary>
- private static double SinPi(double v0) {
- double res = Math.Abs(v0) % 2.0;
-
- if (res < 0.25) {
- res = Math.Sin(res * Math.PI);
- } else if (res < 0.75) {
- res = Math.Cos((res - 0.5) * Math.PI);
- } else if (res < 1.25) {
- res = -Math.Sin((res - 1.0) * Math.PI);
- } else if (res < 1.75) {
- res = -Math.Cos((res - 1.5) * Math.PI);
- } else {
- res = Math.Sin((res - 2.0) * Math.PI);
- }
-
- return v0 < 0 ? -res : res;
- }
-
- /// <summary>
- /// A numerically precise version of |sin(v0 * pi)|
- /// </summary>
- private static double AbsSinPi(double v0) {
- double res = Math.Abs(v0) % 1.0;
-
- if (res < 0.25) {
- res = Math.Sin(res * Math.PI);
- } else if (res < 0.75) {
- res = Math.Cos((res - 0.5) * Math.PI);
- } else {
- res = Math.Sin((res - 1.0) * Math.PI);
- }
-
- return Math.Abs(res);
- }
-
- // polynomial coefficients ordered by increasing degree
- private static double[] ErfNumerCoeffs = {
- 2.4266795523053175e02, 2.1979261618294152e01,
- 6.9963834886191355, -3.5609843701815385e-02
- };
- private static double[] ErfDenomCoeffs = {
- 2.1505887586986120e02, 9.1164905404514901e01,
- 1.5082797630407787e01, 1.0
- };
- private static double[] ErfcNumerCoeffs = {
- 3.004592610201616005e02, 4.519189537118729422e02,
- 3.393208167343436870e02, 1.529892850469404039e02,
- 4.316222722205673530e01, 7.211758250883093659,
- 5.641955174789739711e-01, -1.368648573827167067e-07
- };
- private static double[] ErfcDenomCoeffs = {
- 3.004592609569832933e02, 7.909509253278980272e02,
- 9.313540948506096211e02, 6.389802644656311665e02,
- 2.775854447439876434e02, 7.700015293522947295e01,
- 1.278272731962942351e01, 1.0
- };
- private static double[] GammaNumerCoeffs = {
- 4.401213842800460895436e13, 4.159045335859320051581e13,
- 1.801384278711799677796e13, 4.728736263475388896889e12,
- 8.379100836284046470415e11, 1.055837072734299344907e11,
- 9.701363618494999493386e09, 6.549143975482052641016e08,
- 3.223832294213356530668e07, 1.128514219497091438040e06,
- 2.666579378459858944762e04, 3.818801248632926870394e02,
- 2.506628274631000502415
- };
- private static double[] GammaDenomCoeffs = {
- 0.0, 39916800.0, 120543840.0, 150917976.0,
- 105258076.0, 45995730.0, 13339535.0, 2637558.0,
- 357423.0, 32670.0, 1925.0, 66.0, 1.0
- };
-
- /// <summary>
- /// Take the quotient of the 2 polynomials forming the Lanczos approximation
- /// with N=13 and G=13.144565
- /// </summary>
- private static double GammaRationalFunc(double v0) {
- double numer = 0.0;
- double denom = 0.0;
-
- if (v0 < 1e15) {
- numer = EvalPolynomial(v0, GammaNumerCoeffs);
- denom = EvalPolynomial(v0, GammaDenomCoeffs);
- } else {
- double vRecip = 1.0 / v0;
- numer = EvalPolynomial(vRecip, GammaNumerCoeffs, true);
- denom = EvalPolynomial(vRecip, GammaDenomCoeffs, true);
- }
-
- return numer / denom;
- }
-
- /// <summary>
- /// Computes the Gamma function on positive values, using the Lanczos approximation.
- /// Lanczos parameters are N=13 and G=13.144565.
- /// </summary>
- private static double PositiveGamma(double v0) {
- if (v0 > 200.0) {
- return Double.PositiveInfinity;
- }
-
- double vg = v0 + 12.644565; // v0 + g - 0.5
- double res = GammaRationalFunc(v0);
- res /= Math.Exp(vg);
- if (v0 < 120.0) {
- res *= Math.Pow(vg, v0 - 0.5);
- } else {
- // Use a smaller exponent if we're in danger of overflowing Math.Pow
- double sqrt = Math.Pow(vg, v0 / 2.0 - 0.25);
- res *= sqrt;
- res *= sqrt;
- }
-
- return res;
- }
-
- /// <summary>
- /// Computes the Log-Gamma function on positive values, using the Lanczos approximation.
- /// Lanczos parameters are N=13 and G=13.144565.
- /// </summary>
- private static double PositiveLGamma(double v0) {
- double vg = v0 + 12.644565; // v0 + g - 0.5
- double res = Math.Log(GammaRationalFunc(v0)) - vg;
- res += (v0 - 0.5) * Math.Log(vg);
-
- return res;
- }
-
- #endregion
-
- #region BigInteger
-
- // generated by scripts/radix_generator.py
- private static readonly uint[] maxCharsPerDigit = { 0, 0, 31, 20, 15, 13, 12, 11, 10, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 };
- private static readonly uint[] groupRadixValues = { 0, 0, 2147483648, 3486784401, 1073741824, 1220703125, 2176782336, 1977326743, 1073741824, 3486784401, 1000000000, 2357947691, 429981696, 815730721, 1475789056, 2562890625, 268435456, 410338673, 612220032, 893871739, 1280000000, 1801088541, 2494357888, 3404825447, 191102976, 244140625, 308915776, 387420489, 481890304, 594823321, 729000000, 887503681, 1073741824, 1291467969, 1544804416, 1838265625, 2176782336 };
-
- internal static string BigIntegerToString(uint[] d, int sign, int radix, bool lowerCase) {
- if (radix < 2) {
- throw ExceptionUtils.MakeArgumentOutOfRangeException("radix", radix, "radix must be >= 2");
- }
- if (radix > 36) {
- throw ExceptionUtils.MakeArgumentOutOfRangeException("radix", radix, "radix must be <= 36");
- }
-
- int dl = d.Length;
- if (dl == 0) {
- return "0";
- }
-
- List<uint> digitGroups = new List<uint>();
-
- uint groupRadix = groupRadixValues[radix];
- while (dl > 0) {
- uint rem = div(d, ref dl, groupRadix);
- digitGroups.Add(rem);
- }
-
- StringBuilder ret = new StringBuilder();
- if (sign == -1) {
- ret.Append("-");
- }
-
- int digitIndex = digitGroups.Count - 1;
-
- char[] tmpDigits = new char[maxCharsPerDigit[radix]];
-
- AppendRadix((uint)digitGroups[digitIndex--], (uint)radix, tmpDigits, ret, false, lowerCase);
- while (digitIndex >= 0) {
- AppendRadix((uint)digitGroups[digitIndex--], (uint)radix, tmpDigits, ret, true, lowerCase);
- }
- return ret.Length == 0 ? "0" : ret.ToString();
- }
-
- private const int BitsPerDigit = 32;
-
- private static uint div(uint[] n, ref int nl, uint d) {
- ulong rem = 0;
- int i = nl;
- bool seenNonZero = false;
- while (--i >= 0) {
- rem <<= BitsPerDigit;
- rem |= n[i];
- uint v = (uint)(rem / d);
- n[i] = v;
- if (v == 0) {
- if (!seenNonZero) nl--;
- } else {
- seenNonZero = true;
- }
- rem %= d;
- }
- return (uint)rem;
- }
-
- private static void AppendRadix(uint rem, uint radix, char[] tmp, StringBuilder buf, bool leadingZeros, bool lowerCase) {
- string symbols = lowerCase ? "0123456789abcdefghijklmnopqrstuvwxyz" : "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-
- int digits = tmp.Length;
- int i = digits;
- while (i > 0 && (leadingZeros || rem != 0)) {
- uint digit = rem % radix;
- rem /= radix;
- tmp[--i] = symbols[(int)digit];
- }
- if (leadingZeros) buf.Append(tmp);
- else buf.Append(tmp, i, digits - i);
- }
-
- // Helper for GetRandBits
- private static uint GetWord(byte[] bytes, int start, int end) {
- uint four = 0;
- int bits = end - start;
- int shift = 0;
- if (bits > 32) {
- bits = 32;
- }
- start /= 8;
- while (bits > 0) {
- uint value = bytes[start];
- if (bits < 8) {
- value &= (1u << bits) - 1u;
- }
- value <<= shift;
- four |= value;
- bits -= 8;
- shift += 8;
- start++;
- }
-
- return four;
- }
-#if !MONO_INTERPRETER
-#if !FEATURE_NUMERICS
- public static BigInteger GetRandBits(this Random generator, int bits) {
- ContractUtils.Requires(bits > 0);
-
- // equivalent to (bits + 7) / 8 without possibility of overflow
- int count = bits % 8 == 0 ? bits / 8 : bits / 8 + 1;
-
- // Pad the end (most significant) with zeros if we align to the byte
- // to ensure that we end up with a positive value
- byte[] bytes = new byte[bits % 8 == 0 ? count + 1 : count];
- generator.NextBytes(bytes);
- if (bits % 8 == 0) {
- bytes[bytes.Length - 1] = 0;
- } else {
- bytes[bytes.Length - 1] = (byte)(bytes[bytes.Length - 1] & ((1 << (bits % 8)) - 1));
- }
-
- if (bits <= 32) {
- return (BigInteger)GetWord(bytes, 0, bits);
- } else if (bits <= 64) {
- ulong a = GetWord(bytes, 0, bits);
- ulong b = GetWord(bytes, 32, bits);
- return (BigInteger)(a | (b << 32));
- } else {
- count = (count + 3) / 4;
- uint[] data = new uint[count];
- for (int i = 0; i < count; i++) {
- data[i] = GetWord(bytes, i * 32, bits);
- }
- return new BigInteger(1, data);
- }
- }
-
- public static BigInteger Random(this Random generator, BigInteger limit) {
- ContractUtils.Requires(limit.Sign > 0, "limit");
- ContractUtils.RequiresNotNull(generator, "generator");
-
- // TODO: this doesn't yield a uniform distribution (small numbers will be picked more frequently):
- uint[] result = new uint[limit.GetWordCount() + 1];
- for (int i = 0; i < result.Length; i++) {
- result[i] = unchecked((uint)generator.Next());
- }
- return new BigInteger(1, result) % limit;
- }
-#else
- public static BigInt GetRandBits(this Random generator, int bits) {
- ContractUtils.Requires(bits > 0);
-
- // equivalent to (bits + 7) / 8 without possibility of overflow
- int count = bits % 8 == 0 ? bits / 8 : bits / 8 + 1;
-
- // Pad the end (most significant) with zeros if we align to the byte
- // to ensure that we end up with a positive value
- byte[] bytes = new byte[bits % 8 == 0 ? count + 1 : count];
- generator.NextBytes(bytes);
- if (bits % 8 == 0) {
- bytes[bytes.Length - 1] = 0;
- } else {
- bytes[bytes.Length - 1] = (byte)(bytes[bytes.Length - 1] & ((1 << (bits % 8)) - 1));
- }
-
- if (bits <= 32) {
- return (BigInt)GetWord(bytes, 0, bits);
- } else if (bits <= 64) {
- ulong a = GetWord(bytes, 0, bits);
- ulong b = GetWord(bytes, 32, bits);
- return (BigInt)(a | (b << 32));
- }
-
- return new BigInt(bytes);
- }
-
- public static BigInteger Random(this Random generator, BigInteger limit) {
- return new BigInteger(generator.Random(limit.Value));
- }
-
- public static BigInt Random(this Random generator, BigInt limit) {
- ContractUtils.Requires(limit.Sign > 0, "limit");
- ContractUtils.RequiresNotNull(generator, "generator");
-
- BigInt res = BigInt.Zero;
-
- while (true) {
- // if we've run out of significant digits, we can return the total
- if (limit == BigInt.Zero) {
- return res;
- }
-
- // if we're small enough to fit in an int, do so
- int iLimit;
- if (limit.AsInt32(out iLimit)) {
- return res + generator.Next(iLimit);
- }
-
- // get the 3 or 4 uppermost bytes that fit into an int
- int hiData;
- byte[] data = limit.ToByteArray();
- int index = data.Length;
- while (data[--index] == 0) ;
- if (data[index] < 0x80) {
- hiData = data[index] << 24;
- data[index--] = (byte)0;
- } else {
- hiData = 0;
- }
- hiData |= data[index] << 16;
- data[index--] = (byte)0;
- hiData |= data[index] << 8;
- data[index--] = (byte)0;
- hiData |= data[index];
- data[index--] = (byte)0;
-
- // get a uniform random number for the uppermost portion of the bigint
- byte[] randomData = new byte[index + 2];
- generator.NextBytes(randomData);
- randomData[index + 1] = (byte)0;
- res += new BigInt(randomData);
- res += (BigInt)generator.Next(hiData) << ((index + 1) * 8);
-
- // sum it with a uniform random number for the remainder of the bigint
- limit = new BigInt(data);
- }
- }
-
- public static bool TryToFloat64(this BigInt self, out double result) {
- return StringUtils.TryParseDouble(
- self.ToString(),
- System.Globalization.NumberStyles.Number,
- System.Globalization.CultureInfo.InvariantCulture.NumberFormat,
- out result
- );
- }
-
- public static double ToFloat64(this BigInt self) {
- return double.Parse(
- self.ToString(),
- System.Globalization.NumberStyles.Number,
- System.Globalization.CultureInfo.InvariantCulture.NumberFormat
- );
- }
-#endif
- public static bool TryToFloat64(this BigInteger self, out double result) {
- return StringUtils.TryParseDouble(
- self.ToString(10),
- System.Globalization.NumberStyles.Number,
- System.Globalization.CultureInfo.InvariantCulture.NumberFormat,
- out result
- );
- }
-
- public static double ToFloat64(this BigInteger self) {
- return double.Parse(
- self.ToString(10),
- System.Globalization.NumberStyles.Number,
- System.Globalization.CultureInfo.InvariantCulture.NumberFormat
- );
- }
-
- // Like GetBitCount(Abs(x)), except 0 maps to 0
- public static int BitLength(BigInteger x) {
- if (x.IsZero()) {
- return 0;
- }
-
- return x.Abs().GetBitCount();
- }
-
-#if FEATURE_NUMERICS
- public static int BitLength(BigInt x) {
- if (x.IsZero) {
- return 0;
- }
-
- byte[] bytes = BigInt.Abs(x).ToByteArray();
- int index = bytes.Length;
- while (bytes[--index] == 0) ;
-
- return index * 8 + BitLength((int)bytes[index]);
- }
-#endif
-#endif
- // Like GetBitCount(Abs(x)), except 0 maps to 0
- public static int BitLength(long x) {
- if (x == 0) {
- return 0;
- }
- if (x == Int64.MinValue) {
- return 64;
- }
-
- x = Math.Abs(x);
- int res = 1;
- if (x >= 1L << 32) {
- x >>= 32;
- res += 32;
- }
- if (x >= 1L << 16) {
- x >>= 16;
- res += 16;
- }
- if (x >= 1L << 8) {
- x >>= 8;
- res += 8;
- }
- if (x >= 1L << 4) {
- x >>= 4;
- res += 4;
- }
- if (x >= 1L << 2) {
- x >>= 2;
- res += 2;
- }
- if (x >= 1L << 1) {
- res += 1;
- }
-
- return res;
- }
-
- // Like GetBitCount(Abs(x)), except 0 maps to 0
- [CLSCompliant(false)]
- public static int BitLengthUnsigned(ulong x) {
- if (x >= 1uL << 63) {
- return 64;
- }
- return BitLength((long)x);
- }
-
- // Like GetBitCount(Abs(x)), except 0 maps to 0
- public static int BitLength(int x) {
- if (x == 0) {
- return 0;
- }
- if (x == Int32.MinValue) {
- return 32;
- }
-
- x = Math.Abs(x);
- int res = 1;
- if (x >= 1 << 16) {
- x >>= 16;
- res += 16;
- }
- if (x >= 1 << 8) {
- x >>= 8;
- res += 8;
- }
- if (x >= 1 << 4) {
- x >>= 4;
- res += 4;
- }
- if (x >= 1 << 2) {
- x >>= 2;
- res += 2;
- }
- if (x >= 1 << 1) {
- res += 1;
- }
-
- return res;
- }
-
- // Like GetBitCount(Abs(x)), except 0 maps to 0
- [CLSCompliant(false)]
- public static int BitLengthUnsigned(uint x) {
- if (x >= 1u << 31) {
- return 32;
- }
- return BitLength((int)x);
- }
-
- #region Extending BigInt with BigInteger API
-#if FEATURE_NUMERICS
-
- public static bool AsInt32(this BigInt self, out int ret) {
- if (self >= Int32.MinValue && self <= Int32.MaxValue) {
- ret = (Int32)self;
- return true;
- }
- ret = 0;
- return false;
- }
-
- public static bool AsInt64(this BigInt self, out long ret) {
- if (self >= Int64.MinValue && self <= Int64.MaxValue) {
- ret = (long)self;
- return true;
- }
- ret = 0;
- return false;
- }
-
- [CLSCompliant(false)]
- public static bool AsUInt32(this BigInt self, out uint ret) {
- if (self >= UInt32.MinValue && self <= UInt32.MaxValue) {
- ret = (UInt32)self;
- return true;
- }
- ret = 0;
- return false;
- }
-
- [CLSCompliant(false)]
- public static bool AsUInt64(this BigInt self, out ulong ret) {
- if (self >= UInt64.MinValue && self <= UInt64.MaxValue) {
- ret = (UInt64)self;
- return true;
- }
- ret = 0;
- return false;
- }
-
- public static BigInt Abs(this BigInt self) {
- return BigInt.Abs(self);
- }
-
- public static bool IsZero(this BigInt self) {
- return self.IsZero;
- }
-
- public static bool IsPositive(this BigInt self) {
- return self.Sign > 0;
- }
-
- public static bool IsNegative(this BigInt self) {
- return self.Sign < 0;
- }
-
- public static double Log(this BigInt self) {
- return BigInt.Log(self);
- }
-
- public static double Log(this BigInt self, double baseValue) {
- return BigInt.Log(self, baseValue);
- }
-
- public static double Log10(this BigInt self) {
- return BigInt.Log10(self);
- }
-
- public static BigInt Power(this BigInt self, int exp) {
- return BigInt.Pow(self, exp);
- }
-
- public static BigInt ModPow(this BigInt self, int power, BigInt mod) {
- return BigInt.ModPow(self, power, mod);
- }
-
- public static BigInt ModPow(this BigInt self, BigInt power, BigInt mod) {
- return BigInt.ModPow(self, power, mod);
- }
-
- public static string ToString(this BigInt self, int radix) {
- const string symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-
- if (radix < 2) {
- throw ExceptionUtils.MakeArgumentOutOfRangeException("radix", radix, "radix must be >= 2");
- }
- if (radix > 36) {
- throw ExceptionUtils.MakeArgumentOutOfRangeException("radix", radix, "radix must be <= 36");
- }
-
- bool isNegative = false;
- if (self < BigInt.Zero) {
- self = -self;
- isNegative = true;
- } else if (self == BigInt.Zero) {
- return "0";
- }
-
- List<char> digits = new List<char>();
- while (self > 0) {
- digits.Add(symbols[(int)(self % radix)]);
- self /= radix;
- }
-
- StringBuilder ret = new StringBuilder();
- if (isNegative) {
- ret.Append('-');
- }
- for (int digitIndex = digits.Count - 1; digitIndex >= 0; digitIndex--) {
- ret.Append(digits[digitIndex]);
- }
- return ret.ToString();
- }
-#endif
- #endregion
-
- #region Exposing underlying data
-#if FEATURE_NUMERICS
-
- [CLSCompliant(false)]
- public static uint[] GetWords(this BigInt self) {
- if (self.IsZero) {
- return new uint[] { 0 };
- }
-
- int hi;
- byte[] bytes;
- GetHighestByte(self, out hi, out bytes);
-
- uint[] result = new uint[(hi + 1 + 3) / 4];
- int i = 0;
- int j = 0;
- uint u = 0;
- int shift = 0;
- while (i < bytes.Length) {
- u |= (uint)bytes[i++] << shift;
- if (i % 4 == 0) {
- result[j++] = u;
- u = 0;
- }
- shift += 8;
- }
- if (u != 0) {
- result[j] = u;
- }
- return result;
- }
-
- [CLSCompliant(false)]
- public static uint GetWord(this BigInt self, int index) {
- return GetWords(self)[index];
- }
-
- public static int GetWordCount(this BigInt self) {
- int index;
- byte[] bytes;
- GetHighestByte(self, out index, out bytes);
- return index / 4 + 1; // return (index + 1 + 3) / 4;
- }
-
- public static int GetByteCount(this BigInt self) {
- int index;
- byte[] bytes;
- GetHighestByte(self, out index, out bytes);
- return index + 1;
- }
-
- public static int GetBitCount(this BigInt self) {
- if (self.IsZero) {
- return 1;
- }
- byte[] bytes = BigInt.Abs(self).ToByteArray();
-
- int index = bytes.Length;
- while (bytes[--index] == 0) ;
-
- int count = index * 8;
- for (int hiByte = bytes[index]; hiByte > 0; hiByte >>= 1) {
- count++;
- }
- return count;
- }
-
- private static byte GetHighestByte(BigInt self, out int index, out byte[] byteArray) {
- byte[] bytes = BigInt.Abs(self).ToByteArray();
- if (self.IsZero) {
- byteArray = bytes;
- index = 0;
- return 1;
- }
-
- int hi = bytes.Length;
- byte b;
- do {
- b = bytes[--hi];
- } while (b == 0);
- index = hi;
- byteArray = bytes;
- return b;
- }
-
-#endif
- #endregion
-
- #endregion
-
-#if !MONO_INTERPRETER
- #region Complex
-
-#if !FEATURE_NUMERICS
- public static Complex64 MakeReal(double real) {
- return new Complex64(real, 0.0);
- }
-
- public static Complex64 MakeImaginary(double imag) {
- return new Complex64(0.0, imag);
- }
-
- public static Complex64 MakeComplex(double real, double imag) {
- return new Complex64(real, imag);
- }
-
- public static double Imaginary(this Complex64 self) {
- return self.Imag;
- }
-
- public static bool IsZero(this Complex64 self) {
- return self.IsZero;
- }
-
- public static Complex64 Pow(this Complex64 self, Complex64 power) {
- return self.Power(power);
- }
-#else
- public static Complex MakeReal(double real) {
- return new Complex(real, 0.0);
- }
-
- public static Complex MakeImaginary(double imag) {
- return new Complex(0.0, imag);
- }
-
- public static Complex MakeComplex(double real, double imag) {
- return new Complex(real, imag);
- }
-
- public static double Imaginary(this Complex self) {
- return self.Imaginary;
- }
-
- public static bool IsZero(this Complex self) {
- return self.Equals(Complex.Zero);
- }
-
- public static Complex Conjugate(this Complex self) {
- return new Complex(self.Real, -self.Imaginary);
- }
-
- public static double Abs(this Complex self) {
- return Complex.Abs(self);
- }
-
- public static Complex Pow(this Complex self, Complex power) {
- return Complex.Pow(self, power);
- }
-#endif
-
- #endregion
-#endif
- }
-
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ReferenceEqualityComparer.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ReferenceEqualityComparer.cs
deleted file mode 100644
index 291a23eec16..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ReferenceEqualityComparer.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Collections.Generic;
-using System.Runtime.CompilerServices;
-using System.Linq.Expressions;
-using System.Dynamic;
-
-namespace Microsoft.Scripting.Utils {
- public sealed class ReferenceEqualityComparer<T> : IEqualityComparer<T> where T : class {
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
- public static readonly ReferenceEqualityComparer<T> Instance = new ReferenceEqualityComparer<T>();
-
- private ReferenceEqualityComparer() { }
-
- public bool Equals(T x, T y) {
- return object.ReferenceEquals(x, y);
- }
-
-#if WIN8
- private static Expression NullConst = Expression.Constant(null);
- private static int H = 536870912 ^ NullConst.GetHashCode();
-#endif
-
- public int GetHashCode(T obj) {
-#if WP75 // CF RH.GetHashCode throws NullReferenceException if the argument is null
- return obj != null ? RuntimeHelpers.GetHashCode(obj) : 0;
-#elif WIN8
- // TODO: HACK!
- return BindingRestrictions.GetInstanceRestriction(NullConst, obj).GetHashCode() ^ H;
-#else
- return RuntimeHelpers.GetHashCode(obj);
-#endif
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ReflectionUtils.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ReflectionUtils.cs
deleted file mode 100644
index 342f258a62d..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ReflectionUtils.cs
+++ /dev/null
@@ -1,1951 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_METADATA_READER
-using Microsoft.Scripting.Metadata;
-#endif
-
-#if !WIN8
-using TypeInfo = System.Type;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Linq;
-using System.Reflection;
-#if FEATURE_REFEMIT
-using System.Reflection.Emit;
-#endif
-using System.Runtime.CompilerServices;
-using System.Security;
-using System.Text;
-using System.Runtime.InteropServices;
-using System.Dynamic;
-using System.Linq.Expressions;
-
-using Microsoft.Scripting.Generation;
-using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
-
-#if WIN8 || WP75
-namespace System.Runtime.CompilerServices {
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event)]
- public sealed class SpecialNameAttribute : Attribute {
- public SpecialNameAttribute() {
- }
- }
-}
-#endif
-
-#if WIN8
-namespace System {
- public enum TypeCode {
- Empty,
- Object,
- DBNull,
- Boolean,
- Char,
- SByte,
- Byte,
- Int16,
- UInt16,
- Int32,
- UInt32,
- Int64,
- UInt64,
- Single,
- Double,
- Decimal,
- DateTime,
- String = 18
- }
-}
-
-namespace System.Reflection {
- [Flags]
- public enum BindingFlags {
- /// <summary>Specifies that instance members are to be included in the search.</summary>
- Instance = 4,
- /// <summary>Specifies that static members are to be included in the search.</summary>
- Static = 8,
- /// <summary>Specifies that public members are to be included in the search.</summary>
- Public = 16,
- /// <summary>Specifies that non-public members are to be included in the search.</summary>
- NonPublic = 32
- }
-}
-#elif !CLR45
-namespace System.Reflection {
- public static class RuntimeReflectionExtensions {
- public static MethodInfo GetRuntimeBaseDefinition(this MethodInfo method) {
- return method.GetBaseDefinition();
- }
-
- public static IEnumerable<MethodInfo> GetRuntimeMethods(this Type type) {
- return type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
- }
- }
-}
-#endif
-
-namespace Microsoft.Scripting.Utils {
- // CF doesn't support DefaultParameterValue attribute. Define our own, but not in System.Runtime.InteropServices namespace as that would
- // make C# compiler emit the parameter's default value metadata not the attribute itself. The default value metadata are not accessible on CF.
-#if !FEATURE_DEFAULT_PARAMETER_VALUE
- /// <summary>
- /// The Default Parameter Value Attribute.
- /// </summary>
- public sealed class DefaultParameterValueAttribute : Attribute
- {
- private readonly object _value;
-
- public object Value
- {
- get { return _value; }
- }
-
- /// <summary>
- /// The constructor
- /// </summary>
- /// <param name="value">The value.</param>
- public DefaultParameterValueAttribute(object value)
- {
- _value = value;
- }
- }
-
-#if !ANDROID
- [AttributeUsage(AttributeTargets.Parameter, Inherited = false), ComVisible(true)]
- public sealed class OptionalAttribute : Attribute {
- }
-#endif
-#endif
-
- public static class ReflectionUtils {
- #region Accessibility
-
- public const BindingFlags AllMembers = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
-
- public static bool IsPublic(this PropertyInfo property) {
- return property.GetGetMethod(nonPublic: false) != null
- || property.GetSetMethod(nonPublic: false) != null;
- }
-
- public static bool IsStatic(this PropertyInfo property) {
- var getter = property.GetGetMethod(nonPublic: true);
- var setter = property.GetSetMethod(nonPublic: true);
-
- return getter != null && getter.IsStatic
- || setter != null && setter.IsStatic;
- }
-
- public static bool IsStatic(this EventInfo evnt) {
- var add = evnt.GetAddMethod(nonPublic: true);
- var remove = evnt.GetRemoveMethod(nonPublic: true);
-
- return add != null && add.IsStatic
- || remove != null && remove.IsStatic;
- }
-
- public static bool IsPrivate(this PropertyInfo property) {
- var getter = property.GetGetMethod(nonPublic: true);
- var setter = property.GetSetMethod(nonPublic: true);
-
- return (getter == null || getter.IsPrivate)
- && (setter == null || setter.IsPrivate);
- }
-
- public static bool IsPrivate(this EventInfo evnt) {
- var add = evnt.GetAddMethod(nonPublic: true);
- var remove = evnt.GetRemoveMethod(nonPublic: true);
-
- return (add == null || add.IsPrivate)
- && (remove == null || remove.IsPrivate);
- }
-
- private static bool MatchesFlags(ConstructorInfo member, BindingFlags flags) {
- return
- ((member.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 &&
- ((member.IsStatic ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0;
- }
-
- private static bool MatchesFlags(MethodInfo member, BindingFlags flags) {
- return
- ((member.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 &&
- ((member.IsStatic ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0;
- }
-
- private static bool MatchesFlags(FieldInfo member, BindingFlags flags) {
- return
- ((member.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 &&
- ((member.IsStatic ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0;
- }
-
- private static bool MatchesFlags(PropertyInfo member, BindingFlags flags) {
- return
- ((member.IsPublic() ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 &&
- ((member.IsStatic() ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0;
- }
-
- private static bool MatchesFlags(EventInfo member, BindingFlags flags) {
- var add = member.GetAddMethod();
- var remove = member.GetRemoveMethod();
- var raise = member.GetRaiseMethod();
-
- bool isPublic = add != null && add.IsPublic || remove != null && remove.IsPublic || raise != null && raise.IsPublic;
- bool isStatic = add != null && add.IsStatic || remove != null && remove.IsStatic || raise != null && raise.IsStatic;
-
- return
- ((isPublic ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0 &&
- ((isStatic ? BindingFlags.Static : BindingFlags.Instance) & flags) != 0;
- }
-
- private static bool MatchesFlags(TypeInfo member, BindingFlags flags) {
- // Static/Instance are ignored
- return (((member.IsPublic || member.IsNestedPublic) ? BindingFlags.Public : BindingFlags.NonPublic) & flags) != 0;
- }
-
- private static bool MatchesFlags(MemberInfo member, BindingFlags flags) {
- ConstructorInfo ctor;
- MethodInfo method;
- FieldInfo field;
- EventInfo evnt;
- PropertyInfo property;
-
- if ((method = member as MethodInfo) != null) {
- return MatchesFlags(method, flags);
- }
-
- if ((field = member as FieldInfo) != null) {
- return MatchesFlags(field, flags);
- }
-
- if ((ctor = member as ConstructorInfo) != null) {
- return MatchesFlags(ctor, flags);
- }
-
- if ((evnt = member as EventInfo) != null) {
- return MatchesFlags(evnt, flags);
- }
-
- if ((property = member as PropertyInfo) != null) {
- return MatchesFlags(property, flags);
- }
-
- return MatchesFlags((TypeInfo)member, flags);
- }
-
- private static IEnumerable<T> WithBindingFlags<T>(this IEnumerable<T> members, Func<T, BindingFlags, bool> matchFlags, BindingFlags flags)
- where T : MemberInfo {
- return members.Where(member => matchFlags(member, flags));
- }
-
- public static IEnumerable<MemberInfo> WithBindingFlags(this IEnumerable<MemberInfo> members, BindingFlags flags) {
- return members.WithBindingFlags(MatchesFlags, flags);
- }
-
- public static IEnumerable<MethodInfo> WithBindingFlags(this IEnumerable<MethodInfo> members, BindingFlags flags) {
- return members.WithBindingFlags(MatchesFlags, flags);
- }
-
- public static IEnumerable<ConstructorInfo> WithBindingFlags(this IEnumerable<ConstructorInfo> members, BindingFlags flags) {
- return members.WithBindingFlags(MatchesFlags, flags);
- }
-
- public static IEnumerable<FieldInfo> WithBindingFlags(this IEnumerable<FieldInfo> members, BindingFlags flags) {
- return members.WithBindingFlags(MatchesFlags, flags);
- }
-
- public static IEnumerable<PropertyInfo> WithBindingFlags(this IEnumerable<PropertyInfo> members, BindingFlags flags) {
- return members.WithBindingFlags(MatchesFlags, flags);
- }
-
- public static IEnumerable<EventInfo> WithBindingFlags(this IEnumerable<EventInfo> members, BindingFlags flags) {
- return members.WithBindingFlags(MatchesFlags, flags);
- }
-
- public static IEnumerable<TypeInfo> WithBindingFlags(this IEnumerable<TypeInfo> members, BindingFlags flags) {
- return members.WithBindingFlags(MatchesFlags, flags);
- }
-
- public static MemberInfo WithBindingFlags(this MemberInfo member, BindingFlags flags) {
- return member != null && MatchesFlags(member, flags) ? member : null;
- }
-
- public static MethodInfo WithBindingFlags(this MethodInfo member, BindingFlags flags) {
- return member != null && MatchesFlags(member, flags) ? member : null;
- }
-
- public static ConstructorInfo WithBindingFlags(this ConstructorInfo member, BindingFlags flags) {
- return member != null && MatchesFlags(member, flags) ? member : null;
- }
-
- public static FieldInfo WithBindingFlags(this FieldInfo member, BindingFlags flags) {
- return member != null && MatchesFlags(member, flags) ? member : null;
- }
-
- public static PropertyInfo WithBindingFlags(this PropertyInfo member, BindingFlags flags) {
- return member != null && MatchesFlags(member, flags) ? member : null;
- }
-
- public static EventInfo WithBindingFlags(this EventInfo member, BindingFlags flags) {
- return member != null && MatchesFlags(member, flags) ? member : null;
- }
-
- public static TypeInfo WithBindingFlags(this TypeInfo member, BindingFlags flags) {
- return member != null && MatchesFlags(member, flags) ? member : null;
- }
-
- #endregion
-
- #region Signatures
-
- public static IEnumerable<MethodInfo> WithSignature(this IEnumerable<MethodInfo> members, Type[] parameterTypes) {
- return members.Where(c => {
- var ps = c.GetParameters();
- if (ps.Length != parameterTypes.Length) {
- return false;
- }
-
- for (int i = 0; i < ps.Length; i++) {
- if (parameterTypes[i] != ps[i].ParameterType) {
- return false;
- }
- }
-
- return true;
- });
- }
-
- public static IEnumerable<ConstructorInfo> WithSignature(this IEnumerable<ConstructorInfo> members, Type[] parameterTypes) {
- return members.Where(c => {
- var ps = c.GetParameters();
- if (ps.Length != parameterTypes.Length) {
- return false;
- }
-
- for (int i = 0; i < ps.Length; i++) {
- if (parameterTypes[i] != ps[i].ParameterType) {
- return false;
- }
- }
-
- return true;
- });
- }
-
- #endregion
-
- #region Member Inheritance
-
- // CLI specification, partition I, 8.10.4: Hiding, overriding, and layout
- // ----------------------------------------------------------------------
- // While hiding applies to all members of a type, overriding deals with object layout and is applicable only to instance fields
- // and virtual methods. The CTS provides two forms of member overriding, new slot and expect existing slot. A member of a derived
- // type that is marked as a new slot will always get a new slot in the object’s layout, guaranteeing that the base field or method
- // is available in the object by using a qualified reference that combines the name of the base type with the name of the member
- // and its type or signature. A member of a derived type that is marked as expect existing slot will re-use (i.e., share or override)
- // a slot that corresponds to a member of the same kind (field or method), name, and type if one already exists from the base type;
- // if no such slot exists, a new slot is allocated and used.
- //
- // The general algorithm that is used for determining the names in a type and the layout of objects of the type is roughly as follows:
- // - Flatten the inherited names (using the hide by name or hide by name-and-signature rule) ignoring accessibility rules.
- // - For each new member that is marked “expect existing slot”, look to see if an exact match on kind (i.e., field or method),
- // name, and signature exists and use that slot if it is found, otherwise allocate a new slot.
- // - After doing this for all new members, add these new member-kind/name/signatures to the list of members of this type
- // - Finally, remove any inherited names that match the new members based on the hide by name or hide by name-and-signature rules.
-
- // NOTE: Following GetXxx only implement overriding, not hiding specified by hide-by-name or hide-by-name-and-signature flags.
-
- public static IEnumerable<MethodInfo> GetInheritedMethods(this Type type, string name = null, bool flattenHierarchy = false) {
- while (type.IsGenericParameter) {
- type = type.GetBaseType();
- }
-
- var baseDefinitions = new HashSet<MethodInfo>(ReferenceEqualityComparer<MethodInfo>.Instance);
- foreach (var ancestor in type.Ancestors()) {
- foreach (var declaredMethod in ancestor.GetDeclaredMethods(name)) {
- if (declaredMethod != null && IncludeMethod(declaredMethod, type, baseDefinitions, flattenHierarchy)) {
- yield return declaredMethod;
- }
- }
- }
- }
-
- private static bool IncludeMethod(MethodInfo member, Type reflectedType, HashSet<MethodInfo> baseDefinitions, bool flattenHierarchy) {
- if (member.IsVirtual) {
- if (baseDefinitions.Add(RuntimeReflectionExtensions.GetRuntimeBaseDefinition(member))) {
- return true;
- }
- } else if (member.DeclaringType == reflectedType) {
- return true;
- } else if (!member.IsPrivate && (!member.IsStatic || flattenHierarchy)) {
- return true;
- }
-
- return false;
- }
-
- public static IEnumerable<PropertyInfo> GetInheritedProperties(this Type type, string name = null, bool flattenHierarchy = false) {
- while (type.IsGenericParameter) {
- type = type.GetBaseType();
- }
-
- var baseDefinitions = new HashSet<MethodInfo>(ReferenceEqualityComparer<MethodInfo>.Instance);
- foreach (var ancestor in type.Ancestors()) {
- if (name != null) {
- var declaredProperty = ancestor.GetDeclaredProperty(name);
- if (declaredProperty != null && IncludeProperty(declaredProperty, type, baseDefinitions, flattenHierarchy)) {
- yield return declaredProperty;
- }
- } else {
- foreach (var declaredProperty in ancestor.GetDeclaredProperties()) {
- if (IncludeProperty(declaredProperty, type, baseDefinitions, flattenHierarchy)) {
- yield return declaredProperty;
- }
- }
- }
- }
- }
-
- // CLI spec 22.34 Properties
- // -------------------------
- // [Note: The CLS (see Partition I) refers to instance, virtual, and static properties.
- // The signature of a property (from the Type column) can be used to distinguish a static property,
- // since instance and virtual properties will have the “HASTHIS” bit set in the signature (§23.2.1)
- // while a static property will not. The distinction between an instance and a virtual property
- // depends on the signature of the getter and setter methods, which the CLS requires to be either
- // both virtual or both instance. end note]
- private static bool IncludeProperty(PropertyInfo member, Type reflectedType, HashSet<MethodInfo> baseDefinitions, bool flattenHierarchy) {
- var getter = member.GetGetMethod(nonPublic: true);
- var setter = member.GetSetMethod(nonPublic: true);
-
- MethodInfo virtualAccessor;
- if (getter != null && getter.IsVirtual) {
- virtualAccessor = getter;
- } else if (setter != null && setter.IsVirtual) {
- virtualAccessor = setter;
- } else {
- virtualAccessor = null;
- }
-
- if (virtualAccessor != null) {
- if (baseDefinitions.Add(RuntimeReflectionExtensions.GetRuntimeBaseDefinition(virtualAccessor))) {
- return true;
- }
- } else if (member.DeclaringType == reflectedType) {
- return true;
- } else if (!member.IsPrivate() && (!member.IsStatic() || flattenHierarchy)) {
- return true;
- }
-
- return false;
- }
-
- public static IEnumerable<EventInfo> GetInheritedEvents(this Type type, string name = null, bool flattenHierarchy = false) {
- while (type.IsGenericParameter) {
- type = type.GetBaseType();
- }
-
- var baseDefinitions = new HashSet<MethodInfo>(ReferenceEqualityComparer<MethodInfo>.Instance);
- foreach (var ancestor in type.Ancestors()) {
- if (name != null) {
- var declaredEvent = ancestor.GetDeclaredEvent(name);
- if (declaredEvent != null && IncludeEvent(declaredEvent, type, baseDefinitions, flattenHierarchy)) {
- yield return declaredEvent;
- }
- } else {
- foreach (var declaredEvent in ancestor.GetDeclaredEvents()) {
- if (IncludeEvent(declaredEvent, type, baseDefinitions, flattenHierarchy)) {
- yield return declaredEvent;
- }
- }
- }
- }
- }
-
- private static bool IncludeEvent(EventInfo member, Type reflectedType, HashSet<MethodInfo> baseDefinitions, bool flattenHierarchy) {
- var add = member.GetAddMethod(nonPublic: true);
- var remove = member.GetRemoveMethod(nonPublic: true);
-
- // TOOD: fire method?
-
- MethodInfo virtualAccessor;
- if (add != null && add.IsVirtual) {
- virtualAccessor = add;
- } else if (remove != null && remove.IsVirtual) {
- virtualAccessor = remove;
- } else {
- virtualAccessor = null;
- }
-
- if (virtualAccessor != null) {
- if (baseDefinitions.Add(RuntimeReflectionExtensions.GetRuntimeBaseDefinition(virtualAccessor))) {
- return true;
- }
- } else if (member.DeclaringType == reflectedType) {
- return true;
- } else if (!member.IsPrivate() && (!member.IsStatic() || flattenHierarchy)) {
- return true;
- }
-
- return false;
- }
-
- public static IEnumerable<FieldInfo> GetInheritedFields(this Type type, string name = null, bool flattenHierarchy = false) {
- while (type.IsGenericParameter) {
- type = type.GetBaseType();
- }
-
- foreach (var ancestor in type.Ancestors()) {
- if (name != null) {
- var declaredField = ancestor.GetDeclaredField(name);
- if (declaredField != null && IncludeField(declaredField, type, flattenHierarchy)) {
- yield return declaredField;
- }
- } else {
- foreach (var declaredField in ancestor.GetDeclaredFields()) {
- if (IncludeField(declaredField, type, flattenHierarchy)) {
- yield return declaredField;
- }
- }
- }
- }
- }
-
- private static bool IncludeField(FieldInfo member, Type reflectedType, bool flattenHierarchy) {
- if (member.DeclaringType == reflectedType) {
- return true;
- } else if (!member.IsPrivate && (!member.IsStatic || flattenHierarchy)) {
- return true;
- }
-
- return false;
- }
-
- public static IEnumerable<MemberInfo> GetInheritedMembers(this Type type, string name = null, bool flattenHierarchy = false) {
- var result =
- type.GetInheritedMethods(name, flattenHierarchy).Cast<MethodInfo, MemberInfo>().Concat(
- type.GetInheritedProperties(name, flattenHierarchy).Cast<PropertyInfo, MemberInfo>().Concat(
- type.GetInheritedEvents(name, flattenHierarchy).Cast<EventInfo, MemberInfo>().Concat(
- type.GetInheritedFields(name, flattenHierarchy).Cast<FieldInfo, MemberInfo>())));
-
- if (name == null) {
- return result.Concat<MemberInfo>(
- type.GetDeclaredConstructors().Cast<ConstructorInfo, MemberInfo>().Concat(
- type.GetDeclaredNestedTypes().Cast<TypeInfo, MemberInfo>()));
- }
-
- var nestedType = type.GetDeclaredNestedType(name);
- return (nestedType != null) ? result.Concat(new[] { nestedType }) : result;
- }
-
- #endregion
-
- #region Declared Members
-
- public static IEnumerable<ConstructorInfo> GetDeclaredConstructors(this Type type) {
-#if WIN8
- return type.GetTypeInfo().DeclaredConstructors;
-#else
- return type.GetConstructors(BindingFlags.DeclaredOnly | AllMembers);
-#endif
- }
-
-#if WIN8
- public static ConstructorInfo GetConstructor(this Type type, Type[] parameterTypes) {
- return type.GetDeclaredConstructors().Where(ci => !ci.IsStatic && ci.IsPublic).WithSignature(parameterTypes).SingleOrDefault();
- }
-#endif
-
- public static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type, string name = null) {
-#if WIN8
- if (name == null) {
- return type.GetTypeInfo().DeclaredMethods;
- } else {
- return type.GetTypeInfo().GetDeclaredMethods(name);
- }
-#else
- if (name == null) {
- return type.GetMethods(BindingFlags.DeclaredOnly | AllMembers);
- } else {
- return type.GetMember(name, MemberTypes.Method, BindingFlags.DeclaredOnly | AllMembers).OfType<MethodInfo>();
- }
-#endif
- }
-
- public static IEnumerable<PropertyInfo> GetDeclaredProperties(this Type type) {
-#if WIN8
- return type.GetTypeInfo().DeclaredProperties;
-#else
- return type.GetProperties(BindingFlags.DeclaredOnly | AllMembers);
-#endif
- }
-
- public static PropertyInfo GetDeclaredProperty(this Type type, string name) {
- Debug.Assert(name != null);
-#if WIN8
- return type.GetTypeInfo().GetDeclaredProperty(name);
-#else
- return type.GetProperty(name, BindingFlags.DeclaredOnly | AllMembers);
-#endif
- }
-
- public static IEnumerable<EventInfo> GetDeclaredEvents(this Type type) {
-#if WIN8
- return type.GetTypeInfo().DeclaredEvents;
-#else
- return type.GetEvents(BindingFlags.DeclaredOnly | AllMembers);
-#endif
- }
-
- public static EventInfo GetDeclaredEvent(this Type type, string name) {
- Debug.Assert(name != null);
-#if WIN8
- return type.GetTypeInfo().GetDeclaredEvent(name);
-#else
- return type.GetEvent(name, BindingFlags.DeclaredOnly | AllMembers);
-#endif
- }
-
- public static IEnumerable<FieldInfo> GetDeclaredFields(this Type type) {
-#if WIN8
- return type.GetTypeInfo().DeclaredFields;
-#else
- return type.GetFields(BindingFlags.DeclaredOnly | AllMembers);
-#endif
- }
-
- public static FieldInfo GetDeclaredField(this Type type, string name) {
- Debug.Assert(name != null);
-#if WIN8
- return type.GetTypeInfo().GetDeclaredField(name);
-#else
- return type.GetField(name, BindingFlags.DeclaredOnly | AllMembers);
-#endif
- }
-
- public static IEnumerable<TypeInfo> GetDeclaredNestedTypes(this Type type) {
-#if WIN8
- return type.GetTypeInfo().DeclaredNestedTypes;
-#else
- return type.GetNestedTypes(BindingFlags.DeclaredOnly | AllMembers);
-#endif
- }
-
- public static TypeInfo GetDeclaredNestedType(this Type type, string name) {
- Debug.Assert(name != null);
-#if WIN8
- return type.GetTypeInfo().GetDeclaredNestedType(name);
-#else
- return type.GetNestedType(name, BindingFlags.DeclaredOnly | AllMembers);
-#endif
- }
-
- public static IEnumerable<MemberInfo> GetDeclaredMembers(this Type type, string name = null) {
-#if WIN8
- var info = type.GetTypeInfo();
- if (name == null) {
- return info.DeclaredMembers;
- } else {
- return GetDeclaredMembersWithName(info, name);
- }
-#else
- if (name == null) {
- return type.GetMembers(BindingFlags.DeclaredOnly | AllMembers);
- } else {
- return type.GetMember(name, BindingFlags.DeclaredOnly | AllMembers);
- }
-#endif
- }
-
-#if WIN8
- private static IEnumerable<MemberInfo> GetDeclaredMembersWithName(TypeInfo info, string name) {
- MemberInfo member;
-
- if ((member = info.GetDeclaredMethod(name)) != null) {
- yield return member;
- }
-
- if ((member = info.GetDeclaredField(name)) != null) {
- yield return member;
- }
-
- if ((member = info.GetDeclaredProperty(name)) != null) {
- yield return member;
- }
-
- if ((member = info.GetDeclaredEvent(name)) != null) {
- yield return member;
- }
-
- if ((member = info.GetDeclaredNestedType(name)) != null) {
- yield return member;
- }
- }
-#endif
-
- #endregion
-
- #region Win8
-#if WIN8 || CLR45
- public static TypeCode GetTypeCode(this Enum e) {
- return GetTypeCode(Enum.GetUnderlyingType(e.GetType()));
- }
-
- // TODO: reduce to numeric types?
- public static TypeCode GetTypeCode(this Type type) {
- if (type == typeof(int)) {
- return TypeCode.Int32;
- }
- if (type == typeof(sbyte)) {
- return TypeCode.SByte;
- }
- if (type == typeof(short)) {
- return TypeCode.Int16;
- }
- if (type == typeof(long)) {
- return TypeCode.Int64;
- }
- if (type == typeof(uint)) {
- return TypeCode.UInt32;
- }
- if (type == typeof(byte)) {
- return TypeCode.Byte;
- }
- if (type == typeof(ushort)) {
- return TypeCode.UInt16;
- }
- if (type == typeof(ulong)) {
- return TypeCode.UInt64;
- }
- if (type == typeof(bool)) {
- return TypeCode.Boolean;
- }
- if (type == typeof(char)) {
- return TypeCode.Char;
- }
-
- // TODO: do we need this?
- if (type == typeof(string)) {
- return TypeCode.String;
- }
- if (type == typeof(bool)) {
- return TypeCode.Boolean;
- }
- if (type == typeof(double)) {
- return TypeCode.Double;
- }
- if (type == typeof(float)) {
- return TypeCode.Single;
- }
- if (type == typeof(decimal)) {
- return TypeCode.Decimal;
- }
- if (type == typeof(DateTime)) {
- return TypeCode.DateTime;
- }
- return TypeCode.Object;
- }
-
- public static IEnumerable<Type> GetImplementedInterfaces(this Type type) {
- return type.GetTypeInfo().ImplementedInterfaces;
- }
-
- public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo, bool nonPublic = false) {
- var accessor = propertyInfo.GetMethod;
- return nonPublic || accessor == null || accessor.IsPublic ? accessor : null;
- }
-
- public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo, bool nonPublic = false) {
- var accessor = propertyInfo.SetMethod;
- return nonPublic || accessor == null || accessor.IsPublic ? accessor : null;
- }
-
- public static MethodInfo GetAddMethod(this EventInfo eventInfo, bool nonPublic = false) {
- var accessor = eventInfo.AddMethod;
- return nonPublic || accessor == null || accessor.IsPublic ? accessor : null;
- }
-
- public static MethodInfo GetRemoveMethod(this EventInfo eventInfo, bool nonPublic = false) {
- var accessor = eventInfo.RemoveMethod;
- return nonPublic || accessor == null || accessor.IsPublic ? accessor : null;
- }
-
- public static MethodInfo GetRaiseMethod(this EventInfo eventInfo, bool nonPublic = false) {
- var accessor = eventInfo.RaiseMethod;
- return nonPublic || accessor == null || accessor.IsPublic ? accessor : null;
- }
-
- public static MethodInfo GetMethod(this Type type, string name) {
- return type.GetTypeInfo().GetDeclaredMethod(name);
- }
-
- // TODO: FlattenHierarchy
- // TODO: inherited!
- public static MethodInfo GetMethod(this Type type, string name, Type[] parameterTypes) {
- return type.GetTypeInfo().GetDeclaredMethods(name).WithSignature(parameterTypes).Single();
- }
-
- public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingFlags) {
- return type.GetMethods(name, bindingFlags).Single();
- }
-
- private static IEnumerable<MethodInfo> GetMethods(this Type type, string name, BindingFlags bindingFlags) {
- return type.GetTypeInfo().GetDeclaredMethods(name).WithBindingFlags(bindingFlags);
- }
-
- public static MethodInfo GetMethod(this Delegate d) {
- return d.GetMethodInfo();
- }
-
- // TODO: Callers should distinguish parameters from arguments. Stop using this method.
- public static Type[] GetGenericArguments(this Type type) {
- var info = type.GetTypeInfo();
- return info.IsGenericTypeDefinition ? info.GenericTypeParameters : info.GenericTypeArguments;
- }
-
- public static Type[] GetGenericTypeArguments(this Type type) {
- return type.GetTypeInfo().GenericTypeArguments;
- }
-
- public static Type[] GetGenericTypeParameters(this Type type) {
- return type.GetTypeInfo().GenericTypeParameters;
- }
-
- public static bool IsAssignableFrom(this Type type, Type other) {
- return type.GetTypeInfo().IsAssignableFrom(other.GetTypeInfo());
- }
-
- public static Type[] GetGenericParameterConstraints(this Type type) {
- return type.GetTypeInfo().GetGenericParameterConstraints();
- }
-
- public static bool IsSubclassOf(this Type type, Type other) {
- return type.GetTypeInfo().IsSubclassOf(other);
- }
-
- public static IEnumerable<Type> GetInterfaces(this Type type) {
- return type.GetTypeInfo().ImplementedInterfaces;
- }
-
- public static Type[] GetRequiredCustomModifiers(this ParameterInfo parameter) {
- return EmptyTypes;
- }
-
- public static Type[] GetOptionalCustomModifiers(this ParameterInfo parameter) {
- return EmptyTypes;
- }
-
- public static IEnumerable<Module> GetModules(this Assembly assembly) {
- return assembly.Modules;
- }
-
- private static string GetDefaultMemberName(this Type type) {
- foreach (var ancestor in type.Ancestors()) {
- var attr = ancestor.GetTypeInfo().GetCustomAttributes<DefaultMemberAttribute>().SingleOrDefault();
- if (attr != null) {
- return attr.MemberName;
- }
- }
-
- return null;
- }
-
- public static IEnumerable<MemberInfo> GetDefaultMembers(this Type type) {
- string defaultMemberName = type.GetDefaultMemberName();
- if (defaultMemberName != null) {
- return type.GetInheritedMembers(defaultMemberName).WithBindingFlags(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
- }
-
- return Enumerable.Empty<MemberInfo>();
- }
-#else
- public static Type[] GetGenericTypeArguments(this Type type) {
- return type.IsGenericType && !type.IsGenericTypeDefinition ? type.GetTypeInfo().GetGenericArguments() : null;
- }
-
- public static Type[] GetGenericTypeParameters(this Type type) {
- return type.IsGenericTypeDefinition ? type.GetTypeInfo().GetGenericArguments() : null;
- }
-
- public static IEnumerable<Module> GetModules(this Assembly assembly) {
- return assembly.GetModules();
- }
-
- public static IEnumerable<Type> GetImplementedInterfaces(this Type type) {
- return type.GetInterfaces();
- }
-
- public static TypeCode GetTypeCode(this Type type) {
- return Type.GetTypeCode(type);
- }
-
- public static MethodInfo GetMethodInfo(this Delegate d) {
- return d.Method;
- }
-
- public static bool IsDefined(this Assembly assembly, Type attributeType) {
- return assembly.IsDefined(attributeType, false);
- }
-
- public static T GetCustomAttribute<T>(this Assembly assembly, bool inherit = false) where T : Attribute {
- return (T)Attribute.GetCustomAttribute(assembly, typeof(T), inherit);
- }
-
- public static T GetCustomAttribute<T>(this MemberInfo member, bool inherit = false) where T : Attribute {
- return (T)Attribute.GetCustomAttribute(member, typeof(T), inherit);
- }
-
- public static IEnumerable<T> GetCustomAttributes<T>(this Assembly assembly, bool inherit = false) where T : Attribute {
- return Attribute.GetCustomAttributes(assembly, typeof(T), inherit).Cast<T>();
- }
-
- public static IEnumerable<T> GetCustomAttributes<T>(this MemberInfo member, bool inherit = false) where T : Attribute {
- return Attribute.GetCustomAttributes(member, typeof(T), inherit).Cast<T>();
- }
-#endif
-
- public static bool ContainsGenericParameters(this Type type) {
- return type.GetTypeInfo().ContainsGenericParameters;
- }
-
- public static bool IsInterface(this Type type) {
- return type.GetTypeInfo().IsInterface;
- }
-
- public static bool IsClass(this Type type) {
- return type.GetTypeInfo().IsClass;
- }
-
- public static bool IsGenericType(this Type type) {
- return type.GetTypeInfo().IsGenericType;
- }
-
- public static bool IsGenericTypeDefinition(this Type type) {
- return type.GetTypeInfo().IsGenericTypeDefinition;
- }
-
- public static bool IsSealed(this Type type) {
- return type.GetTypeInfo().IsSealed;
- }
-
- public static bool IsAbstract(this Type type) {
- return type.GetTypeInfo().IsAbstract;
- }
-
- public static bool IsPublic(this Type type) {
- return type.GetTypeInfo().IsPublic;
- }
-
- public static bool IsVisible(this Type type) {
- return type.GetTypeInfo().IsVisible;
- }
-
- public static Type GetBaseType(this Type type) {
- return type.GetTypeInfo().BaseType;
- }
-
- public static bool IsValueType(this Type type) {
- return type.GetTypeInfo().IsValueType;
- }
-
- public static bool IsEnum(this Type type) {
- return type.GetTypeInfo().IsEnum;
- }
-
- public static bool IsPrimitive(this Type type) {
- return type.GetTypeInfo().IsPrimitive;
- }
-
- public static GenericParameterAttributes GetGenericParameterAttributes(this Type type) {
- return type.GetTypeInfo().GenericParameterAttributes;
- }
-
- public static Type[] EmptyTypes = new Type[0];
-
- public static object GetRawConstantValue(this FieldInfo field) {
- if (!field.IsLiteral) {
- throw new ArgumentException(field + " not a literal.");
- }
-
- object value = field.GetValue(null);
- return field.FieldType.IsEnum() ? UnwrapEnumValue(value) : value;
- }
-
- /// <summary>
- /// Converts a boxed enum value to the underlying integer value.
- /// </summary>
- public static object UnwrapEnumValue(object value) {
- if (value == null) {
- throw new ArgumentNullException("value");
- }
-
- switch (value.GetType().GetTypeCode()) {
- case TypeCode.Byte:
- return System.Convert.ToByte(value);
-
- case TypeCode.Int16:
- return System.Convert.ToInt16(value);
-
- case TypeCode.Int32:
- return System.Convert.ToInt32(value);
-
- case TypeCode.Int64:
- return System.Convert.ToInt64(value);
-
- case TypeCode.SByte:
- return System.Convert.ToSByte(value);
-
- case TypeCode.UInt16:
- return System.Convert.ToUInt16(value);
-
- case TypeCode.UInt32:
- return System.Convert.ToUInt32(value);
-
- case TypeCode.UInt64:
- return System.Convert.ToUInt64(value);
-
- default:
- throw new ArgumentException("Value must be a boxed enum.", "value");
- }
- }
-
- #endregion
-
-#if FEATURE_REFEMIT
-#if FEATURE_ASSEMBLYBUILDER_DEFINEDYNAMICASSEMBLY
- public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) {
- return AssemblyBuilder.DefineDynamicAssembly(name, access);
- }
-#else
- public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) {
- return AppDomain.CurrentDomain.DefineDynamicAssembly(name, access);
- }
-#endif
-#if !FEATURE_PDBEMIT
- public static ModuleBuilder DefineDynamicModule(this AssemblyBuilder assembly, string name, bool emitDebugInfo) {
- // ignore the flag
- return assembly.DefineDynamicModule(name);
- }
-#endif
-#endif
-
- #region Signature and Type Formatting
-
- // Generic type names have the arity (number of generic type paramters) appended at the end.
- // For eg. the mangled name of System.List<T> is "List`1". This mangling is done to enable multiple
- // generic types to exist as long as they have different arities.
- public const char GenericArityDelimiter = '`';
-
-#if !WIN8
- public static StringBuilder FormatSignature(StringBuilder result, MethodBase method) {
- return FormatSignature(result, method, (t) => t.FullName);
- }
-
- public static StringBuilder FormatSignature(StringBuilder result, MethodBase method, Func<Type, string> nameDispenser) {
- ContractUtils.RequiresNotNull(result, "result");
- ContractUtils.RequiresNotNull(method, "method");
- ContractUtils.RequiresNotNull(nameDispenser, "nameDispenser");
-
- MethodInfo methodInfo = method as MethodInfo;
- if (methodInfo != null) {
- FormatTypeName(result, methodInfo.ReturnType, nameDispenser);
- result.Append(' ');
- }
-
-#if FEATURE_REFEMIT
- MethodBuilder builder = method as MethodBuilder;
- if (builder != null) {
- result.Append(builder.Signature);
- return result;
- }
-
- ConstructorBuilder cb = method as ConstructorBuilder;
- if (cb != null) {
- result.Append(cb.Signature);
- return result;
- }
-#endif
- FormatTypeName(result, method.DeclaringType, nameDispenser);
- result.Append("::");
- result.Append(method.Name);
-
- if (!method.IsConstructor) {
- FormatTypeArgs(result, method.GetGenericArguments(), nameDispenser);
- }
-
- result.Append("(");
-
- if (!method.ContainsGenericParameters) {
- ParameterInfo[] ps = method.GetParameters();
- for (int i = 0; i < ps.Length; i++) {
- if (i > 0) result.Append(", ");
- FormatTypeName(result, ps[i].ParameterType, nameDispenser);
- if (!System.String.IsNullOrEmpty(ps[i].Name)) {
- result.Append(" ");
- result.Append(ps[i].Name);
- }
- }
- } else {
- result.Append("?");
- }
-
- result.Append(")");
- return result;
- }
-#endif
-
- public static StringBuilder FormatTypeName(StringBuilder result, Type type) {
- return FormatTypeName(result, type, (t) => t.FullName);
- }
-
- public static StringBuilder FormatTypeName(StringBuilder result, Type type, Func<Type, string> nameDispenser) {
- ContractUtils.RequiresNotNull(result, "result");
- ContractUtils.RequiresNotNull(type, "type");
- ContractUtils.RequiresNotNull(nameDispenser, "nameDispenser");
-
- if (type.IsGenericType()) {
- Type genType = type.GetGenericTypeDefinition();
- string genericName = nameDispenser(genType).Replace('+', '.');
- int tickIndex = genericName.IndexOf('`');
- result.Append(tickIndex != -1 ? genericName.Substring(0, tickIndex) : genericName);
-
- Type[] typeArgs = type.GetGenericArguments();
- if (type.IsGenericTypeDefinition()) {
- result.Append('<');
- result.Append(',', typeArgs.Length - 1);
- result.Append('>');
- } else {
- FormatTypeArgs(result, typeArgs, nameDispenser);
- }
- } else if (type.IsGenericParameter) {
- result.Append(type.Name);
- } else {
- // cut namespace off:
- result.Append(nameDispenser(type).Replace('+', '.'));
- }
- return result;
- }
-
- public static StringBuilder FormatTypeArgs(StringBuilder result, Type[] types) {
- return FormatTypeArgs(result, types, (t) => t.FullName);
- }
-
- public static StringBuilder FormatTypeArgs(StringBuilder result, Type[] types, Func<Type, string> nameDispenser) {
- ContractUtils.RequiresNotNull(result, "result");
- ContractUtils.RequiresNotNullItems(types, "types");
- ContractUtils.RequiresNotNull(nameDispenser, "nameDispenser");
-
- if (types.Length > 0) {
- result.Append("<");
-
- for (int i = 0; i < types.Length; i++) {
- if (i > 0) result.Append(", ");
- FormatTypeName(result, types[i], nameDispenser);
- }
-
- result.Append(">");
- }
- return result;
- }
-
- internal static string ToValidTypeName(string str) {
- if (String.IsNullOrEmpty(str)) {
- return "_";
- }
-
- StringBuilder sb = new StringBuilder(str);
- for (int i = 0; i < str.Length; i++) {
- if (str[i] == '\0' || str[i] == '.' || str[i] == '*' || str[i] == '+' || str[i] == '[' || str[i] == ']' || str[i] == '\\') {
- sb[i] = '_';
- }
- }
- return sb.ToString();
- }
-
- public static string GetNormalizedTypeName(Type type) {
- string name = type.Name;
- if (type.IsGenericType()) {
- return GetNormalizedTypeName(name);
- }
- return name;
- }
-
- public static string GetNormalizedTypeName(string typeName) {
- Debug.Assert(typeName.IndexOf('.') == -1); // This is the simple name, not the full name
- int backtick = typeName.IndexOf(ReflectionUtils.GenericArityDelimiter);
- if (backtick != -1) return typeName.Substring(0, backtick);
- return typeName;
- }
-
- #endregion
-
- #region Delegates and Dynamic Methods
-
-#if WP75
- /// <summary>
- /// Creates an open delegate for the given (dynamic)method.
- /// </summary>
- public static Delegate CreateDelegate(this MethodInfo methodInfo, Type delegateType) {
- return CreateDelegate(methodInfo, delegateType, null);
- }
-
- /// <summary>
- /// Creates a closed delegate for the given (dynamic)method.
- /// </summary>
- public static Delegate CreateDelegate(this MethodInfo methodInfo, Type delegateType, object target) {
- return Delegate.CreateDelegate(delegateType, target, methodInfo);
- }
-#elif !WIN8
- /// <summary>
- /// Creates an open delegate for the given (dynamic)method.
- /// </summary>
- public static Delegate CreateDelegate(this MethodInfo methodInfo, Type delegateType) {
- return CreateDelegate(methodInfo, delegateType, null);
- }
-
- /// <summary>
- /// Creates a closed delegate for the given (dynamic)method.
- /// </summary>
- public static Delegate CreateDelegate(this MethodInfo methodInfo, Type delegateType, object target) {
-#if FEATURE_REFEMIT
- DynamicMethod dm = methodInfo as DynamicMethod;
- if (dm != null) {
- return dm.CreateDelegate(delegateType, target);
-#endif
- return Delegate.CreateDelegate(delegateType, target, methodInfo);
- }
-#endif
-
-#if FEATURE_LCG
- public static bool IsDynamicMethod(MethodBase method) {
- return !PlatformAdaptationLayer.IsCompactFramework && IsDynamicMethodInternal(method);
- }
-
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static bool IsDynamicMethodInternal(MethodBase method) {
- return method is DynamicMethod;
- }
-#else
- public static bool IsDynamicMethod(MethodBase method) {
- return false;
- }
-#endif
-
- public static void GetDelegateSignature(Type delegateType, out ParameterInfo[] parameterInfos, out ParameterInfo returnInfo) {
- ContractUtils.RequiresNotNull(delegateType, "delegateType");
-
- MethodInfo invokeMethod = delegateType.GetMethod("Invoke");
- ContractUtils.Requires(invokeMethod != null, "delegateType", Strings.InvalidDelegate);
-
- parameterInfos = invokeMethod.GetParameters();
- returnInfo = invokeMethod.ReturnParameter;
- }
-
- /// <summary>
- /// Gets a Func of CallSite, object * paramCnt, object delegate type
- /// that's suitable for use in a non-strongly typed call site.
- /// </summary>
- public static Type GetObjectCallSiteDelegateType(int paramCnt) {
- switch (paramCnt) {
- case 0: return typeof(Func<CallSite, object, object>);
- case 1: return typeof(Func<CallSite, object, object, object>);
- case 2: return typeof(Func<CallSite, object, object, object, object>);
- case 3: return typeof(Func<CallSite, object, object, object, object, object>);
- case 4: return typeof(Func<CallSite, object, object, object, object, object, object>);
- case 5: return typeof(Func<CallSite, object, object, object, object, object, object, object>);
- case 6: return typeof(Func<CallSite, object, object, object, object, object, object, object, object>);
- case 7: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object>);
- case 8: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object>);
- case 9: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object>);
- case 10: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object>);
- case 11: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object>);
- case 12: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object, object>);
- case 13: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>);
- case 14: return typeof(Func<CallSite, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>);
- default:
-#if FEATURE_REFEMIT
- Type[] paramTypes = new Type[paramCnt + 2];
- paramTypes[0] = typeof(CallSite);
- paramTypes[1] = typeof(object);
- for (int i = 0; i < paramCnt; i++) {
- paramTypes[i + 2] = typeof(object);
- }
- return Snippets.Shared.DefineDelegate("InvokeDelegate" + paramCnt, typeof(object), paramTypes);
-#else
- throw new NotSupportedException("Signature not supported on this platform.");
-#endif
- }
- }
-
-#if FEATURE_LCG
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework")]
- internal static DynamicMethod RawCreateDynamicMethod(string name, Type returnType, Type[] parameterTypes) {
-#if SILVERLIGHT // Module-hosted DynamicMethod is not available in SILVERLIGHT
- return new DynamicMethod(name, returnType, parameterTypes);
-#else
- //
- // WARNING: we set restrictedSkipVisibility == true (last parameter)
- // setting this bit will allow accessing nonpublic members
- // for more information see http://msdn.microsoft.com/en-us/library/bb348332.aspx
- //
- return new DynamicMethod(name, returnType, parameterTypes, true);
-#endif
- }
-#endif
-
- #endregion
-
- #region Methods and Parameters
-
- public static MethodBase[] GetMethodInfos(MemberInfo[] members) {
- return ArrayUtils.ConvertAll<MemberInfo, MethodBase>(
- members,
- delegate(MemberInfo inp) { return (MethodBase)inp; });
- }
-
- public static Type[] GetParameterTypes(ParameterInfo[] parameterInfos) {
- return GetParameterTypes((IList<ParameterInfo>)parameterInfos);
- }
-
- public static Type[] GetParameterTypes(IList<ParameterInfo> parameterInfos) {
- Type[] result = new Type[parameterInfos.Count];
- for (int i = 0; i < result.Length; i++) {
- result[i] = parameterInfos[i].ParameterType;
- }
- return result;
- }
-
- public static Type GetReturnType(this MethodBase mi) {
- return (mi.IsConstructor) ? mi.DeclaringType : ((MethodInfo)mi).ReturnType;
- }
-
- public static bool SignatureEquals(MethodInfo method, params Type[] requiredSignature) {
- ContractUtils.RequiresNotNull(method, "method");
-
- Type[] actualTypes = ReflectionUtils.GetParameterTypes(method.GetParameters());
- Debug.Assert(actualTypes.Length == requiredSignature.Length - 1);
- int i = 0;
- while (i < actualTypes.Length) {
- if (actualTypes[i] != requiredSignature[i]) return false;
- i++;
- }
-
- return method.ReturnType == requiredSignature[i];
- }
-
-#if CLR2 && !SILVERLIGHT
- private static Type _ExtensionAttributeType;
-#endif
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
- public static bool IsExtension(this MemberInfo member) {
- var dlrExtension = typeof(ExtensionAttribute);
- if (member.IsDefined(dlrExtension, false)) {
- return true;
- }
-
-#if CLR2 && !SILVERLIGHT
- if (_ExtensionAttributeType == null) {
- try {
- _ExtensionAttributeType = Assembly.Load("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
- .GetType("System.Runtime.CompilerServices.ExtensionAttribute");
- } catch {
- _ExtensionAttributeType = dlrExtension;
- }
- }
-
- if (_ExtensionAttributeType != dlrExtension) {
- return member.IsDefined(_ExtensionAttributeType, false);
- }
-#endif
- return false;
- }
-
- public static bool IsOutParameter(this ParameterInfo pi) {
- // not using IsIn/IsOut properties as they are not available in Silverlight:
- return pi.ParameterType.IsByRef && (pi.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out;
- }
-
- /// <summary>
- /// Returns <c>true</c> if the specified parameter is mandatory, i.e. is not optional and doesn't have a default value.
- /// </summary>
- public static bool IsMandatory(this ParameterInfo pi) {
- return (pi.Attributes & ParameterAttributes.Optional) == 0 && !pi.HasDefaultValue();
- }
-
- public static bool HasDefaultValue(this ParameterInfo pi) {
-#if !FEATURE_DEFAULT_PARAMETER_VALUE
- return pi.IsDefined(typeof(DefaultParameterValueAttribute), false);
-#else
- return (pi.Attributes & ParameterAttributes.HasDefault) != 0;
-#endif
- }
-
- public static bool ProhibitsNull(this ParameterInfo parameter) {
- return parameter.IsDefined(typeof(NotNullAttribute), false);
- }
-
- public static bool ProhibitsNullItems(this ParameterInfo parameter) {
- return parameter.IsDefined(typeof(NotNullItemsAttribute), false);
- }
-
- public static bool IsParamArray(this ParameterInfo parameter) {
- return parameter.IsDefined(typeof(ParamArrayAttribute), false);
- }
-
- public static bool IsParamDictionary(this ParameterInfo parameter) {
- return parameter.IsDefined(typeof(ParamDictionaryAttribute), false);
- }
-
- public static bool IsParamsMethod(MethodBase method) {
- return IsParamsMethod(method.GetParameters());
- }
-
- public static bool IsParamsMethod(ParameterInfo[] pis) {
- foreach (ParameterInfo pi in pis) {
- if (pi.IsParamArray() || pi.IsParamDictionary()) return true;
- }
- return false;
- }
-
- public static object GetDefaultValue(this ParameterInfo info) {
-#if !FEATURE_DEFAULT_PARAMETER_VALUE
- if (info.IsOptional) {
- return info.ParameterType == typeof(object) ? Missing.Value : ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(info.ParameterType);
- }
-
- var defaultValueAttribute = info.GetCustomAttributes(typeof(DefaultParameterValueAttribute), false);
- if (defaultValueAttribute.Length > 0) {
- return ((DefaultParameterValueAttribute)defaultValueAttribute[0]).Value;
- }
-
- return null;
-#else
- return info.DefaultValue;
-#endif
- }
-
- #endregion
-
- #region Types
-
- /// <summary>
- /// Yields all ancestors of the given type including the type itself.
- /// Does not include implemented interfaces.
- /// </summary>
- public static IEnumerable<Type> Ancestors(this Type type) {
- do {
- yield return type;
- type = type.GetTypeInfo().BaseType;
- } while (type != null);
- }
-
- /// <summary>
- /// Like Type.GetInterfaces, but only returns the interfaces implemented by this type
- /// and not its parents.
- /// </summary>
- public static List<Type> GetDeclaredInterfaces(Type type) {
- IEnumerable<Type> baseInterfaces = (type.GetBaseType() != null) ? type.GetBaseType().GetInterfaces() : EmptyTypes;
- List<Type> interfaces = new List<Type>();
- foreach (Type iface in type.GetInterfaces()) {
- if (!baseInterfaces.Contains(iface)) {
- interfaces.Add(iface);
- }
- }
- return interfaces;
- }
-
- internal static IEnumerable<TypeInfo> GetAllTypesFromAssembly(Assembly asm) {
- // TODO: WP7, SL5
-#if SILVERLIGHT // ReflectionTypeLoadException
- try {
- return asm.GetTypes();
- } catch (Exception) {
- return ReflectionUtils.EmptyTypes;
- }
-#elif WIN8
- return asm.DefinedTypes;
-#else
- foreach (Module module in asm.GetModules()) {
- Type[] moduleTypes;
- try {
- moduleTypes = module.GetTypes();
- } catch (ReflectionTypeLoadException e) {
- moduleTypes = e.Types;
- }
-
- foreach (var type in moduleTypes) {
- if (type != null) {
- yield return type;
- }
- }
- }
-#endif
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
- internal static IEnumerable<TypeInfo> GetAllTypesFromAssembly(Assembly assembly, bool includePrivateTypes) {
- ContractUtils.RequiresNotNull(assembly, "assembly");
-
- if (includePrivateTypes) {
- return GetAllTypesFromAssembly(assembly);
- }
-
- try {
-#if WIN8
- return assembly.ExportedTypes.Select(t => t.GetTypeInfo());
-#else
- return assembly.GetExportedTypes();
-#endif
- } catch (NotSupportedException) {
- // GetExportedTypes does not work with dynamic assemblies
- } catch (Exception) {
- // Some type loads may cause exceptions. Unfortunately, there is no way to ask GetExportedTypes
- // for just the list of types that we successfully loaded.
- }
-
- return GetAllTypesFromAssembly(assembly).Where(type => type.IsPublic);
- }
-
- #endregion
-
- #region Type Builder
-#if FEATURE_REFEMIT
-
-#if WIN8 // TODO: what is ReservedMask?
- private const MethodAttributes MethodAttributesToEraseInOveride = MethodAttributes.Abstract | (MethodAttributes)0xD000;
-#else
- private const MethodAttributes MethodAttributesToEraseInOveride = MethodAttributes.Abstract | MethodAttributes.ReservedMask;
-#endif
-
- public static MethodBuilder DefineMethodOverride(TypeBuilder tb, MethodAttributes extra, MethodInfo decl) {
- MethodAttributes finalAttrs = (decl.Attributes & ~MethodAttributesToEraseInOveride) | extra;
- if (!decl.DeclaringType.GetTypeInfo().IsInterface) {
- finalAttrs &= ~MethodAttributes.NewSlot;
- }
-
- if ((extra & MethodAttributes.MemberAccessMask) != 0) {
- // remove existing member access, add new member access
- finalAttrs &= ~MethodAttributes.MemberAccessMask;
- finalAttrs |= extra;
- }
-
- MethodBuilder impl = tb.DefineMethod(decl.Name, finalAttrs, decl.CallingConvention);
- CopyMethodSignature(decl, impl, false);
- return impl;
- }
-
- public static void CopyMethodSignature(MethodInfo from, MethodBuilder to, bool substituteDeclaringType) {
- ParameterInfo[] paramInfos = from.GetParameters();
- Type[] parameterTypes = new Type[paramInfos.Length];
- Type[][] parameterRequiredModifiers = null, parameterOptionalModifiers = null;
- Type[] returnRequiredModifiers = null, returnOptionalModifiers = null;
-
-#if FEATURE_CUSTOM_MODIFIERS
- returnRequiredModifiers = from.ReturnParameter.GetRequiredCustomModifiers();
- returnOptionalModifiers = from.ReturnParameter.GetOptionalCustomModifiers();
-#endif
- for (int i = 0; i < paramInfos.Length; i++) {
- if (substituteDeclaringType && paramInfos[i].ParameterType == from.DeclaringType) {
- parameterTypes[i] = to.DeclaringType;
- } else {
- parameterTypes[i] = paramInfos[i].ParameterType;
- }
-
-#if FEATURE_CUSTOM_MODIFIERS
- var mods = paramInfos[i].GetRequiredCustomModifiers();
- if (mods.Length > 0) {
- if (parameterRequiredModifiers == null) {
- parameterRequiredModifiers = new Type[paramInfos.Length][];
- }
-
- parameterRequiredModifiers[i] = mods;
- }
-
- mods = paramInfos[i].GetOptionalCustomModifiers();
- if (mods.Length > 0) {
- if (parameterOptionalModifiers == null) {
- parameterOptionalModifiers = new Type[paramInfos.Length][];
- }
-
- parameterOptionalModifiers[i] = mods;
- }
-#endif
- }
-
- to.SetSignature(
- from.ReturnType, returnRequiredModifiers, returnOptionalModifiers,
- parameterTypes, parameterRequiredModifiers, parameterOptionalModifiers
- );
-
- CopyGenericMethodAttributes(from, to);
-
- for (int i = 0; i < paramInfos.Length; i++) {
- to.DefineParameter(i + 1, paramInfos[i].Attributes, paramInfos[i].Name);
- }
- }
-
- private static void CopyGenericMethodAttributes(MethodInfo from, MethodBuilder to) {
- if (from.IsGenericMethodDefinition) {
- Type[] args = from.GetGenericArguments();
- string[] names = new string[args.Length];
- for (int i = 0; i < args.Length; i++) {
- names[i] = args[i].Name;
- }
- var builders = to.DefineGenericParameters(names);
- for (int i = 0; i < args.Length; i++) {
- // Copy template parameter attributes
- builders[i].SetGenericParameterAttributes(args[i].GetGenericParameterAttributes());
-
- // Copy template parameter constraints
- Type[] constraints = args[i].GetGenericParameterConstraints();
- List<Type> interfaces = new List<Type>(constraints.Length);
- foreach (Type constraint in constraints) {
- if (constraint.IsInterface()) {
- interfaces.Add(constraint);
- } else {
- builders[i].SetBaseTypeConstraint(constraint);
- }
- }
- if (interfaces.Count > 0) {
- builders[i].SetInterfaceConstraints(interfaces.ToArray());
- }
- }
- }
- }
-#endif
- #endregion
-
- #region Extension Methods
-
- public static IEnumerable<MethodInfo> GetVisibleExtensionMethods(Assembly assembly) {
-#if FEATURE_METADATA_READER
- if (!assembly.IsDynamic && AppDomain.CurrentDomain.IsFullyTrusted) {
- try {
- return GetVisibleExtensionMethodsFast(assembly);
- } catch (SecurityException) {
- // full-demand can still fail if there is a partial trust domain on the stack
- }
- }
-#endif
- return GetVisibleExtensionMethodsSlow(assembly);
- }
-
-#if FEATURE_METADATA_READER
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2116:AptcaMethodsShouldOnlyCallAptcaMethods")]
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static IEnumerable<MethodInfo> GetVisibleExtensionMethodsFast(Assembly assembly) {
- // Security: link demand
- return MetadataServices.GetVisibleExtensionMethodInfos(assembly);
- }
-#endif
-
- // TODO: make internal
- // TODO: handle type load exceptions
- public static IEnumerable<MethodInfo> GetVisibleExtensionMethodsSlow(Assembly assembly) {
- var ea = typeof(ExtensionAttribute);
- if (assembly.IsDefined(ea)) {
- foreach (TypeInfo type in ReflectionUtils.GetAllTypesFromAssembly(assembly)) {
- if ((type.IsPublic || type.IsNestedPublic) &&
- type.IsAbstract &&
- type.IsSealed &&
- type.IsDefined(ea, false)) {
-
- foreach (MethodInfo method in type.AsType().GetDeclaredMethods()) {
- if (method.IsPublic && method.IsStatic && method.IsDefined(ea, false)) {
- yield return method;
- }
- }
- }
- }
- }
- }
-
- // Value is null if there are no extension methods in the assembly.
- private static Dictionary<Assembly, Dictionary<string, List<ExtensionMethodInfo>>> _extensionMethodsCache;
-
- /// <summary>
- /// Enumerates extension methods in given assembly. Groups the methods by declaring namespace.
- /// Uses a global cache if <paramref name="useCache"/> is true.
- /// </summary>
- public static IEnumerable<KeyValuePair<string, IEnumerable<ExtensionMethodInfo>>> GetVisibleExtensionMethodGroups(Assembly/*!*/ assembly, bool useCache) {
-#if !CLR2 && FEATURE_REFEMIT
- useCache &= !assembly.IsDynamic;
-#endif
- if (useCache) {
- if (_extensionMethodsCache == null) {
- _extensionMethodsCache = new Dictionary<Assembly, Dictionary<string, List<ExtensionMethodInfo>>>();
- }
-
- lock (_extensionMethodsCache) {
- Dictionary<string, List<ExtensionMethodInfo>> existing;
- if (_extensionMethodsCache.TryGetValue(assembly, out existing)) {
- return EnumerateExtensionMethods(existing);
- }
- }
- }
-
- Dictionary<string, List<ExtensionMethodInfo>> result = null;
- foreach (MethodInfo method in ReflectionUtils.GetVisibleExtensionMethodsSlow(assembly)) {
- if (method.DeclaringType == null || method.DeclaringType.IsGenericTypeDefinition()) {
- continue;
- }
-
- var parameters = method.GetParameters();
- if (parameters.Length == 0) {
- continue;
- }
-
- Type type = parameters[0].ParameterType;
- if (type.IsByRef || type.IsPointer) {
- continue;
- }
-
- string ns = method.DeclaringType.Namespace ?? String.Empty;
- List<ExtensionMethodInfo> extensions = null;
-
- if (result == null) {
- result = new Dictionary<string, List<ExtensionMethodInfo>>();
- }
-
- if (!result.TryGetValue(ns, out extensions)) {
- result.Add(ns, extensions = new List<ExtensionMethodInfo>());
- }
-
- extensions.Add(new ExtensionMethodInfo(type, method));
- }
-
- if (useCache) {
- lock (_extensionMethodsCache) {
- _extensionMethodsCache[assembly] = result;
- }
- }
-
- return EnumerateExtensionMethods(result);
- }
-
- // TODO: GetVisibleExtensionMethods(Hashset<string> namespaces, Type type, string methodName) : IEnumerable<MethodInfo> {}
-
- private static IEnumerable<KeyValuePair<string, IEnumerable<ExtensionMethodInfo>>> EnumerateExtensionMethods(Dictionary<string, List<ExtensionMethodInfo>> dict) {
- if (dict != null) {
- foreach (var entry in dict) {
- yield return new KeyValuePair<string, IEnumerable<ExtensionMethodInfo>>(entry.Key, new ReadOnlyCollection<ExtensionMethodInfo>(entry.Value));
- }
- }
- }
-
- #endregion
-
- #region Generic Types
-
- internal static Dictionary<Type, Type> BindGenericParameters(Type/*!*/ openType, Type/*!*/ closedType, bool ignoreUnboundParameters) {
- var binding = new Dictionary<Type, Type>();
- BindGenericParameters(openType, closedType, (parameter, type) => {
- Type existing;
- if (binding.TryGetValue(parameter, out existing)) {
- return type == existing;
- }
-
- binding[parameter] = type;
-
- return true;
- });
-
- return ConstraintsViolated(binding, ignoreUnboundParameters) ? null : binding;
- }
-
- /// <summary>
- /// Binds occurances of generic parameters in <paramref name="openType"/> against corresponding types in <paramref name="closedType"/>.
- /// Invokes <paramref name="binder"/>(parameter, type) for each such binding.
- /// Returns false if the <paramref name="openType"/> is structurally different from <paramref name="closedType"/> or if the binder returns false.
- /// </summary>
- internal static bool BindGenericParameters(Type/*!*/ openType, Type/*!*/ closedType, Func<Type, Type, bool>/*!*/ binder) {
- if (openType.IsGenericParameter) {
- return binder(openType, closedType);
- }
-
- if (openType.IsArray) {
- if (!closedType.IsArray) {
- return false;
- }
- return BindGenericParameters(openType.GetElementType(), closedType.GetElementType(), binder);
- }
-
- if (!openType.IsGenericType() || !closedType.IsGenericType()) {
- return openType == closedType;
- }
-
- if (openType.GetGenericTypeDefinition() != closedType.GetGenericTypeDefinition()) {
- return false;
- }
-
- Type[] closedArgs = closedType.GetGenericArguments();
- Type[] openArgs = openType.GetGenericArguments();
-
- for (int i = 0; i < openArgs.Length; i++) {
- if (!BindGenericParameters(openArgs[i], closedArgs[i], binder)) {
- return false;
- }
- }
-
- return true;
- }
-
- internal static bool ConstraintsViolated(Dictionary<Type, Type>/*!*/ binding, bool ignoreUnboundParameters) {
- foreach (var entry in binding) {
- if (ConstraintsViolated(entry.Key, entry.Value, binding, ignoreUnboundParameters)) {
- return true;
- }
- }
-
- return false;
- }
-
- internal static bool ConstraintsViolated(Type/*!*/ genericParameter, Type/*!*/ closedType, Dictionary<Type, Type>/*!*/ binding, bool ignoreUnboundParameters) {
- if ((genericParameter.GetGenericParameterAttributes() & GenericParameterAttributes.ReferenceTypeConstraint) != 0 && closedType.IsValueType()) {
- // value type to parameter type constrained as class
- return true;
- }
-
- if ((genericParameter.GetGenericParameterAttributes() & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0 &&
- (!closedType.IsValueType() || (closedType.IsGenericType() && closedType.GetGenericTypeDefinition() == typeof(Nullable<>)))) {
- // nullable<T> or class/interface to parameter type constrained as struct
- return true;
- }
-
- if ((genericParameter.GetGenericParameterAttributes() & GenericParameterAttributes.DefaultConstructorConstraint) != 0 &&
- (!closedType.IsValueType() && closedType.GetConstructor(ReflectionUtils.EmptyTypes) == null)) {
- // reference type w/o a default constructor to type constrianed as new()
- return true;
- }
-
- Type[] constraints = genericParameter.GetGenericParameterConstraints();
- for (int i = 0; i < constraints.Length; i++) {
- Type instantiation = InstantiateConstraint(constraints[i], binding);
-
- if (instantiation == null) {
- if (ignoreUnboundParameters) {
- continue;
- } else {
- return true;
- }
- }
-
- if (!instantiation.IsAssignableFrom(closedType)) {
- return true;
- }
- }
-
- return false;
- }
-
- internal static Type InstantiateConstraint(Type/*!*/ constraint, Dictionary<Type, Type>/*!*/ binding) {
- Debug.Assert(!constraint.IsArray && !constraint.IsByRef && !constraint.IsGenericTypeDefinition());
- if (!constraint.ContainsGenericParameters()) {
- return constraint;
- }
-
- Type closedType;
- if (constraint.IsGenericParameter) {
- return binding.TryGetValue(constraint, out closedType) ? closedType : null;
- }
-
- Type[] args = constraint.GetGenericArguments();
- for (int i = 0; i < args.Length; i++) {
- if ((args[i] = InstantiateConstraint(args[i], binding)) == null) {
- return null;
- }
- }
-
- return constraint.GetGenericTypeDefinition().MakeGenericType(args);
- }
-
- #endregion
- }
-
- public struct ExtensionMethodInfo : IEquatable<ExtensionMethodInfo> {
- private readonly Type/*!*/ _extendedType; // cached type of the first parameter
- private readonly MethodInfo/*!*/ _method;
-
- internal ExtensionMethodInfo(Type/*!*/ extendedType, MethodInfo/*!*/ method) {
- Assert.NotNull(extendedType, method);
- _extendedType = extendedType;
- _method = method;
- }
-
- public Type/*!*/ ExtendedType {
- get { return _extendedType; }
- }
-
- public MethodInfo/*!*/ Method {
- get { return _method; }
- }
-
- public override bool Equals(object obj) {
- return obj is ExtensionMethodInfo && Equals((ExtensionMethodInfo)obj);
- }
-
- public bool Equals(ExtensionMethodInfo other) {
- return _method.Equals(other._method);
- }
-
- public static bool operator ==(ExtensionMethodInfo self, ExtensionMethodInfo other) {
- return self.Equals(other);
- }
-
- public static bool operator !=(ExtensionMethodInfo self, ExtensionMethodInfo other) {
- return !self.Equals(other);
- }
-
- public override int GetHashCode() {
- return _method.GetHashCode();
- }
-
- /// <summary>
- /// Determines if a given type matches the type that the method extends.
- /// The match might be non-trivial if the extended type is an open generic type with constraints.
- /// </summary>
- public bool IsExtensionOf(Type/*!*/ type) {
- ContractUtils.RequiresNotNull(type, "type");
-#if FEATURE_TYPE_EQUIVALENCE
- if (type.IsEquivalentTo(ExtendedType)) {
- return true;
- }
-#else
- if (type == _extendedType) {
- return true;
- }
-#endif
- if (!_extendedType.GetTypeInfo().ContainsGenericParameters) {
- return false;
- }
-
- //
- // Ignores constraints that can't be instantiated given the information we have (type of the first parameter).
- //
- // For example,
- // void Foo<S, T>(this S x, T y) where S : T;
- //
- // We make such methods available on all types.
- // If they are not called with arguments that satisfy the constraint the overload resolver might fail.
- //
- return ReflectionUtils.BindGenericParameters(_extendedType, type, true) != null;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/StringUtils.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/StringUtils.cs
deleted file mode 100644
index 934021ff69b..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/StringUtils.cs
+++ /dev/null
@@ -1,269 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Text;
-
-namespace Microsoft.Scripting.Utils {
- public static class StringUtils {
-
- public static Encoding DefaultEncoding {
- get {
-#if FEATURE_ENCODING
- return Encoding.Default;
-#else
- return Encoding.UTF8;
-#endif
- }
- }
-
- public static string GetSuffix(string str, char separator, bool includeSeparator) {
- ContractUtils.RequiresNotNull(str, "str");
- int last = str.LastIndexOf(separator);
- return (last != -1) ? str.Substring(includeSeparator ? last : last + 1) : null;
- }
-
- public static string GetLongestPrefix(string str, char separator, bool includeSeparator) {
- ContractUtils.RequiresNotNull(str, "str");
- int last = str.LastIndexOf(separator);
- return (last != -1) ? str.Substring(0, (includeSeparator || last == 0) ? last : last - 1) : null;
- }
-
- public static int CountOf(string str, char c) {
- if (System.String.IsNullOrEmpty(str)) return 0;
-
- int result = 0;
- for (int i = 0; i < str.Length; i++) {
- if (c == str[i]) {
- result++;
- }
- }
- return result;
- }
-
- public static string[] Split(string str, string separator, int maxComponents, StringSplitOptions options) {
- ContractUtils.RequiresNotNull(str, "str");
-#if SILVERLIGHT || WP75
- if (string.IsNullOrEmpty(separator)) throw new ArgumentNullException("separator");
-
- bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;
-
- List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);
-
- int i = 0;
- int next;
- while (maxComponents > 1 && i < str.Length && (next = str.IndexOf(separator, i)) != -1) {
-
- if (next > i || keep_empty) {
- result.Add(str.Substring(i, next - i));
- maxComponents--;
- }
-
- i = next + separator.Length;
- }
-
- if (i < str.Length || keep_empty) {
- result.Add(str.Substring(i));
- }
-
- return result.ToArray();
-#else
- return str.Split(new string[] { separator }, maxComponents, options);
-#endif
- }
-
- public static string[] Split(string str, char[] separators, int maxComponents, StringSplitOptions options) {
- ContractUtils.RequiresNotNull(str, "str");
-#if SILVERLIGHT || WP75
- if (separators == null) return SplitOnWhiteSpace(str, maxComponents, options);
-
- bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;
-
- List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);
-
- int i = 0;
- int next;
- while (maxComponents > 1 && i < str.Length && (next = str.IndexOfAny(separators, i)) != -1) {
-
- if (next > i || keep_empty) {
- result.Add(str.Substring(i, next - i));
- maxComponents--;
- }
-
- i = next + 1;
- }
-
- if (i < str.Length || keep_empty) {
- result.Add(str.Substring(i));
- }
-
- return result.ToArray();
-#else
- return str.Split(separators, maxComponents, options);
-#endif
- }
-
-#if SILVERLIGHT|| WP75
- public static string[] SplitOnWhiteSpace(string str, int maxComponents, StringSplitOptions options) {
- ContractUtils.RequiresNotNull(str, "str");
-
- bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;
-
- List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);
-
- int i = 0;
- int next;
- while (maxComponents > 1 && i < str.Length && (next = IndexOfWhiteSpace(str, i)) != -1) {
-
- if (next > i || keep_empty) {
- result.Add(str.Substring(i, next - i));
- maxComponents--;
- }
-
- i = next + 1;
- }
-
- if (i < str.Length || keep_empty) {
- result.Add(str.Substring(i));
- }
-
- return result.ToArray();
- }
-
- public static int IndexOfWhiteSpace(string str, int start) {
- ContractUtils.RequiresNotNull(str, "str");
- if (start < 0 || start > str.Length) throw new ArgumentOutOfRangeException("start");
-
- while (start < str.Length && !Char.IsWhiteSpace(str[start])) start++;
-
- return (start == str.Length) ? -1 : start;
- }
-#endif
-
- /// <summary>
- /// Splits text and optionally indents first lines - breaks along words, not characters.
- /// </summary>
- public static string SplitWords(string text, bool indentFirst, int lineWidth) {
- ContractUtils.RequiresNotNull(text, "text");
-
- const string indent = " ";
-
- if (text.Length <= lineWidth || lineWidth <= 0) {
- if (indentFirst) return indent + text;
- return text;
- }
-
- StringBuilder res = new StringBuilder();
- int start = 0, len = lineWidth;
- while (start != text.Length) {
- if (len >= lineWidth) {
- // find last space to break on
- while (len != 0 && !Char.IsWhiteSpace(text[start + len - 1]))
- len--;
- }
-
- if (res.Length != 0) res.Append(' ');
- if (indentFirst || res.Length != 0) res.Append(indent);
-
- if (len == 0) {
- int copying = System.Math.Min(lineWidth, text.Length - start);
- res.Append(text, start, copying);
- start += copying;
- } else {
- res.Append(text, start, len);
- start += len;
- }
- res.AppendLine();
- len = System.Math.Min(lineWidth, text.Length - start);
- }
- return res.ToString();
- }
-
- public static string AddSlashes(string str) {
- ContractUtils.RequiresNotNull(str, "str");
-
- // TODO: optimize
- StringBuilder result = new StringBuilder(str.Length);
- for (int i = 0; i < str.Length; i++) {
- switch (str[i]) {
- case '\a': result.Append("\\a"); break;
- case '\b': result.Append("\\b"); break;
- case '\f': result.Append("\\f"); break;
- case '\n': result.Append("\\n"); break;
- case '\r': result.Append("\\r"); break;
- case '\t': result.Append("\\t"); break;
- case '\v': result.Append("\\v"); break;
- default: result.Append(str[i]); break;
- }
- }
-
- return result.ToString();
- }
-
- public static bool TryParseDouble(string s, NumberStyles style, IFormatProvider provider, out double result) {
- return Double.TryParse(s, style, provider, out result);
- }
-
- public static bool TryParseInt32(string s, out int result) {
- return Int32.TryParse(s, out result);
- }
-
- public static bool TryParseDateTimeExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result) {
- return DateTime.TryParseExact(s, format, provider, style, out result);
- }
-
- public static bool TryParseDateTimeExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style, out DateTime result) {
- return DateTime.TryParseExact(s, formats, provider, style, out result);
- }
-
- public static bool TryParseDate(string s, IFormatProvider provider, DateTimeStyles style, out DateTime result) {
- return DateTime.TryParse(s, provider, style, out result);
- }
-
-#if !WIN8
-#if SILVERLIGHT || WP75
- private static Dictionary<string, CultureInfo> _cultureInfoCache = new Dictionary<string, CultureInfo>();
-#endif
-
- // Aims to be equivalent to Culture.GetCultureInfo for Silverlight
- public static CultureInfo GetCultureInfo(string name) {
-#if SILVERLIGHT || WP75
- lock (_cultureInfoCache) {
- CultureInfo result;
- if (_cultureInfoCache.TryGetValue(name, out result)) {
- return result;
- }
- _cultureInfoCache[name] = result = new CultureInfo(name);
- return result;
- }
-#else
- return CultureInfo.GetCultureInfo(name);
-#endif
- }
-#endif
- // Like string.Split, but enumerates
- public static IEnumerable<string> Split(string str, string sep) {
- int start = 0, end;
- while ((end = str.IndexOf(sep, start)) != -1) {
- yield return str.Substring(start, end - start);
-
- start = end + sep.Length;
- }
- yield return str.Substring(start);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/TypeUtils.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/TypeUtils.cs
deleted file mode 100644
index c20371d0f0e..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/TypeUtils.cs
+++ /dev/null
@@ -1,375 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Reflection;
-using System.Dynamic;
-using Microsoft.Scripting.Generation;
-using Microsoft.Scripting.Runtime;
-
-namespace Microsoft.Scripting.Utils {
- public static class TypeUtils {
- public static bool IsNested(this Type t) {
- return t.DeclaringType != null;
- }
-
- // keep in sync with System.Core version
- internal static Type GetNonNullableType(Type type) {
- if (IsNullableType(type)) {
- return type.GetGenericArguments()[0];
- }
- return type;
- }
-
- // keep in sync with System.Core version
- internal static bool IsNullableType(Type type) {
- return type.IsGenericType() && type.GetGenericTypeDefinition() == typeof(Nullable<>);
- }
-
- // keep in sync with System.Core version
- internal static bool IsBool(Type type) {
- return GetNonNullableType(type) == typeof(bool);
- }
-
- // keep in sync with System.Core version
- internal static bool IsNumeric(Type type) {
- type = GetNonNullableType(type);
- if (!type.IsEnum()) {
- return IsNumeric(type.GetTypeCode());
- }
- return false;
- }
-
- internal static bool IsNumeric(TypeCode typeCode) {
- switch (typeCode) {
- case TypeCode.Char:
- case TypeCode.SByte:
- case TypeCode.Byte:
- case TypeCode.Int16:
- case TypeCode.Int32:
- case TypeCode.Int64:
- case TypeCode.Double:
- case TypeCode.Single:
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- return true;
- }
- return false;
- }
-
- // keep in sync with System.Core version
- internal static bool IsArithmetic(Type type) {
- type = GetNonNullableType(type);
- if (!type.IsEnum()) {
- switch (type.GetTypeCode()) {
- case TypeCode.Int16:
- case TypeCode.Int32:
- case TypeCode.Int64:
- case TypeCode.Double:
- case TypeCode.Single:
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- return true;
- }
- }
- return false;
- }
-
- // keep in sync with System.Core version
- internal static bool IsUnsignedInt(Type type) {
- type = GetNonNullableType(type);
- if (!type.IsEnum()) {
- switch (type.GetTypeCode()) {
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- return true;
- }
- }
- return false;
- }
-
- // keep in sync with System.Core version
- internal static bool IsIntegerOrBool(Type type) {
- type = GetNonNullableType(type);
- if (!type.IsEnum()) {
- switch (type.GetTypeCode()) {
- case TypeCode.Int64:
- case TypeCode.Int32:
- case TypeCode.Int16:
- case TypeCode.UInt64:
- case TypeCode.UInt32:
- case TypeCode.UInt16:
- case TypeCode.Boolean:
- case TypeCode.SByte:
- case TypeCode.Byte:
- return true;
- }
- }
- return false;
- }
-
- internal static bool CanAssign(Type to, Expression from) {
- if (CanAssign(to, from.Type)) return true;
-
- if (to.IsValueType() &&
- to.IsGenericType() &&
- to.GetGenericTypeDefinition() == typeof(Nullable<>) &&
- ConstantCheck.Check(from, null)) {
- return true;
- }
-
- return false;
- }
-
- internal static bool CanAssign(Type to, Type from) {
- if (to == from) {
- return true;
- }
- // Reference types
- if (!to.IsValueType() && !from.IsValueType()) {
- if (to.IsAssignableFrom(from)) {
- return true;
- }
- // Arrays can be assigned if they have same rank and assignable element types.
- if (to.IsArray && from.IsArray &&
- to.GetArrayRank() == from.GetArrayRank() &&
- CanAssign(to.GetElementType(), from.GetElementType())) {
- return true;
- }
- }
-
- return false;
- }
-
- internal static bool IsGeneric(Type type) {
- return type.ContainsGenericParameters() || type.IsGenericTypeDefinition();
- }
-
- internal static bool CanCompareToNull(Type type) {
- // This is a bit too conservative.
- return !type.IsValueType();
- }
-
- /// <summary>
- /// Returns a numerical code of the size of a type. All types get both a horizontal
- /// and vertical code. Types that are lower in both dimensions have implicit conversions
- /// to types that are higher in both dimensions.
- /// </summary>
- internal static bool GetNumericConversionOrder(TypeCode code, out int x, out int y) {
- // implicit conversions:
- // 0 1 2 3 4
- // 0: U1 -> U2 -> U4 -> U8
- // | | |
- // v v v
- // 1: I1 -> I2 -> I4 -> I8
- // | |
- // v v
- // 2: R4 -> R8
-
- switch (code) {
- case TypeCode.Byte: x = 0; y = 0; break;
- case TypeCode.UInt16: x = 1; y = 0; break;
- case TypeCode.UInt32: x = 2; y = 0; break;
- case TypeCode.UInt64: x = 3; y = 0; break;
-
- case TypeCode.SByte: x = 0; y = 1; break;
- case TypeCode.Int16: x = 1; y = 1; break;
- case TypeCode.Int32: x = 2; y = 1; break;
- case TypeCode.Int64: x = 3; y = 1; break;
-
- case TypeCode.Single: x = 1; y = 2; break;
- case TypeCode.Double: x = 2; y = 2; break;
-
- default:
- x = y = 0;
- return false;
- }
- return true;
- }
-
- internal static bool IsImplicitlyConvertible(int fromX, int fromY, int toX, int toY) {
- return fromX <= toX && fromY <= toY;
- }
-
- internal static bool HasBuiltinEquality(Type left, Type right) {
- // Reference type can be compared to interfaces
- if (left.IsInterface() && !right.IsValueType() ||
- right.IsInterface() && !left.IsValueType()) {
- return true;
- }
-
- // Reference types compare if they are assignable
- if (!left.IsValueType() && !right.IsValueType()) {
- if (CanAssign(left, right) || CanAssign(right, left)) {
- return true;
- }
- }
-
- // Nullable<T> vs null
- if (NullVsNullable(left, right) || NullVsNullable(right, left)) {
- return true;
- }
-
- if (left != right) {
- return false;
- }
-
- if (left == typeof(bool) || IsNumeric(left) || left.IsEnum()) {
- return true;
- }
-
- return false;
- }
-
- private static bool NullVsNullable(Type left, Type right) {
- return IsNullableType(left) && right == typeof(DynamicNull);
- }
-
- // keep in sync with System.Core version
- internal static bool AreEquivalent(Type t1, Type t2) {
-#if FEATURE_TYPE_EQUIVALENCE
- return t1 == t2 || t1.IsEquivalentTo(t2);
-#else
- return t1 == t2;
-#endif
- }
-
- // keep in sync with System.Core version
- internal static bool AreReferenceAssignable(Type dest, Type src) {
- // WARNING: This actually implements "Is this identity assignable and/or reference assignable?"
- if (dest == src) {
- return true;
- }
- if (!dest.IsValueType() && !src.IsValueType() && AreAssignable(dest, src)) {
- return true;
- }
- return false;
- }
-
- // keep in sync with System.Core version
- internal static bool AreAssignable(Type dest, Type src) {
- if (dest == src) {
- return true;
- }
- if (dest.IsAssignableFrom(src)) {
- return true;
- }
- if (dest.IsArray && src.IsArray && dest.GetArrayRank() == src.GetArrayRank() && AreReferenceAssignable(dest.GetElementType(), src.GetElementType())) {
- return true;
- }
- if (src.IsArray && dest.IsGenericType() &&
- (dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IEnumerable<>)
- || dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IList<>)
- || dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.ICollection<>))
- && dest.GetGenericArguments()[0] == src.GetElementType()) {
- return true;
- }
- return false;
- }
-
- // keep in sync with System.Core version
- internal static Type GetConstantType(Type type) {
- // If it's a visible type, we're done
- if (type.IsVisible()) {
- return type;
- }
-
- // Get the visible base type
- Type bt = type;
- do {
- bt = bt.GetBaseType();
- } while (!bt.IsVisible());
-
- // If it's one of the known reflection types,
- // return the known type.
- if (bt == typeof(Type) ||
- bt == typeof(ConstructorInfo) ||
- bt == typeof(EventInfo) ||
- bt == typeof(FieldInfo) ||
- bt == typeof(MethodInfo) ||
- bt == typeof(PropertyInfo)) {
- return bt;
- }
-
- // else return the original type
- return type;
- }
-
- internal static bool IsConvertible(Type type) {
- type = GetNonNullableType(type);
- if (type.IsEnum()) {
- return true;
- }
- switch (type.GetTypeCode()) {
- case TypeCode.Boolean:
- case TypeCode.Byte:
- case TypeCode.SByte:
- case TypeCode.Int16:
- case TypeCode.Int32:
- case TypeCode.Int64:
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- case TypeCode.Single:
- case TypeCode.Double:
- case TypeCode.Char:
- return true;
- default:
- return false;
- }
- }
-
- internal static bool IsFloatingPoint(Type type) {
- type = GetNonNullableType(type);
- switch (type.GetTypeCode()) {
- case TypeCode.Single:
- case TypeCode.Double:
- return true;
- default:
- return false;
- }
- }
-
-#if FEATURE_COM
- public static readonly Type ComObjectType = typeof(object).Assembly.GetType("System.__ComObject");
-
- public static bool IsComObjectType(Type/*!*/ type) {
- return ComObjectType.IsAssignableFrom(type);
- }
-
- // we can't use System.Runtime.InteropServices.Marshal.IsComObject(obj) since it doesn't work in partial trust
- public static bool IsComObject(object obj) {
- return obj != null && IsComObjectType(obj.GetType());
- }
-#else
- public static bool IsComObjectType(Type/*!*/ type) {
- return false;
- }
-
- public static bool IsComObject(object obj) {
- return false;
- }
-#endif
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/BinaryOperationBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/BinaryOperationBinder.cs
deleted file mode 100644
index 9260938dfa1..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/BinaryOperationBinder.cs
+++ /dev/null
@@ -1,148 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-#else
-using System.Linq.Expressions;
-#endif
-
-using System.Dynamic.Utils;
-
-namespace System.Dynamic {
- /// <summary>
- /// Represents the binary dynamic operation at the call site, providing the binding semantic and the details about the operation.
- /// </summary>
- public abstract class BinaryOperationBinder : DynamicMetaObjectBinder {
- private ExpressionType _operation;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="BinaryOperationBinder"/> class.
- /// </summary>
- /// <param name="operation">The binary operation kind.</param>
- protected BinaryOperationBinder(ExpressionType operation) {
- ContractUtils.Requires(OperationIsValid(operation), "operation");
- _operation = operation;
- }
-
- /// <summary>
- /// The result type of the operation.
- /// </summary>
- public override sealed Type ReturnType {
- get { return typeof(object); }
- }
-
- /// <summary>
- /// The binary operation kind.
- /// </summary>
- public ExpressionType Operation {
- get {
- return _operation;
- }
- }
-
- /// <summary>
- /// Performs the binding of the binary dynamic operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic binary operation.</param>
- /// <param name="arg">The right hand side operand of the dynamic binary operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject target, DynamicMetaObject arg) {
- return FallbackBinaryOperation(target, arg, null);
- }
-
- /// <summary>
- /// When overridden in the derived class, performs the binding of the binary dynamic operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic binary operation.</param>
- /// <param name="arg">The right hand side operand of the dynamic binary operation.</param>
- /// <param name="errorSuggestion">The binding result in case the binding fails, or null.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public abstract DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion);
-
- /// <summary>
- /// Performs the binding of the dynamic binary operation.
- /// </summary>
- /// <param name="target">The target of the dynamic operation.</param>
- /// <param name="args">An array of arguments of the dynamic operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(target, "target");
- ContractUtils.RequiresNotNull(args, "args");
- ContractUtils.Requires(args.Length == 1, "args");
-
- var arg0 = args[0];
- ContractUtils.RequiresNotNull(arg0, "args");
-
- return target.BindBinaryOperation(this, arg0);
- }
-
- // this is a standard DynamicMetaObjectBinder
- internal override sealed bool IsStandardBinder {
- get {
- return true;
- }
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- internal static bool OperationIsValid(ExpressionType operation) {
- switch (operation) {
- #region Generated Binary Operation Binder Validator
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_binop_validator from: generate_tree.py
-
- case ExpressionType.Add:
- case ExpressionType.And:
- 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.NotEqual:
- case ExpressionType.Or:
- case ExpressionType.Power:
- case ExpressionType.RightShift:
- case ExpressionType.Subtract:
- case ExpressionType.AddAssign:
- case ExpressionType.AndAssign:
- case ExpressionType.DivideAssign:
- case ExpressionType.ExclusiveOrAssign:
- case ExpressionType.LeftShiftAssign:
- case ExpressionType.ModuloAssign:
- case ExpressionType.MultiplyAssign:
- case ExpressionType.OrAssign:
- case ExpressionType.PowerAssign:
- case ExpressionType.RightShiftAssign:
- case ExpressionType.SubtractAssign:
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- case ExpressionType.Extension:
- return true;
-
- default:
- return false;
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/BindingRestrictions.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/BindingRestrictions.cs
deleted file mode 100644
index bf395abba53..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/BindingRestrictions.cs
+++ /dev/null
@@ -1,366 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-#else
-using System.Linq.Expressions;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Runtime.CompilerServices;
-
-namespace System.Dynamic {
-
- /// <summary>
- /// Represents a set of binding restrictions on the <see cref="DynamicMetaObject"/>under which the dynamic binding is valid.
- /// </summary>
- [DebuggerTypeProxy(typeof(BindingRestrictionsProxy)), DebuggerDisplay("{DebugView}")]
- public abstract class BindingRestrictions {
- /// <summary>
- /// Represents an empty set of binding restrictions. This field is read only.
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
- public static readonly BindingRestrictions Empty = new CustomRestriction(Expression.Constant(true));
-
- private const int TypeRestrictionHash = 0x10000000;
- private const int InstanceRestrictionHash = 0x20000000;
- private const int CustomRestrictionHash = 0x40000000;
-
- private BindingRestrictions() {
- }
-
- // Overridden by specialized subclasses
- internal abstract Expression GetExpression();
-
- /// <summary>
- /// Merges the set of binding restrictions with the current binding restrictions.
- /// </summary>
- /// <param name="restrictions">The set of restrictions with which to merge the current binding restrictions.</param>
- /// <returns>The new set of binding restrictions.</returns>
- public BindingRestrictions Merge(BindingRestrictions restrictions) {
- ContractUtils.RequiresNotNull(restrictions, "restrictions");
- if (this == Empty) {
- return restrictions;
- }
- if (restrictions == Empty) {
- return this;
- }
- return new MergedRestriction(this, restrictions);
- }
-
- /// <summary>
- /// Creates the binding restriction that check the expression for runtime type identity.
- /// </summary>
- /// <param name="expression">The expression to test.</param>
- /// <param name="type">The exact type to test.</param>
- /// <returns>The new binding restrictions.</returns>
- public static BindingRestrictions GetTypeRestriction(Expression expression, Type type) {
- ContractUtils.RequiresNotNull(expression, "expression");
- ContractUtils.RequiresNotNull(type, "type");
-
- return new TypeRestriction(expression, type);
- }
-
- /// <summary>
- /// The method takes a DynamicMetaObject, and returns an instance restriction for testing null if the object
- /// holds a null value, otherwise returns a type restriction.
- /// </summary>
- internal static BindingRestrictions GetTypeRestriction(DynamicMetaObject obj) {
- if (obj.Value == null && obj.HasValue) {
- return BindingRestrictions.GetInstanceRestriction(obj.Expression, null);
- } else {
- return BindingRestrictions.GetTypeRestriction(obj.Expression, obj.LimitType);
- }
- }
-
- /// <summary>
- /// Creates the binding restriction that checks the expression for object instance identity.
- /// </summary>
- /// <param name="expression">The expression to test.</param>
- /// <param name="instance">The exact object instance to test.</param>
- /// <returns>The new binding restrictions.</returns>
- public static BindingRestrictions GetInstanceRestriction(Expression expression, object instance) {
- ContractUtils.RequiresNotNull(expression, "expression");
-
- return new InstanceRestriction(expression, instance);
- }
-
- /// <summary>
- /// Creates the binding restriction that checks the expression for arbitrary immutable properties.
- /// </summary>
- /// <param name="expression">The expression expression the restrictions.</param>
- /// <returns>The new binding restrictions.</returns>
- /// <remarks>
- /// By convention, the general restrictions created by this method must only test
- /// immutable object properties.
- /// </remarks>
- public static BindingRestrictions GetExpressionRestriction(Expression expression) {
- ContractUtils.RequiresNotNull(expression, "expression");
- ContractUtils.Requires(expression.Type == typeof(bool), "expression");
- return new CustomRestriction(expression);
- }
-
- /// <summary>
- /// Combines binding restrictions from the list of <see cref="DynamicMetaObject"/> instances into one set of restrictions.
- /// </summary>
- /// <param name="contributingObjects">The list of <see cref="DynamicMetaObject"/> instances from which to combine restrictions.</param>
- /// <returns>The new set of binding restrictions.</returns>
- public static BindingRestrictions Combine(IList<DynamicMetaObject> contributingObjects) {
- BindingRestrictions res = BindingRestrictions.Empty;
- if (contributingObjects != null) {
- foreach (DynamicMetaObject mo in contributingObjects) {
- if (mo != null) {
- res = res.Merge(mo.Restrictions);
- }
- }
- }
- return res;
- }
-
- /// <summary>
- /// Builds a balanced tree of AndAlso nodes.
- /// We do this so the compiler won't stack overflow if we have many
- /// restrictions.
- /// </summary>
- private sealed class TestBuilder {
- private readonly Set<BindingRestrictions> _unique = new Set<BindingRestrictions>();
- private readonly Stack<AndNode> _tests = new Stack<AndNode>();
-
- private struct AndNode {
- internal int Depth;
- internal Expression Node;
- }
-
- internal void Append(BindingRestrictions restrictions) {
- if (_unique.Contains(restrictions)) {
- return;
- }
- _unique.Add(restrictions);
-
- Push(restrictions.GetExpression(), 0);
- }
-
- internal Expression ToExpression() {
- Expression result = _tests.Pop().Node;
- while (_tests.Count > 0) {
- result = Expression.AndAlso(_tests.Pop().Node, result);
- }
- return result;
- }
-
- private void Push(Expression node, int depth) {
- while (_tests.Count > 0 && _tests.Peek().Depth == depth) {
- node = Expression.AndAlso(_tests.Pop().Node, node);
- depth++;
- }
- _tests.Push(new AndNode { Node = node, Depth = depth });
- }
- }
-
- /// <summary>
- /// Creates the <see cref="Expression"/> representing the binding restrictions.
- /// </summary>
- /// <returns>The expression tree representing the restrictions.</returns>
- public Expression ToExpression() {
- // We could optimize this better, e.g. common subexpression elimination
- // But for now, it's good enough.
-
- if (this == Empty) {
- return Expression.Constant(true);
- }
-
- var testBuilder = new TestBuilder();
-
- // Visit the tree, left to right.
- // Use an explicit stack so we don't stack overflow.
- //
- // Left-most node is on top of the stack, so we always expand the
- // left most node each iteration.
- var stack = new Stack<BindingRestrictions>();
- stack.Push(this);
- do {
- var top = stack.Pop();
- var m = top as MergedRestriction;
- if (m != null) {
- stack.Push(m.Right);
- stack.Push(m.Left);
- } else {
- testBuilder.Append(top);
- }
- } while (stack.Count > 0);
-
- return testBuilder.ToExpression();
- }
-
- private sealed class MergedRestriction : BindingRestrictions {
- internal readonly BindingRestrictions Left;
- internal readonly BindingRestrictions Right;
-
- internal MergedRestriction(BindingRestrictions left, BindingRestrictions right) {
- Left = left;
- Right = right;
- }
- internal override Expression GetExpression() {
- throw ContractUtils.Unreachable;
- }
- }
-
- private sealed class CustomRestriction : BindingRestrictions {
- private readonly Expression _expression;
-
- internal CustomRestriction(Expression expression) {
- _expression = expression;
- }
-
- public override bool Equals(object obj) {
- var other = obj as CustomRestriction;
- return other != null && other._expression == _expression;
- }
-
- public override int GetHashCode() {
- return CustomRestrictionHash ^ _expression.GetHashCode();
- }
-
- internal override Expression GetExpression() {
- return _expression;
- }
- }
-
- private sealed class TypeRestriction : BindingRestrictions {
- private readonly Expression _expression;
- private readonly Type _type;
-
- internal TypeRestriction(Expression parameter, Type type) {
- _expression = parameter;
- _type = type;
- }
-
- public override bool Equals(object obj) {
- var other = obj as TypeRestriction;
- return other != null && TypeUtils.AreEquivalent(other._type, _type) && other._expression == _expression;
- }
-
- public override int GetHashCode() {
- return TypeRestrictionHash ^ _expression.GetHashCode() ^ _type.GetHashCode();
- }
-
- internal override Expression GetExpression() {
- return Expression.TypeEqual(_expression, _type);
- }
- }
-
- private sealed class InstanceRestriction : BindingRestrictions {
- private readonly Expression _expression;
- private readonly object _instance;
-
- internal InstanceRestriction(Expression parameter, object instance) {
- _expression = parameter;
- _instance = instance;
- }
-
- public override bool Equals(object obj) {
- var other = obj as InstanceRestriction;
- return other != null && other._instance == _instance && other._expression == _expression;
- }
-
- public override int GetHashCode() {
- return InstanceRestrictionHash ^ ReferenceEqualityComparer<object>.Instance.GetHashCode(_instance) ^ _expression.GetHashCode();
- }
-
- internal override Expression GetExpression() {
- if (_instance == null) {
- return Expression.Equal(
- Expression.Convert(_expression, typeof(object)),
- Expression.Constant(null)
- );
- }
-
- ParameterExpression temp = Expression.Parameter(typeof(object), null);
- return Expression.Block(
- new[] { temp },
- Expression.Assign(
- temp,
- Expression.Property(
- Expression.Constant(new WeakReference(_instance)),
- typeof(WeakReference).GetProperty("Target")
- )
- ),
- Expression.AndAlso(
- //check that WeekReference was not collected.
- Expression.NotEqual(temp, Expression.Constant(null)),
- Expression.Equal(
- Expression.Convert(_expression, typeof(object)),
- temp
- )
- )
- );
- }
- }
-
- private string DebugView {
- get { return ToExpression().ToString(); }
- }
-
- private sealed class BindingRestrictionsProxy {
- private readonly BindingRestrictions _node;
-
- public BindingRestrictionsProxy(BindingRestrictions node) {
- _node = node;
- }
-
- public bool IsEmpty {
- get { return _node == Empty; }
- }
-
- public Expression Test {
- get { return _node.ToExpression(); }
- }
-
- public BindingRestrictions[] Restrictions {
- get {
- var restrictions = new List<BindingRestrictions>();
-
- // Visit the tree, left to right
- //
- // Left-most node is on top of the stack, so we always expand the
- // left most node each iteration.
- var stack = new Stack<BindingRestrictions>();
- stack.Push(_node);
- do {
- var top = stack.Pop();
- var m = top as MergedRestriction;
- if (m != null) {
- stack.Push(m.Right);
- stack.Push(m.Left);
- } else {
- restrictions.Add(top);
- }
- } while (stack.Count > 0);
-
- return restrictions.ToArray();
- }
- }
-
- public override string ToString() {
- // To prevent fxcop warning about this field
- return _node.DebugView;
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallInfo.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallInfo.cs
deleted file mode 100644
index 27289d49252..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallInfo.cs
+++ /dev/null
@@ -1,109 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-#else
-using System.Linq.Expressions;
-#endif
-
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Dynamic.Utils;
-
-namespace System.Dynamic {
-
- /// <summary>
- /// Describes arguments in the dynamic binding process.
- /// </summary>
- /// <remarks>
- /// ArgumentCount - all inclusive number of arguments.
- /// ArgumentNames - names for those arguments that are named.
- ///
- /// Argument names match to the argument values in left to right order
- /// and last name corresponds to the last argument.
- ///
- /// Example:
- /// Foo(arg1, arg2, arg3, name1 = arg4, name2 = arg5, name3 = arg6)
- ///
- /// will correspond to:
- /// ArgumentCount: 6
- /// ArgumentNames: {"name1", "name2", "name3"}
- /// </remarks>
- public sealed class CallInfo {
- private readonly int _argCount;
- private readonly ReadOnlyCollection<string> _argNames;
-
- /// <summary>
- /// Creates a new PositionalArgumentInfo.
- /// </summary>
- /// <param name="argCount">The number of arguments.</param>
- /// <param name="argNames">The argument names.</param>
- /// <returns>The new CallInfo</returns>
- public CallInfo(int argCount, params string[] argNames)
- : this(argCount, (IEnumerable<string>)argNames) {
- }
-
- /// <summary>
- /// Creates a new CallInfo that represents arguments in the dynamic binding process.
- /// </summary>
- /// <param name="argCount">The number of arguments.</param>
- /// <param name="argNames">The argument names.</param>
- /// <returns>The new CallInfo</returns>
- public CallInfo(int argCount, IEnumerable<string> argNames) {
- ContractUtils.RequiresNotNull(argNames, "argNames");
-
- var argNameCol = argNames.ToReadOnly();
-
- if (argCount < argNameCol.Count) throw Error.ArgCntMustBeGreaterThanNameCnt();
- ContractUtils.RequiresNotNullItems(argNameCol, "argNames");
-
- _argCount = argCount;
- _argNames = argNameCol;
- }
-
- /// <summary>
- /// The number of arguments.
- /// </summary>
- public int ArgumentCount {
- get { return _argCount; }
- }
-
- /// <summary>
- /// The argument names.
- /// </summary>
- public ReadOnlyCollection<string> ArgumentNames {
- get { return _argNames; }
- }
-
- /// <summary>
- /// Serves as a hash function for the current CallInfo.
- /// </summary>
- /// <returns>A hash code for the current CallInfo.</returns>
- public override int GetHashCode() {
- return _argCount ^ _argNames.ListHashCode();
- }
-
- /// <summary>
- /// Determines whether the specified CallInfo instance is considered equal to the current.
- /// </summary>
- /// <param name="obj">The instance of CallInfo to compare with the current instance.</param>
- /// <returns>true if the specified instance is equal to the current one otherwise, false.</returns>
- public override bool Equals(object obj) {
- var other = obj as CallInfo;
- return _argCount == other._argCount && _argNames.ListEquals(other._argNames);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSite.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSite.cs
deleted file mode 100644
index 5ec58814184..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSite.cs
+++ /dev/null
@@ -1,734 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-using Microsoft.Scripting.Ast.Compiler;
-using Microsoft.Scripting.Utils;
-#else
-using System.Linq.Expressions;
-using System.Linq.Expressions.Compiler;
-#endif
-
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic;
-using System.Dynamic.Utils;
-using System.Reflection;
-
-namespace System.Runtime.CompilerServices {
-
- //
- // A CallSite provides a fast mechanism for call-site caching of dynamic dispatch
- // behvaior. Each site will hold onto a delegate that provides a fast-path dispatch
- // based on previous types that have been seen at the call-site. This delegate will
- // call UpdateAndExecute if it is called with types that it hasn't seen before.
- // Updating the binding will typically create (or lookup) a new delegate
- // that supports fast-paths for both the new type and for any types that
- // have been seen previously.
- //
- // DynamicSites will generate the fast-paths specialized for sets of runtime argument
- // types. However, they will generate exactly the right amount of code for the types
- // that are seen in the program so that int addition will remain as fast as it would
- // be with custom implementation of the addition, and the user-defined types can be
- // as fast as ints because they will all have the same optimal dynamically generated
- // fast-paths.
- //
- // DynamicSites don't encode any particular caching policy, but use their
- // CallSiteBinding to encode a caching policy.
- //
-
-
- /// <summary>
- /// A Dynamic Call Site base class. This type is used as a parameter type to the
- /// dynamic site targets. The first parameter of the delegate (T) below must be
- /// of this type.
- /// </summary>
- public class CallSite {
-
- // Cache of CallSite constructors for a given delegate type
- private static CacheDict<Type, Func<CallSiteBinder, CallSite>> _SiteCtors;
-
- /// <summary>
- /// The Binder responsible for binding operations at this call site.
- /// This binder is invoked by the UpdateAndExecute below if all Level 0,
- /// Level 1 and Level 2 caches experience cache miss.
- /// </summary>
- internal readonly CallSiteBinder _binder;
-
- // only CallSite<T> derives from this
- internal CallSite(CallSiteBinder binder) {
- _binder = binder;
- }
-
- /// <summary>
- /// used by Matchmaker sites to indicate rule match.
- /// </summary>
- internal bool _match;
-
- /// <summary>
- /// Class responsible for binding dynamic operations on the dynamic site.
- /// </summary>
- public CallSiteBinder Binder {
- get { return _binder; }
- }
-
- /// <summary>
- /// Creates a CallSite with the given delegate type and binder.
- /// </summary>
- /// <param name="delegateType">The CallSite delegate type.</param>
- /// <param name="binder">The CallSite binder.</param>
- /// <returns>The new CallSite.</returns>
- public static CallSite Create(Type delegateType, CallSiteBinder binder) {
- ContractUtils.RequiresNotNull(delegateType, "delegateType");
- ContractUtils.RequiresNotNull(binder, "binder");
- if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate();
-
- if (_SiteCtors == null) {
- // It's okay to just set this, worst case we're just throwing away some data
- _SiteCtors = new CacheDict<Type, Func<CallSiteBinder, CallSite>>(100);
- }
- Func<CallSiteBinder, CallSite> ctor;
-
- MethodInfo method = null;
- var ctors = _SiteCtors;
- lock (ctors) {
- if (!ctors.TryGetValue(delegateType, out ctor)) {
- method = typeof(CallSite<>).MakeGenericType(delegateType).GetMethod("Create");
-
- if (TypeUtils.CanCache(delegateType)) {
- ctor = (Func<CallSiteBinder, CallSite>)Delegate.CreateDelegate(typeof(Func<CallSiteBinder, CallSite>), method);
- ctors.Add(delegateType, ctor);
- }
- }
- }
- if (ctor != null) {
- return ctor(binder);
- }
-
- // slow path
- return (CallSite)method.Invoke(null, new object[] { binder });
- }
- }
-
- /// <summary>
- /// Dynamic site type.
- /// </summary>
- /// <typeparam name="T">The delegate type.</typeparam>
- public partial class CallSite<T> : CallSite where T : class {
- /// <summary>
- /// The update delegate. Called when the dynamic site experiences cache miss.
- /// </summary>
- /// <returns>The update delegate.</returns>
- public T Update {
- get {
- // if this site is set up for match making, then use NoMatch as an Update
- if (_match) {
- Debug.Assert(_CachedNoMatch != null, "all normal sites should have Update cached once there is an instance.");
- return _CachedNoMatch;
- } else {
- Debug.Assert(_CachedUpdate != null, "all normal sites should have Update cached once there is an instance.");
- return _CachedUpdate;
- }
- }
- }
-
- /// <summary>
- /// The Level 0 cache - a delegate specialized based on the site history.
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
- public T Target;
-
-
- /// <summary>
- /// The Level 1 cache - a history of the dynamic site.
- /// </summary>
- internal T[] Rules;
-
-
- // Cached update delegate for all sites with a given T
- private static T _CachedUpdate;
-
- // Cached noMatch delegate for all sites with a given T
- private static T _CachedNoMatch;
-
- private CallSite(CallSiteBinder binder)
- : base(binder) {
- Target = GetUpdateDelegate();
- }
-
- private CallSite()
- : base(null) {
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
- internal CallSite<T> CreateMatchMaker() {
- return new CallSite<T>();
- }
-
- /// <summary>
- /// Creates an instance of the dynamic call site, initialized with the binder responsible for the
- /// runtime binding of the dynamic operations at this call site.
- /// </summary>
- /// <param name="binder">The binder responsible for the runtime binding of the dynamic operations at this call site.</param>
- /// <returns>The new instance of dynamic call site.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
- public static CallSite<T> Create(CallSiteBinder binder) {
- if (!typeof(T).IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate();
- return new CallSite<T>(binder);
- }
-
- private T GetUpdateDelegate() {
- // This is intentionally non-static to speed up creation - in particular MakeUpdateDelegate
- // as static generic methods are more expensive than instance methods. We call a ref helper
- // so we only access the generic static field once.
- return GetUpdateDelegate(ref _CachedUpdate);
- }
-
- private T GetUpdateDelegate(ref T addr) {
- if (addr == null) {
- // reduce creation cost by not using Interlocked.CompareExchange. Calling I.CE causes
- // us to spend 25% of our creation time in JIT_GenericHandle. Instead we'll rarely
- // create 2 delegates with no other harm caused.
- addr = MakeUpdateDelegate();
- }
- return addr;
- }
-
- /// <summary>
- /// Clears the rule cache ... used by the call site tests.
- /// </summary>
- private void ClearRuleCache() {
- // make sure it initialized/atomized etc...
- Binder.GetRuleCache<T>();
-
- var cache = Binder.Cache;
-
- if (cache != null) {
- lock (cache) {
- cache.Clear();
- }
- }
- }
-
- const int MaxRules = 10;
- internal void AddRule(T newRule) {
- T[] rules = Rules;
- if (rules == null) {
- Rules = new[] { newRule };
- return;
- }
-
- T[] temp;
- if (rules.Length < (MaxRules - 1)) {
- temp = new T[rules.Length + 1];
- Array.Copy(rules, 0, temp, 1, rules.Length);
- } else {
- temp = new T[MaxRules];
- Array.Copy(rules, 0, temp, 1, MaxRules - 1);
- }
- temp[0] = newRule;
- Rules = temp;
- }
-
- // moves rule +2 up.
- internal void MoveRule(int i) {
- var rules = Rules;
- var rule = rules[i];
-
- rules[i] = rules[i - 1];
- rules[i - 1] = rules[i - 2];
- rules[i - 2] = rule;
- }
-
- internal T MakeUpdateDelegate() {
- Type target = typeof(T);
- Type[] args;
- MethodInfo invoke = target.GetMethod("Invoke");
-
-
- if (target.IsGenericType && IsSimpleSignature(invoke, out args)) {
- MethodInfo method = null;
- MethodInfo noMatchMethod = null;
-
- if (invoke.ReturnType == typeof(void)) {
- if (target == DelegateHelpers.GetActionType(args.AddFirst(typeof(CallSite)))) {
- method = typeof(UpdateDelegates).GetMethod("UpdateAndExecuteVoid" + args.Length, BindingFlags.NonPublic | BindingFlags.Static);
- noMatchMethod = typeof(UpdateDelegates).GetMethod("NoMatchVoid" + args.Length, BindingFlags.NonPublic | BindingFlags.Static);
- }
- } else {
- if (target == DelegateHelpers.GetFuncType(args.AddFirst(typeof(CallSite)))) {
- method = typeof(UpdateDelegates).GetMethod("UpdateAndExecute" + (args.Length - 1), BindingFlags.NonPublic | BindingFlags.Static);
- noMatchMethod = typeof(UpdateDelegates).GetMethod("NoMatch" + (args.Length - 1), BindingFlags.NonPublic | BindingFlags.Static);
- }
- }
- if (method != null) {
- _CachedNoMatch = (T)(object)CreateDelegateHelper(target, noMatchMethod.MakeGenericMethod(args));
- return (T)(object)CreateDelegateHelper(target, method.MakeGenericMethod(args));
- }
- }
-
- _CachedNoMatch = CreateCustomNoMatchDelegate(invoke);
- return CreateCustomUpdateDelegate(invoke);
- }
-
- // NEEDS SECURITY REVIEW:
- //
- // This needs to be SafeCritical on Silverlight to allow access to
- // internal types from user code as generic parameters.
- //
- // It's safe for a few reasons:
- // 1. The internal types are coming from a lower trust level (app code)
- // 2. We got the internal types from our own generic parameter: T
- // 3. The UpdateAndExecute methods don't do anything with the types,
- // we just want the CallSite args to be strongly typed to avoid
- // casting.
- // 4. Works on desktop CLR with AppDomain that has only Execute
- // permission. In theory it might require RestrictedMemberAccess,
- // but it's unclear because we have tests passing without RMA.
- //
- // When Silverlight gets RMA we may be able to remove this.
-#if SILVERLIGHT
- [System.Security.SecuritySafeCritical]
-#endif
- private static Delegate CreateDelegateHelper(Type delegateType, MethodInfo method) {
- return Delegate.CreateDelegate(delegateType, method);
- }
-
- private static bool IsSimpleSignature(MethodInfo invoke, out Type[] sig) {
- ParameterInfo[] pis = invoke.GetParametersCached();
- ContractUtils.Requires(pis.Length > 0 && pis[0].ParameterType == typeof(CallSite), "T");
-
- Type[] args = new Type[invoke.ReturnType != typeof(void) ? pis.Length : pis.Length - 1];
- bool supported = true;
-
- for (int i = 1; i < pis.Length; i++) {
- ParameterInfo pi = pis[i];
- if (pi.IsByRefParameter()) {
- supported = false;
- }
- args[i - 1] = pi.ParameterType;
- }
- if (invoke.ReturnType != typeof(void)) {
- args[args.Length - 1] = invoke.ReturnType;
- }
- sig = args;
- return supported;
- }
-
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
- private T CreateCustomNoMatchDelegate(MethodInfo invoke) {
- var @params = invoke.GetParametersCached().Map(p => Expression.Parameter(p.ParameterType, p.Name));
- return Expression.Lambda<T>(
- Expression.Block(
- Expression.Call(
- typeof(CallSiteOps).GetMethod("SetNotMatched"),
- @params.First()
- ),
- Expression.Default(invoke.GetReturnType())
- ),
- @params
- ).Compile();
- }
-
- //
- // WARNING: If you're changing this method, make sure you update the
- // pregenerated versions as well, which are generated by
- // generate_dynsites.py
- // The two implementations *must* be kept functionally equivalent!
- //
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
- private T CreateCustomUpdateDelegate(MethodInfo invoke) {
- var body = new List<Expression>();
- var vars = new List<ParameterExpression>();
- var @params = invoke.GetParametersCached().Map(p => Expression.Parameter(p.ParameterType, p.Name));
- var @return = Expression.Label(invoke.GetReturnType());
- var typeArgs = new[] { typeof(T) };
-
- var site = @params[0];
- var arguments = @params.RemoveFirst();
-
- //var @this = (CallSite<T>)site;
- var @this = Expression.Variable(typeof(CallSite<T>), "this");
- vars.Add(@this);
- body.Add(Expression.Assign(@this, Expression.Convert(site, @this.Type)));
-
- //T[] applicable;
- var applicable = Expression.Variable(typeof(T[]), "applicable");
- vars.Add(applicable);
-
- //T rule, originalRule = @this.Target;
- var rule = Expression.Variable(typeof(T), "rule");
- vars.Add(rule);
-
- var originalRule = Expression.Variable(typeof(T), "originalRule");
- vars.Add(originalRule);
- body.Add(Expression.Assign(originalRule, Expression.Field(@this, "Target")));
-
- //TRet result;
- ParameterExpression result = null;
- if (@return.Type != typeof(void)) {
- vars.Add(result = Expression.Variable(@return.Type, "result"));
- }
-
- //int count, index;
- var count = Expression.Variable(typeof(int), "count");
- vars.Add(count);
- var index = Expression.Variable(typeof(int), "index");
- vars.Add(index);
-
- ////
- //// Create matchmaker site. We'll need it regardless.
- ////
- //site = CallSiteOps.CreateMatchmaker();
- body.Add(
- Expression.Assign(
- site,
- Expression.Call(
- typeof(CallSiteOps),
- "CreateMatchmaker",
- typeArgs,
- @this
- )
- )
- );
-
- ////
- //// Level 1 cache lookup
- ////
- //if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- // for (index = 0, count = applicable.Length; index < count; index++) {
- // @this.Target = rule = applicable[i];
-
- // //
- // // Execute the rule
- // //
- //
- // // if we've already tried it skip it...
- // if ((object)rule != (object)originalRule) {
- // %(setResult)s rule(site, %(args)s);
- // if (CallSiteOps.GetMatch(site)) {
- // CallSiteOps.UpdateRules(@this, i);
- // %(returnResult)s;
- // }
- //
- // // Rule didn't match, try the next one
- // CallSiteOps.ClearMatch(site);
- // }
- // }
- //}
- Expression invokeRule;
-
- Expression getMatch = Expression.Call(
- typeof(CallSiteOps).GetMethod("GetMatch"),
- site
- );
-
- Expression resetMatch = Expression.Call(
- typeof(CallSiteOps).GetMethod("ClearMatch"),
- site
- );
-
- var onMatch = Expression.Call(
- typeof(CallSiteOps),
- "UpdateRules",
- typeArgs,
- @this,
- index
- );
-
- if (@return.Type == typeof(void)) {
- invokeRule = Expression.Block(
- Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params)),
- Expression.IfThen(
- getMatch,
- Expression.Block(onMatch, Expression.Return(@return))
- )
- );
- } else {
- invokeRule = Expression.Block(
- Expression.Assign(result, Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params))),
- Expression.IfThen(
- getMatch,
- Expression.Block(onMatch, Expression.Return(@return, result))
- )
- );
- }
-
- Expression getRule = Expression.Assign(rule, Expression.ArrayAccess(applicable, index));
-
- var @break = Expression.Label();
-
- var breakIfDone = Expression.IfThen(
- Expression.Equal(index, count),
- Expression.Break(@break)
- );
-
- var incrementIndex = Expression.PreIncrementAssign(index);
-
- body.Add(
- Expression.IfThen(
- Expression.NotEqual(
- Expression.Assign(applicable, Expression.Call(typeof(CallSiteOps), "GetRules", typeArgs, @this)),
- Expression.Constant(null, applicable.Type)
- ),
- Expression.Block(
- Expression.Assign(count, Expression.ArrayLength(applicable)),
- Expression.Assign(index, Expression.Constant(0)),
- Expression.Loop(
- Expression.Block(
- breakIfDone,
- getRule,
- Expression.IfThen(
- Expression.NotEqual(
- Expression.Convert(rule, typeof(object)),
- Expression.Convert(originalRule, typeof(object))
- ),
- Expression.Block(
- Expression.Assign(
- Expression.Field(@this, "Target"),
- rule
- ),
- invokeRule,
- resetMatch
- )
- ),
- incrementIndex
- ),
- @break,
- null
- )
- )
- )
- );
-
- ////
- //// Level 2 cache lookup
- ////
- //
- ////
- //// Any applicable rules in level 2 cache?
- ////
- //
- // var cache = CallSiteOps.GetRuleCache(@this);
-
- var cache = Expression.Variable(typeof(RuleCache<T>), "cache");
- vars.Add(cache);
-
- body.Add(
- Expression.Assign(
- cache,
- Expression.Call(typeof(CallSiteOps), "GetRuleCache", typeArgs, @this)
- )
- );
-
- // applicable = cache.GetRules();
-
- body.Add(
- Expression.Assign(
- applicable,
- Expression.Call(typeof(CallSiteOps), "GetCachedRules", typeArgs, cache)
- )
- );
-
- // for (int i = 0, count = applicable.Length; i < count; i++) {
- // @this.Target = rule = applicable[i];
- //
- // //
- // // Execute the rule
- // //
- //
- // try {
- // result = rule(site, arg0);
- // if (match) {
- // return result;
- // }
- // } finally {
- // if (CallSiteOps.GetMatch(site)) {
- // //
- // // Rule worked. Add it to level 1 cache
- // //
- //
- // CallSiteOps.AddRule(@this, rule);
- // // and then move it to the front of the L2 cache
- // CallSiteOps.MoveRule(cache, rule, index);
- // }
- // }
- //
- // // Rule didn't match, try the next one
- // CallSiteOps.ClearMatch(site);
- // }
- //
-
-
- // L2 invokeRule is different (no onMatch)
- if (@return.Type == typeof(void)) {
- invokeRule = Expression.Block(
- Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params)),
- Expression.IfThen(
- getMatch,
- Expression.Return(@return)
- )
- );
- } else {
- invokeRule = Expression.Block(
- Expression.Assign(result, Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params))),
- Expression.IfThen(
- getMatch,
- Expression.Return(@return, result)
- )
- );
- }
-
- var tryRule = Expression.TryFinally(
- invokeRule,
- Expression.IfThen(
- getMatch,
- Expression.Block(
- Expression.Call(typeof(CallSiteOps), "AddRule", typeArgs, @this, rule),
- Expression.Call(typeof(CallSiteOps), "MoveRule", typeArgs, cache, rule, index)
- )
- )
- );
-
- getRule = Expression.Assign(
- Expression.Field(@this, "Target"),
- Expression.Assign(rule, Expression.ArrayAccess(applicable, index))
- );
-
- body.Add(Expression.Assign(index, Expression.Constant(0)));
- body.Add(Expression.Assign(count, Expression.ArrayLength(applicable)));
- body.Add(
- Expression.Loop(
- Expression.Block(
- breakIfDone,
- getRule,
- tryRule,
- resetMatch,
- incrementIndex
- ),
- @break,
- null
- )
- );
-
- ////
- //// Miss on Level 0, 1 and 2 caches. Create new rule
- ////
-
- //rule = null;
- body.Add(Expression.Assign(rule, Expression.Constant(null, rule.Type)));
-
- //var args = new object[] { arg0, arg1, ... };
- var args = Expression.Variable(typeof(object[]), "args");
- vars.Add(args);
- body.Add(
- Expression.Assign(
- args,
- Expression.NewArrayInit(typeof(object), arguments.Map(p => Convert(p, typeof(object))))
- )
- );
-
- //for (; ; ) {
- // @this.Target = originalRule;
- // rule = @this.Target = @this.Binder.BindDelegate(@this, args);
-
- // //
- // // Execute the rule on the matchmaker site
- // //
-
- // try {
- // %(setResult)s ruleTarget(site, %(args)s);
- // if (match) {
- // %(returnResult)s;
- // }
- // } finally {
- // if (match) {
- // //
- // // The rule worked. Add it to level 1 cache.
- // //
- // CallSiteOps.AddRule(@this, rule);
- // }
- // }
-
- // // Rule we got back didn't work, try another one
- // match = true;
- //}
-
- Expression setOldTarget = Expression.Assign(
- Expression.Field(@this, "Target"),
- originalRule
- );
-
- getRule = Expression.Assign(
- Expression.Field(@this, "Target"),
- Expression.Assign(
- rule,
- Expression.Call(
- typeof(CallSiteOps),
- "Bind",
- typeArgs,
- Expression.Property(@this, "Binder"),
- @this,
- args
- )
- )
- );
-
- tryRule = Expression.TryFinally(
- invokeRule,
- Expression.IfThen(
- getMatch,
- Expression.Call(typeof(CallSiteOps), "AddRule", typeArgs, @this, rule)
- )
- );
-
- body.Add(
- Expression.Loop(
- Expression.Block(setOldTarget, getRule, tryRule, resetMatch),
- null, null
- )
- );
-
- body.Add(Expression.Default(@return.Type));
-
- var lambda = Expression.Lambda<T>(
- Expression.Label(
- @return,
- Expression.Block(
- new ReadOnlyCollection<ParameterExpression>(vars),
- new ReadOnlyCollection<Expression>(body)
- )
- ),
- "CallSite.Target",
- true, // always compile the rules with tail call optimization
- new ReadOnlyCollection<ParameterExpression>(@params)
- );
-
- // Need to compile with forceDynamic because T could be invisible,
- // or one of the argument types could be invisible
- return lambda.Compile();
- }
-
- private static Expression Convert(Expression arg, Type type) {
- if (TypeUtils.AreReferenceAssignable(type, arg.Type)) {
- return arg;
- }
- return Expression.Convert(arg, type);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteBinder.cs
deleted file mode 100644
index ccf1134dfa8..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteBinder.cs
+++ /dev/null
@@ -1,232 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-#else
-using System.Linq.Expressions;
-#endif
-
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic;
-using System.Dynamic.Utils;
-using System.Threading;
-using System.Reflection;
-
-namespace System.Runtime.CompilerServices {
- /// <summary>
- /// Class responsible for runtime binding of the dynamic operations on the dynamic call site.
- /// </summary>
- public abstract class CallSiteBinder {
- private static readonly LabelTarget _updateLabel = Expression.Label("CallSiteBinder.UpdateLabel");
-
- /// <summary>
- /// The Level 2 cache - all rules produced for the same binder.
- /// </summary>
- internal Dictionary<Type, object> Cache;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CallSiteBinder"/> class.
- /// </summary>
- protected CallSiteBinder() {
- }
-
- /// <summary>
- /// Gets a label that can be used to cause the binding to be updated. It
- /// indicates that the expression's binding is no longer valid.
- /// This is typically used when the "version" of a dynamic object has
- /// changed.
- /// </summary>
- public static LabelTarget UpdateLabel {
- get { return _updateLabel; }
- }
-
- private sealed class LambdaSignature<T> where T : class {
- internal static readonly LambdaSignature<T> Instance = new LambdaSignature<T>();
-
- internal readonly ReadOnlyCollection<ParameterExpression> Parameters;
- internal readonly LabelTarget ReturnLabel;
-
- private LambdaSignature() {
- Type target = typeof(T);
- if (!target.IsSubclassOf(typeof(MulticastDelegate))) {
- throw Error.TypeParameterIsNotDelegate(target);
- }
-
- MethodInfo invoke = target.GetMethod("Invoke");
- ParameterInfo[] pis = invoke.GetParametersCached();
- if (pis[0].ParameterType != typeof(CallSite)) {
- throw Error.FirstArgumentMustBeCallSite();
- }
-
- var @params = new ParameterExpression[pis.Length - 1];
- for (int i = 0; i < @params.Length; i++) {
- @params[i] = Expression.Parameter(pis[i + 1].ParameterType, "$arg" + i);
- }
-
- Parameters = new TrueReadOnlyCollection<ParameterExpression>(@params);
- ReturnLabel = Expression.Label(invoke.GetReturnType());
- }
- }
-
- /// <summary>
- /// Performs the runtime binding of the dynamic operation on a set of arguments.
- /// </summary>
- /// <param name="args">An array of arguments to the dynamic operation.</param>
- /// <param name="parameters">The array of <see cref="ParameterExpression"/> instances that represent the parameters of the call site in the binding process.</param>
- /// <param name="returnLabel">A LabelTarget used to return the result of the dynamic binding.</param>
- /// <returns>
- /// An Expression that performs tests on the dynamic operation arguments, and
- /// performs the dynamic operation if hte tests are valid. If the tests fail on
- /// subsequent occurrences of the dynamic operation, Bind will be called again
- /// to produce a new <see cref="Expression"/> for the new argument types.
- /// </returns>
- public abstract Expression Bind(object[] args, ReadOnlyCollection<ParameterExpression> parameters, LabelTarget returnLabel);
-
- /// <summary>
- /// Provides low-level runtime binding support. Classes can override this and provide a direct
- /// delegate for the implementation of rule. This can enable saving rules to disk, having
- /// specialized rules available at runtime, or providing a different caching policy.
- /// </summary>
- /// <typeparam name="T">The target type of the CallSite.</typeparam>
- /// <param name="site">The CallSite the bind is being performed for.</param>
- /// <param name="args">The arguments for the binder.</param>
- /// <returns>A new delegate which replaces the CallSite Target.</returns>
- public virtual T BindDelegate<T>(CallSite<T> site, object[] args) where T : class {
- return null;
- }
-
-
- internal T BindCore<T>(CallSite<T> site, object[] args) where T : class {
- //
- // Try to find a precompiled delegate, and return it if found.
- //
- T result = BindDelegate(site, args);
- if (result != null) {
- return result;
- }
-
- //
- // Get the Expression for the binding
- //
- var signature = LambdaSignature<T>.Instance;
- Expression binding = Bind(args, signature.Parameters, signature.ReturnLabel);
-
- //
- // Check the produced rule
- //
- if (binding == null) {
- throw Error.NoOrInvalidRuleProduced();
- }
-
- //
- // finally produce the new rule if we need to
- //
-#if !CLR2 && !SILVERLIGHT && !ANDROID && !WP75
- // We cannot compile rules in the heterogeneous app domains since they
- // may come from less trusted sources
- // Silverlight always uses a homogenous appdomain, so we don’t need this check
- if (!AppDomain.CurrentDomain.IsHomogenous) {
- throw Error.HomogenousAppDomainRequired();
- }
-#endif
- Expression<T> e = Stitch(binding, signature);
- T newRule = e.Compile();
-
- CacheTarget(newRule);
-
- return newRule;
- }
-
- /// <summary>
- /// Adds a target to the cache of known targets. The cached targets will
- /// be scanned before calling BindDelegate to produce the new rule.
- /// </summary>
- /// <typeparam name="T">The type of target being added.</typeparam>
- /// <param name="target">The target delegate to be added to the cache.</param>
- protected void CacheTarget<T>(T target) where T : class {
- GetRuleCache<T>().AddRule(target);
- }
-
- private static Expression<T> Stitch<T>(Expression binding, LambdaSignature<T> signature) where T : class {
- Type siteType = typeof(CallSite<T>);
-
- var body = new ReadOnlyCollectionBuilder<Expression>(3);
- body.Add(binding);
-
- var site = Expression.Parameter(typeof(CallSite), "$site");
- var @params = signature.Parameters.AddFirst(site);
-
- Expression updLabel = Expression.Label(CallSiteBinder.UpdateLabel);
-
-#if DEBUG
- // put the AST into the constant pool for debugging purposes
- updLabel = Expression.Block(
- Expression.Constant(binding, typeof(Expression)),
- updLabel
- );
-#endif
-
- body.Add(updLabel);
- body.Add(
- Expression.Label(
- signature.ReturnLabel,
- Expression.Condition(
- Expression.Call(
- typeof(CallSiteOps).GetMethod("SetNotMatched"),
- @params.First()
- ),
- Expression.Default(signature.ReturnLabel.Type),
- Expression.Invoke(
- Expression.Property(
- Expression.Convert(site, siteType),
- typeof(CallSite<T>).GetProperty("Update")
- ),
- new TrueReadOnlyCollection<Expression>(@params)
- )
- )
- )
- );
-
- return new Expression<T>(
- Expression.Block(body),
- "CallSite.Target",
- true, // always compile the rules with tail call optimization
- new TrueReadOnlyCollection<ParameterExpression>(@params)
- );
- }
-
- internal RuleCache<T> GetRuleCache<T>() where T : class {
- // make sure we have cache.
- if (Cache == null) {
- Interlocked.CompareExchange(ref Cache, new Dictionary<Type, object>(), null);
- }
-
- object ruleCache;
- var cache = Cache;
- lock (cache) {
- if (!cache.TryGetValue(typeof(T), out ruleCache)) {
- cache[typeof(T)] = ruleCache = new RuleCache<T>();
- }
- }
-
- RuleCache<T> result = ruleCache as RuleCache<T>;
- Debug.Assert(result != null);
- return result;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteHelpers.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteHelpers.cs
deleted file mode 100644
index 2bb42801830..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteHelpers.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Reflection;
-namespace System.Runtime.CompilerServices {
- /// <summary>
- /// Class that contains helper methods for DLR CallSites.
- /// </summary>
- public static class CallSiteHelpers {
- private static Type _knownNonDynamicMethodType = typeof(object).GetMethod("ToString").GetType();
-
- /// <summary>
- /// Checks if a <see cref="MethodBase"/> is internally used by DLR and should not
- /// be displayed on the language code's stack.
- /// </summary>
- /// <param name="mb">The input <see cref="MethodBase"/></param>
- /// <returns>
- /// True if the input <see cref="MethodBase"/> is internally used by DLR and should not
- /// be displayed on the language code's stack. Otherwise, false.
- /// </returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
- public static bool IsInternalFrame(MethodBase mb) {
- //All the dynamic methods created for DLR rules have a special name.
- //We also check if the method has a different type than the known
- //non-static method. If it does, it is a dynamic method.
- //This could be improved if the CLR provides a way to attach some information
- //to the dynamic method we create, like CustomAttributes.
- if (mb.Name == "CallSite.Target" && mb.GetType() != _knownNonDynamicMethodType) {
- return true;
- }
-
- //Filter out the helper methods.
- if (mb.DeclaringType == typeof(System.Dynamic.UpdateDelegates)) {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteOps.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteOps.cs
deleted file mode 100644
index 7b66829d342..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteOps.cs
+++ /dev/null
@@ -1,161 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Dynamic;
-using System.Collections.Generic;
-
-namespace System.Runtime.CompilerServices {
-
- // Conceptually these are instance methods on CallSite<T> but
- // we don't want users to see them
-
- /// <summary>
- /// This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never), DebuggerStepThrough]
- public static class CallSiteOps {
-
- /// <summary>
- /// Creates an instance of a dynamic call site used for cache lookup.
- /// </summary>
- /// <typeparam name="T">The type of the delegate of the <see cref="CallSite"/>.</typeparam>
- /// <returns>The new call site.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static CallSite<T> CreateMatchmaker<T>(CallSite<T> site) where T : class {
- var mm = site.CreateMatchMaker();
- CallSiteOps.ClearMatch(mm);
- return mm;
- }
-
- /// <summary>
- /// Checks if a dynamic site requires an update.
- /// </summary>
- /// <param name="site">An instance of the dynamic call site.</param>
- /// <returns>true if rule does not need updating, false otherwise.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static bool SetNotMatched(CallSite site) {
- var res = site._match;
- site._match = false; //avoid branch here to make sure the method is inlined
- return res;
- }
-
- /// <summary>
- /// Checks whether the executed rule matched
- /// </summary>
- /// <param name="site">An instance of the dynamic call site.</param>
- /// <returns>true if rule matched, false otherwise.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static bool GetMatch(CallSite site) {
- return site._match;
- }
-
- /// <summary>
- /// Clears the match flag on the matchmaker call site.
- /// </summary>
- /// <param name="site">An instance of the dynamic call site.</param>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static void ClearMatch(CallSite site) {
- site._match = true;
- }
-
- /// <summary>
- /// Adds a rule to the cache maintained on the dynamic call site.
- /// </summary>
- /// <typeparam name="T">The type of the delegate of the <see cref="CallSite"/>.</typeparam>
- /// <param name="site">An instance of the dynamic call site.</param>
- /// <param name="rule">An instance of the call site rule.</param>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static void AddRule<T>(CallSite<T> site, T rule) where T : class {
- site.AddRule(rule);
- }
-
- /// <summary>
- /// Updates rules in the cache.
- /// </summary>
- /// <typeparam name="T">The type of the delegate of the <see cref="CallSite"/>.</typeparam>
- /// <param name="this">An instance of the dynamic call site.</param>
- /// <param name="matched">The matched rule index.</param>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static void UpdateRules<T>(CallSite<T> @this, int matched) where T : class {
- if (matched > 1) {
- @this.MoveRule(matched);
- }
- }
-
- /// <summary>
- /// Gets the dynamic binding rules from the call site.
- /// </summary>
- /// <typeparam name="T">The type of the delegate of the <see cref="CallSite"/>.</typeparam>
- /// <param name="site">An instance of the dynamic call site.</param>
- /// <returns>An array of dynamic binding rules.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static T[] GetRules<T>(CallSite<T> site) where T : class {
- return site.Rules;
- }
-
-
- /// <summary>
- /// Retrieves binding rule cache.
- /// </summary>
- /// <typeparam name="T">The type of the delegate of the <see cref="CallSite"/>.</typeparam>
- /// <param name="site">An instance of the dynamic call site.</param>
- /// <returns>The cache.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static RuleCache<T> GetRuleCache<T>(CallSite<T> site) where T : class {
- return site.Binder.GetRuleCache<T>();
- }
-
-
- /// <summary>
- /// Moves the binding rule within the cache.
- /// </summary>
- /// <typeparam name="T">The type of the delegate of the <see cref="CallSite"/>.</typeparam>
- /// <param name="cache">The call site rule cache.</param>
- /// <param name="rule">An instance of the call site rule.</param>
- /// <param name="i">An index of the call site rule.</param>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static void MoveRule<T>(RuleCache<T> cache, T rule, int i) where T : class {
- if (i > 1) {
- cache.MoveRule(rule, i);
- }
- }
-
- /// <summary>
- /// Searches the dynamic rule cache for rules applicable to the dynamic operation.
- /// </summary>
- /// <typeparam name="T">The type of the delegate of the <see cref="CallSite"/>.</typeparam>
- /// <param name="cache">The cache.</param>
- /// <returns>The collection of applicable rules.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static T[] GetCachedRules<T>(RuleCache<T> cache) where T : class {
- return cache.GetRules();
- }
-
- /// <summary>
- /// Updates the call site target with a new rule based on the arguments.
- /// </summary>
- /// <typeparam name="T">The type of the delegate of the <see cref="CallSite"/>.</typeparam>
- /// <param name="binder">The call site binder.</param>
- /// <param name="site">An instance of the dynamic call site.</param>
- /// <param name="args">Arguments to the call site.</param>
- /// <returns>The new call site target.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static T Bind<T>(CallSiteBinder binder, CallSite<T> site, object[] args) where T : class {
- return binder.BindCore(site, args);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/ConvertBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/ConvertBinder.cs
deleted file mode 100644
index af6b2782502..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/ConvertBinder.cs
+++ /dev/null
@@ -1,101 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Dynamic.Utils;
-
-namespace System.Dynamic {
- /// <summary>
- /// Represents the convert dynamic operation at the call site, providing the binding semantic and the details about the operation.
- /// </summary>
- public abstract class ConvertBinder : DynamicMetaObjectBinder {
- private readonly Type _type;
- private readonly bool _explicit;
-
- /// <summary>
- /// Initializes a new intsance of the <see cref="ConvertBinder" />.
- /// </summary>
- /// <param name="type">The type to convert to.</param>
- /// <param name="explicit">true if the conversion should consider explicit conversions; otherwise, false.</param>
- protected ConvertBinder(Type type, bool @explicit) {
- ContractUtils.RequiresNotNull(type, "type");
-
- _type = type;
- _explicit = @explicit;
- }
-
- /// <summary>
- /// The type to convert to.
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
- public Type Type {
- get {
- return _type;
- }
- }
-
- /// <summary>
- /// Gets the value indicating if the conversion should consider explicit conversions.
- /// </summary>
- public bool Explicit {
- get {
- return _explicit;
- }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic convert operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic convert operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject FallbackConvert(DynamicMetaObject target) {
- return FallbackConvert(target, null);
- }
-
- /// <summary>
- /// When overridden in the derived class, performs the binding of the dynamic convert operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic convert operation.</param>
- /// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public abstract DynamicMetaObject FallbackConvert(DynamicMetaObject target, DynamicMetaObject errorSuggestion);
-
- /// <summary>
- /// Performs the binding of the dynamic convert operation.
- /// </summary>
- /// <param name="target">The target of the dynamic convert operation.</param>
- /// <param name="args">An array of arguments of the dynamic convert operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(target, "target");
- ContractUtils.Requires(args == null || args.Length == 0, "args");
-
- return target.BindConvert(this);
- }
-
- // this is a standard DynamicMetaObjectBinder
- internal override sealed bool IsStandardBinder {
- get {
- return true;
- }
- }
-
- /// <summary>
- /// The result type of the operation.
- /// </summary>
- public override sealed Type ReturnType {
- get { return _type; }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CreateInstanceBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CreateInstanceBinder.cs
deleted file mode 100644
index 9edf1b7db0e..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/CreateInstanceBinder.cs
+++ /dev/null
@@ -1,87 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Dynamic.Utils;
-
-namespace System.Dynamic {
- /// <summary>
- /// Represents the create dynamic operation at the call site, providing the binding semantic and the details about the operation.
- /// </summary>
- public abstract class CreateInstanceBinder : DynamicMetaObjectBinder {
- private readonly CallInfo _callInfo;
-
- /// <summary>
- /// Initializes a new intsance of the <see cref="CreateInstanceBinder" />.
- /// </summary>
- /// <param name="callInfo">The signature of the arguments at the call site.</param>
- protected CreateInstanceBinder(CallInfo callInfo) {
- ContractUtils.RequiresNotNull(callInfo, "callInfo");
- _callInfo = callInfo;
- }
-
- /// <summary>
- /// The result type of the operation.
- /// </summary>
- public override sealed Type ReturnType {
- get { return typeof(object); }
- }
-
- /// <summary>
- /// Gets the signature of the arguments at the call site.
- /// </summary>
- public CallInfo CallInfo {
- get { return _callInfo; }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic create operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic create operation.</param>
- /// <param name="args">The arguments of the dynamic create operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject FallbackCreateInstance(DynamicMetaObject target, DynamicMetaObject[] args) {
- return FallbackCreateInstance(target, args, null);
- }
-
- /// <summary>
- /// When overridden in the derived class, performs the binding of the dynamic create operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic create operation.</param>
- /// <param name="args">The arguments of the dynamic create operation.</param>
- /// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public abstract DynamicMetaObject FallbackCreateInstance(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion);
-
- /// <summary>
- /// Performs the binding of the dynamic create operation.
- /// </summary>
- /// <param name="target">The target of the dynamic create operation.</param>
- /// <param name="args">An array of arguments of the dynamic create operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(target, "target");
- ContractUtils.RequiresNotNullItems(args, "args");
-
- return target.BindCreateInstance(this, args);
- }
-
- // this is a standard DynamicMetaObjectBinder
- internal override sealed bool IsStandardBinder {
- get {
- return true;
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DeleteIndexBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DeleteIndexBinder.cs
deleted file mode 100644
index 1cf5abf7498..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DeleteIndexBinder.cs
+++ /dev/null
@@ -1,87 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Dynamic.Utils;
-
-namespace System.Dynamic {
- /// <summary>
- /// Represents the dynamic delete index operation at the call site, providing the binding semantic and the details about the operation.
- /// </summary>
- public abstract class DeleteIndexBinder : DynamicMetaObjectBinder {
- private readonly CallInfo _callInfo;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DeleteIndexBinder" />.
- /// </summary>
- /// <param name="callInfo">The signature of the arguments at the call site.</param>
- protected DeleteIndexBinder(CallInfo callInfo) {
- ContractUtils.RequiresNotNull(callInfo, "callInfo");
- _callInfo = callInfo;
- }
-
- /// <summary>
- /// The result type of the operation.
- /// </summary>
- public override sealed Type ReturnType {
- get { return typeof(void); }
- }
-
- /// <summary>
- /// Gets the signature of the arguments at the call site.
- /// </summary>
- public CallInfo CallInfo {
- get { return _callInfo; }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic delete index operation.
- /// </summary>
- /// <param name="target">The target of the dynamic delete index operation.</param>
- /// <param name="args">An array of arguments of the dynamic delete index operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(target, "target");
- ContractUtils.RequiresNotNullItems(args, "args");
-
- return target.BindDeleteIndex(this, args);
- }
-
- // this is a standard DynamicMetaObjectBinder
- internal override sealed bool IsStandardBinder {
- get {
- return true;
- }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic delete index operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic delete index operation.</param>
- /// <param name="indexes">The arguments of the dynamic delete index operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject FallbackDeleteIndex(DynamicMetaObject target, DynamicMetaObject[] indexes) {
- return FallbackDeleteIndex(target, indexes, null);
- }
-
- /// <summary>
- /// When overridden in the derived class, performs the binding of the dynamic delete index operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic delete index operation.</param>
- /// <param name="indexes">The arguments of the dynamic delete index operation.</param>
- /// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public abstract DynamicMetaObject FallbackDeleteIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject errorSuggestion);
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DeleteMemberBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DeleteMemberBinder.cs
deleted file mode 100644
index d01bfcdf00b..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DeleteMemberBinder.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Dynamic.Utils;
-
-namespace System.Dynamic {
-
- /// <summary>
- /// Represents the dynamic delete member operation at the call site, providing the binding semantic and the details about the operation.
- /// </summary>
- public abstract class DeleteMemberBinder : DynamicMetaObjectBinder {
- private readonly string _name;
- private readonly bool _ignoreCase;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DeleteIndexBinder" />.
- /// </summary>
- /// <param name="name">The name of the member to delete.</param>
- /// <param name="ignoreCase">true if the name should be matched ignoring case; false otherwise.</param>
- protected DeleteMemberBinder(string name, bool ignoreCase) {
- ContractUtils.RequiresNotNull(name, "name");
-
- _name = name;
- _ignoreCase = ignoreCase;
- }
-
- /// <summary>
- /// Gets the name of the member to delete.
- /// </summary>
- public string Name {
- get {
- return _name;
- }
- }
-
- /// <summary>
- /// Gets the value indicating if the string comparison should ignore the case of the member name.
- /// </summary>
- public bool IgnoreCase {
- get {
- return _ignoreCase;
- }
- }
-
- /// <summary>
- /// The result type of the operation.
- /// </summary>
- public override sealed Type ReturnType {
- get { return typeof(void); }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic delete member operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic delete member operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject FallbackDeleteMember(DynamicMetaObject target) {
- return FallbackDeleteMember(target, null);
- }
-
- /// <summary>
- /// When overridden in the derived class, performs the binding of the dynamic delete member operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic delete member operation.</param>
- /// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public abstract DynamicMetaObject FallbackDeleteMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion);
-
- /// <summary>
- /// Performs the binding of the dynamic delete member operation.
- /// </summary>
- /// <param name="target">The target of the dynamic delete member operation.</param>
- /// <param name="args">An array of arguments of the dynamic delete member operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(target, "target");
- ContractUtils.Requires(args == null || args.Length == 0);
-
- return target.BindDeleteMember(this);
- }
-
-
- // this is a standard DynamicMetaObjectBinder
- internal override sealed bool IsStandardBinder {
- get {
- return true;
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicMetaObject.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicMetaObject.cs
deleted file mode 100644
index 5db80654ba1..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicMetaObject.cs
+++ /dev/null
@@ -1,332 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-#else
-using System.Linq.Expressions;
-#endif
-
-#if FEATURE_REMOTING
-using System.Runtime.Remoting;
-#endif
-
-using System.Collections.Generic;
-using System.Dynamic.Utils;
-using System.Reflection;
-
-namespace System.Dynamic {
- /// <summary>
- /// Represents the dynamic binding and a binding logic of an object participating in the dynamic binding.
- /// </summary>
- public class DynamicMetaObject {
- private readonly Expression _expression;
- private readonly BindingRestrictions _restrictions;
- private readonly object _value;
- private readonly bool _hasValue;
-
- /// <summary>
- /// Represents an empty array of type <see cref="DynamicMetaObject"/>. This field is read only.
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
- public static readonly DynamicMetaObject[] EmptyMetaObjects = new DynamicMetaObject[0];
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DynamicMetaObject"/> class.
- /// </summary>
- /// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param>
- /// <param name="restrictions">The set of binding restrictions under which the binding is valid.</param>
- public DynamicMetaObject(Expression expression, BindingRestrictions restrictions) {
- ContractUtils.RequiresNotNull(expression, "expression");
- ContractUtils.RequiresNotNull(restrictions, "restrictions");
-
- _expression = expression;
- _restrictions = restrictions;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DynamicMetaObject"/> class.
- /// </summary>
- /// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param>
- /// <param name="restrictions">The set of binding restrictions under which the binding is valid.</param>
- /// <param name="value">The runtime value represented by the <see cref="DynamicMetaObject"/>.</param>
- public DynamicMetaObject(Expression expression, BindingRestrictions restrictions, object value)
- : this(expression, restrictions) {
- _value = value;
- _hasValue = true;
- }
-
- /// <summary>
- /// The expression representing the <see cref="DynamicMetaObject"/> during the dynamic binding process.
- /// </summary>
- public Expression Expression {
- get {
- return _expression;
- }
- }
-
- /// <summary>
- /// The set of binding restrictions under which the binding is valid.
- /// </summary>
- public BindingRestrictions Restrictions {
- get {
- return _restrictions;
- }
- }
-
- /// <summary>
- /// The runtime value represented by this <see cref="DynamicMetaObject"/>.
- /// </summary>
- public object Value {
- get {
- return _value;
- }
- }
-
- /// <summary>
- /// Gets a value indicating whether the <see cref="DynamicMetaObject"/> has the runtime value.
- /// </summary>
- public bool HasValue {
- get {
- return _hasValue;
- }
- }
-
-
- /// <summary>
- /// Gets the <see cref="Type"/> of the runtime value or null if the <see cref="DynamicMetaObject"/> has no value associated with it.
- /// </summary>
- public Type RuntimeType {
- get {
- if (_hasValue) {
- Type ct = Expression.Type;
- // valuetype at compile tyme, type cannot change.
- if (ct.IsValueType) {
- return ct;
- }
- if (_value != null) {
- return _value.GetType();
- } else {
- return null;
- }
- } else {
- return null;
- }
- }
- }
-
- /// <summary>
- /// Gets the limit type of the <see cref="DynamicMetaObject"/>.
- /// </summary>
- /// <remarks>Represents the most specific type known about the object represented by the <see cref="DynamicMetaObject"/>. <see cref="RuntimeType"/> if runtime value is available, a type of the <see cref="Expression"/> otherwise.</remarks>
- public Type LimitType {
- get {
- return RuntimeType ?? Expression.Type;
- }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic conversion operation.
- /// </summary>
- /// <param name="binder">An instance of the <see cref="ConvertBinder"/> that represents the details of the dynamic operation.</param>
- /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public virtual DynamicMetaObject BindConvert(ConvertBinder binder) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return binder.FallbackConvert(this);
- }
-
- /// <summary>
- /// Performs the binding of the dynamic get member operation.
- /// </summary>
- /// <param name="binder">An instance of the <see cref="GetMemberBinder"/> that represents the details of the dynamic operation.</param>
- /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public virtual DynamicMetaObject BindGetMember(GetMemberBinder binder) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return binder.FallbackGetMember(this);
- }
-
- /// <summary>
- /// Performs the binding of the dynamic set member operation.
- /// </summary>
- /// <param name="binder">An instance of the <see cref="SetMemberBinder"/> that represents the details of the dynamic operation.</param>
- /// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set member operation.</param>
- /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public virtual DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return binder.FallbackSetMember(this, value);
- }
-
- /// <summary>
- /// Performs the binding of the dynamic delete member operation.
- /// </summary>
- /// <param name="binder">An instance of the <see cref="DeleteMemberBinder"/> that represents the details of the dynamic operation.</param>
- /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public virtual DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return binder.FallbackDeleteMember(this);
- }
-
- /// <summary>
- /// Performs the binding of the dynamic get index operation.
- /// </summary>
- /// <param name="binder">An instance of the <see cref="GetIndexBinder"/> that represents the details of the dynamic operation.</param>
- /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the get index operation.</param>
- /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public virtual DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return binder.FallbackGetIndex(this, indexes);
- }
-
- /// <summary>
- /// Performs the binding of the dynamic set index operation.
- /// </summary>
- /// <param name="binder">An instance of the <see cref="SetIndexBinder"/> that represents the details of the dynamic operation.</param>
- /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the set index operation.</param>
- /// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set index operation.</param>
- /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public virtual DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return binder.FallbackSetIndex(this, indexes, value);
- }
-
- /// <summary>
- /// Performs the binding of the dynamic delete index operation.
- /// </summary>
- /// <param name="binder">An instance of the <see cref="DeleteIndexBinder"/> that represents the details of the dynamic operation.</param>
- /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the delete index operation.</param>
- /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public virtual DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return binder.FallbackDeleteIndex(this, indexes);
- }
-
- /// <summary>
- /// Performs the binding of the dynamic invoke member operation.
- /// </summary>
- /// <param name="binder">An instance of the <see cref="InvokeMemberBinder"/> that represents the details of the dynamic operation.</param>
- /// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke member operation.</param>
- /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public virtual DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return binder.FallbackInvokeMember(this, args);
- }
-
- /// <summary>
- /// Performs the binding of the dynamic invoke operation.
- /// </summary>
- /// <param name="binder">An instance of the <see cref="InvokeBinder"/> that represents the details of the dynamic operation.</param>
- /// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke operation.</param>
- /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public virtual DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return binder.FallbackInvoke(this, args);
- }
-
- /// <summary>
- /// Performs the binding of the dynamic create instance operation.
- /// </summary>
- /// <param name="binder">An instance of the <see cref="CreateInstanceBinder"/> that represents the details of the dynamic operation.</param>
- /// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the create instance operation.</param>
- /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public virtual DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return binder.FallbackCreateInstance(this, args);
- }
-
- /// <summary>
- /// Performs the binding of the dynamic unary operation.
- /// </summary>
- /// <param name="binder">An instance of the <see cref="UnaryOperationBinder"/> that represents the details of the dynamic operation.</param>
- /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public virtual DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return binder.FallbackUnaryOperation(this);
- }
-
- /// <summary>
- /// Performs the binding of the dynamic binary operation.
- /// </summary>
- /// <param name="binder">An instance of the <see cref="BinaryOperationBinder"/> that represents the details of the dynamic operation.</param>
- /// <param name="arg">An instance of the <see cref="DynamicMetaObject"/> representing the right hand side of the binary operation.</param>
- /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public virtual DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return binder.FallbackBinaryOperation(this, arg);
- }
-
- /// <summary>
- /// Returns the enumeration of all dynamic member names.
- /// </summary>
- /// <returns>The list of dynamic member names.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
- public virtual IEnumerable<string> GetDynamicMemberNames() {
- return new string[0];
- }
-
- /// <summary>
- /// Returns the list of expressions represented by the <see cref="DynamicMetaObject"/> instances.
- /// </summary>
- /// <param name="objects">An array of <see cref="DynamicMetaObject"/> instances to extract expressions from.</param>
- /// <returns>The array of expressions.</returns>
- internal static Expression[] GetExpressions(DynamicMetaObject[] objects) {
- ContractUtils.RequiresNotNull(objects, "objects");
-
- Expression[] res = new Expression[objects.Length];
- for (int i = 0; i < objects.Length; i++) {
- DynamicMetaObject mo = objects[i];
- ContractUtils.RequiresNotNull(mo, "objects");
- Expression expr = mo.Expression;
- ContractUtils.RequiresNotNull(expr, "objects");
- res[i] = expr;
- }
-
- return res;
- }
-
- /// <summary>
- /// Creates a meta-object for the specified object.
- /// </summary>
- /// <param name="value">The object to get a meta-object for.</param>
- /// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param>
- /// <returns>
- /// If the given object implements <see cref="IDynamicMetaObjectProvider"/> and is not a remote object from outside the current AppDomain,
- /// returns the object's specific meta-object returned by <see cref="IDynamicMetaObjectProvider.GetMetaObject"/>. Otherwise a plain new meta-object
- /// with no restrictions is created and returned.
- /// </returns>
- public static DynamicMetaObject Create(object value, Expression expression) {
- ContractUtils.RequiresNotNull(expression, "expression");
-
- IDynamicMetaObjectProvider ido = value as IDynamicMetaObjectProvider;
-#if FEATURE_REMOTING
- if (ido != null && !RemotingServices.IsObjectOutOfAppDomain(value)) {
-#else
- if (ido != null) {
-#endif
- var idoMetaObject = ido.GetMetaObject(expression);
-
- if (idoMetaObject == null ||
- !idoMetaObject.HasValue ||
- idoMetaObject.Value == null ||
- (object)idoMetaObject.Expression != (object)expression) {
- throw Error.InvalidMetaObjectCreated(ido.GetType());
- }
-
- return idoMetaObject;
- } else {
- return new DynamicMetaObject(expression, BindingRestrictions.Empty, value);
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicMetaObjectBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicMetaObjectBinder.cs
deleted file mode 100644
index 899c45338d3..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicMetaObjectBinder.cs
+++ /dev/null
@@ -1,287 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-using Microsoft.Scripting.Ast.Compiler;
-#else
-using System.Linq.Expressions;
-using System.Linq.Expressions.Compiler;
-#endif
-
-#if FEATURE_REMOTING
-using System.Runtime.Remoting;
-#endif
-
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Runtime.CompilerServices;
-
-namespace System.Dynamic {
- /// <summary>
- /// The dynamic call site binder that participates in the <see cref="DynamicMetaObject"/> binding protocol.
- /// </summary>
- /// <remarks>
- /// The <see cref="CallSiteBinder"/> performs the binding of the dynamic operation using the runtime values
- /// as input. On the other hand, the <see cref="DynamicMetaObjectBinder"/> participates in the <see cref="DynamicMetaObject"/>
- /// binding protocol.
- /// </remarks>
- public abstract class DynamicMetaObjectBinder : CallSiteBinder {
-
- #region Public APIs
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DynamicMetaObjectBinder"/> class.
- /// </summary>
- protected DynamicMetaObjectBinder() {
- }
-
- /// <summary>
- /// The result type of the operation.
- /// </summary>
- public virtual Type ReturnType {
- get { return typeof(object); }
- }
-
- /// <summary>
- /// Performs the runtime binding of the dynamic operation on a set of arguments.
- /// </summary>
- /// <param name="args">An array of arguments to the dynamic operation.</param>
- /// <param name="parameters">The array of <see cref="ParameterExpression"/> instances that represent the parameters of the call site in the binding process.</param>
- /// <param name="returnLabel">A LabelTarget used to return the result of the dynamic binding.</param>
- /// <returns>
- /// An Expression that performs tests on the dynamic operation arguments, and
- /// performs the dynamic operation if the tests are valid. If the tests fail on
- /// subsequent occurrences of the dynamic operation, Bind will be called again
- /// to produce a new <see cref="Expression"/> for the new argument types.
- /// </returns>
- public sealed override Expression Bind(object[] args, ReadOnlyCollection<ParameterExpression> parameters, LabelTarget returnLabel) {
- ContractUtils.RequiresNotNull(args, "args");
- ContractUtils.RequiresNotNull(parameters, "parameters");
- ContractUtils.RequiresNotNull(returnLabel, "returnLabel");
- if (args.Length == 0) {
- throw Error.OutOfRange("args.Length", 1);
- }
- if (parameters.Count == 0) {
- throw Error.OutOfRange("parameters.Count", 1);
- }
- if (args.Length != parameters.Count) {
- throw new ArgumentOutOfRangeException("args");
- }
-
- // Ensure that the binder's ReturnType matches CallSite's return
- // type. We do this so meta objects and language binders can
- // compose trees together without needing to insert converts.
- Type expectedResult;
- if (IsStandardBinder) {
- expectedResult = ReturnType;
-
- if (returnLabel.Type != typeof(void) &&
- !TypeUtils.AreReferenceAssignable(returnLabel.Type, expectedResult)) {
- throw Error.BinderNotCompatibleWithCallSite(expectedResult, this, returnLabel.Type);
- }
- } else {
- // Even for non-standard binders, we have to at least make sure
- // it works with the CallSite's type to build the return.
- expectedResult = returnLabel.Type;
- }
-
- DynamicMetaObject target = DynamicMetaObject.Create(args[0], parameters[0]);
- DynamicMetaObject[] metaArgs = CreateArgumentMetaObjects(args, parameters);
-
- DynamicMetaObject binding = Bind(target, metaArgs);
-
- if (binding == null) {
- throw Error.BindingCannotBeNull();
- }
-
- Expression body = binding.Expression;
- BindingRestrictions restrictions = binding.Restrictions;
-
- // Ensure the result matches the expected result type.
- if (expectedResult != typeof(void) &&
- !TypeUtils.AreReferenceAssignable(expectedResult, body.Type)) {
-
- //
- // Blame the last person that handled the result: assume it's
- // the dynamic object (if any), otherwise blame the language.
- //
- if (target.Value is IDynamicMetaObjectProvider) {
- throw Error.DynamicObjectResultNotAssignable(body.Type, target.Value.GetType(), this, expectedResult);
- } else {
- throw Error.DynamicBinderResultNotAssignable(body.Type, this, expectedResult);
- }
- }
-
- // if the target is IDO, standard binders ask it to bind the rule so we may have a target-specific binding.
- // it makes sense to restrict on the target's type in such cases.
- // ideally IDO metaobjects should do this, but they often miss that type of "this" is significant.
- if (IsStandardBinder && args[0] as IDynamicMetaObjectProvider != null) {
- if (restrictions == BindingRestrictions.Empty) {
- throw Error.DynamicBindingNeedsRestrictions(target.Value.GetType(), this);
- }
- }
-
- restrictions = AddRemoteObjectRestrictions(restrictions, args, parameters);
-
- // Add the return
- if (body.NodeType != ExpressionType.Goto) {
- body = Expression.Return(returnLabel, body);
- }
-
- // Finally, add restrictions
- if (restrictions != BindingRestrictions.Empty) {
- body = Expression.IfThen(restrictions.ToExpression(), body);
- }
-
- return body;
- }
-
- private static DynamicMetaObject[] CreateArgumentMetaObjects(object[] args, ReadOnlyCollection<ParameterExpression> parameters) {
- DynamicMetaObject[] mos;
- if (args.Length != 1) {
- mos = new DynamicMetaObject[args.Length - 1];
- for (int i = 1; i < args.Length; i++) {
- mos[i - 1] = DynamicMetaObject.Create(args[i], parameters[i]);
- }
- } else {
- mos = DynamicMetaObject.EmptyMetaObjects;
- }
- return mos;
- }
-
- private static BindingRestrictions AddRemoteObjectRestrictions(BindingRestrictions restrictions, object[] args, ReadOnlyCollection<ParameterExpression> parameters) {
-#if FEATURE_REMOTING
- for (int i = 0; i < parameters.Count; i++) {
- var expr = parameters[i];
- var value = args[i] as MarshalByRefObject;
-
- // special case for MBR objects.
- // when MBR objects are remoted they can have different conversion behavior
- // so bindings created for local and remote objects should not be mixed.
- if (value != null && !IsComObject(value)) {
- BindingRestrictions remotedRestriction;
- if (RemotingServices.IsObjectOutOfAppDomain(value)) {
- remotedRestriction = BindingRestrictions.GetExpressionRestriction(
- Expression.AndAlso(
- Expression.NotEqual(expr, Expression.Constant(null)),
- Expression.Call(
- typeof(RemotingServices).GetMethod("IsObjectOutOfAppDomain"),
- expr
- )
- )
- );
- } else {
- remotedRestriction = BindingRestrictions.GetExpressionRestriction(
- Expression.AndAlso(
- Expression.NotEqual(expr, Expression.Constant(null)),
- Expression.Not(
- Expression.Call(
- typeof(RemotingServices).GetMethod("IsObjectOutOfAppDomain"),
- expr
- )
- )
- )
- );
- }
- restrictions = restrictions.Merge(remotedRestriction);
- }
- }
-#endif
- return restrictions;
- }
-
- /// <summary>
- /// When overridden in the derived class, performs the binding of the dynamic operation.
- /// </summary>
- /// <param name="target">The target of the dynamic operation.</param>
- /// <param name="args">An array of arguments of the dynamic operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public abstract DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args);
-
- /// <summary>
- /// Gets an expression that will cause the binding to be updated. It
- /// indicates that the expression's binding is no longer valid.
- /// This is typically used when the "version" of a dynamic object has
- /// changed.
- /// </summary>
- /// <param name="type">The <see cref="Expression.Type">Type</see> property of the resulting expression; any type is allowed.</param>
- /// <returns>The update expression.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
- public Expression GetUpdateExpression(Type type) {
- return Expression.Goto(CallSiteBinder.UpdateLabel, type);
- }
-
- /// <summary>
- /// Defers the binding of the operation until later time when the runtime values of all dynamic operation arguments have been computed.
- /// </summary>
- /// <param name="target">The target of the dynamic operation.</param>
- /// <param name="args">An array of arguments of the dynamic operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject Defer(DynamicMetaObject target, params DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(target, "target");
-
- if (args == null) {
- return MakeDeferred(target.Restrictions, target);
- } else {
- return MakeDeferred(
- target.Restrictions.Merge(BindingRestrictions.Combine(args)),
- args.AddFirst(target)
- );
- }
- }
-
- /// <summary>
- /// Defers the binding of the operation until later time when the runtime values of all dynamic operation arguments have been computed.
- /// </summary>
- /// <param name="args">An array of arguments of the dynamic operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject Defer(params DynamicMetaObject[] args) {
- return MakeDeferred(BindingRestrictions.Combine(args), args);
- }
-
- private DynamicMetaObject MakeDeferred(BindingRestrictions rs, params DynamicMetaObject[] args) {
- var exprs = DynamicMetaObject.GetExpressions(args);
-
- Type delegateType = DelegateHelpers.MakeDeferredSiteDelegate(args, ReturnType);
-
- // Because we know the arguments match the delegate type (we just created the argument types)
- // we go directly to DynamicExpression.Make to avoid a bunch of unnecessary argument validation
- return new DynamicMetaObject(
- DynamicExpression.Make(ReturnType, delegateType, this, new TrueReadOnlyCollection<Expression>(exprs)),
- rs
- );
- }
-
- #endregion
-
- // used to detect standard MetaObjectBinders.
- internal virtual bool IsStandardBinder {
- get {
- return false;
- }
- }
-
-#if FEATURE_COM
- private static readonly Type ComObjectType = typeof(object).Assembly.GetType("System.__ComObject");
- private static bool IsComObject(object obj) {
- // we can't use System.Runtime.InteropServices.Marshal.IsComObject(obj) since it doesn't work in partial trust
- return obj != null && ComObjectType.IsAssignableFrom(obj.GetType());
- }
-#endif
-
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicObject.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicObject.cs
deleted file mode 100644
index 7da7303d755..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicObject.cs
+++ /dev/null
@@ -1,803 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-#else
-using System.Linq.Expressions;
-#endif
-
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-
-namespace System.Dynamic {
- /// <summary>
- /// Provides a simple class that can be inherited from to create an object with dynamic behavior
- /// at runtime. Subclasses can override the various binder methods (GetMember, SetMember, Call, etc...)
- /// to provide custom behavior that will be invoked at runtime.
- ///
- /// If a method is not overridden then the DynamicObject does not directly support that behavior and
- /// the call site will determine how the binding should be performed.
- /// </summary>
- [Serializable]
- public class DynamicObject : IDynamicMetaObjectProvider {
-
- /// <summary>
- /// Enables derived types to create a new instance of DynamicObject. DynamicObject instances cannot be
- /// directly instantiated because they have no implementation of dynamic behavior.
- /// </summary>
- protected DynamicObject() {
- }
-
- #region Public Virtual APIs
-
- /// <summary>
- /// Provides the implementation of getting a member. Derived classes can override
- /// this method to customize behavior. When not overridden the call site requesting the
- /// binder determines the behavior.
- /// </summary>
- /// <param name="binder">The binder provided by the call site.</param>
- /// <param name="result">The result of the get operation.</param>
- /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
- public virtual bool TryGetMember(GetMemberBinder binder, out object result) {
- result = null;
- return false;
- }
-
- /// <summary>
- /// Provides the implementation of setting a member. Derived classes can override
- /// this method to customize behavior. When not overridden the call site requesting the
- /// binder determines the behavior.
- /// </summary>
- /// <param name="binder">The binder provided by the call site.</param>
- /// <param name="value">The value to set.</param>
- /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
- public virtual bool TrySetMember(SetMemberBinder binder, object value) {
- return false;
- }
-
- /// <summary>
- /// Provides the implementation of deleting a member. Derived classes can override
- /// this method to customize behavior. When not overridden the call site requesting the
- /// binder determines the behavior.
- /// </summary>
- /// <param name="binder">The binder provided by the call site.</param>
- /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
- public virtual bool TryDeleteMember(DeleteMemberBinder binder) {
- return false;
- }
-
- /// <summary>
- /// Provides the implementation of calling a member. Derived classes can override
- /// this method to customize behavior. When not overridden the call site requesting the
- /// binder determines the behavior.
- /// </summary>
- /// <param name="binder">The binder provided by the call site.</param>
- /// <param name="args">The arguments to be used for the invocation.</param>
- /// <param name="result">The result of the invocation.</param>
- /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
- public virtual bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) {
- result = null;
- return false;
- }
-
- /// <summary>
- /// Provides the implementation of converting the DynamicObject to another type. Derived classes
- /// can override this method to customize behavior. When not overridden the call site
- /// requesting the binder determines the behavior.
- /// </summary>
- /// <param name="binder">The binder provided by the call site.</param>
- /// <param name="result">The result of the conversion.</param>
- /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
- public virtual bool TryConvert(ConvertBinder binder, out object result) {
- result = null;
- return false;
- }
-
- /// <summary>
- /// Provides the implementation of creating an instance of the DynamicObject. Derived classes
- /// can override this method to customize behavior. When not overridden the call site requesting
- /// the binder determines the behavior.
- /// </summary>
- /// <param name="binder">The binder provided by the call site.</param>
- /// <param name="args">The arguments used for creation.</param>
- /// <param name="result">The created instance.</param>
- /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
- public virtual bool TryCreateInstance(CreateInstanceBinder binder, object[] args, out object result) {
- result = null;
- return false;
- }
-
- /// <summary>
- /// Provides the implementation of invoking the DynamicObject. Derived classes can
- /// override this method to customize behavior. When not overridden the call site requesting
- /// the binder determines the behavior.
- /// </summary>
- /// <param name="binder">The binder provided by the call site.</param>
- /// <param name="args">The arguments to be used for the invocation.</param>
- /// <param name="result">The result of the invocation.</param>
- /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
- public virtual bool TryInvoke(InvokeBinder binder, object[] args, out object result) {
- result = null;
- return false;
- }
-
- /// <summary>
- /// Provides the implementation of performing a binary operation. Derived classes can
- /// override this method to customize behavior. When not overridden the call site requesting
- /// the binder determines the behavior.
- /// </summary>
- /// <param name="binder">The binder provided by the call site.</param>
- /// <param name="arg">The right operand for the operation.</param>
- /// <param name="result">The result of the operation.</param>
- /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
- public virtual bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result) {
- result = null;
- return false;
- }
-
- /// <summary>
- /// Provides the implementation of performing a unary operation. Derived classes can
- /// override this method to customize behavior. When not overridden the call site requesting
- /// the binder determines the behavior.
- /// </summary>
- /// <param name="binder">The binder provided by the call site.</param>
- /// <param name="result">The result of the operation.</param>
- /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
- public virtual bool TryUnaryOperation(UnaryOperationBinder binder, out object result) {
- result = null;
- return false;
- }
-
- /// <summary>
- /// Provides the implementation of performing a get index operation. Derived classes can
- /// override this method to customize behavior. When not overridden the call site requesting
- /// the binder determines the behavior.
- /// </summary>
- /// <param name="binder">The binder provided by the call site.</param>
- /// <param name="indexes">The indexes to be used.</param>
- /// <param name="result">The result of the operation.</param>
- /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
- public virtual bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) {
- result = null;
- return false;
- }
-
- /// <summary>
- /// Provides the implementation of performing a set index operation. Derived classes can
- /// override this method to custmize behavior. When not overridden the call site requesting
- /// the binder determines the behavior.
- /// </summary>
- /// <param name="binder">The binder provided by the call site.</param>
- /// <param name="indexes">The indexes to be used.</param>
- /// <param name="value">The value to set.</param>
- /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
- public virtual bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) {
- return false;
- }
-
- /// <summary>
- /// Provides the implementation of performing a delete index operation. Derived classes
- /// can override this method to custmize behavior. When not overridden the call site
- /// requesting the binder determines the behavior.
- /// </summary>
- /// <param name="binder">The binder provided by the call site.</param>
- /// <param name="indexes">The indexes to be deleted.</param>
- /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
- public virtual bool TryDeleteIndex(DeleteIndexBinder binder, object[] indexes) {
- return false;
- }
-
- /// <summary>
- /// Returns the enumeration of all dynamic member names.
- /// </summary>
- /// <returns>The list of dynamic member names.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
- public virtual System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames() {
- return new string[0];
- }
- #endregion
-
- #region MetaDynamic
-
- private sealed class MetaDynamic : DynamicMetaObject {
-
- internal MetaDynamic(Expression expression, DynamicObject value)
- : base(expression, BindingRestrictions.Empty, value) {
- }
-
- public override System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames()
- {
- return Value.GetDynamicMemberNames();
- }
-
- public override DynamicMetaObject BindGetMember(GetMemberBinder binder) {
- if (IsOverridden("TryGetMember")) {
- return CallMethodWithResult("TryGetMember", binder, NoArgs, (e) => binder.FallbackGetMember(this, e));
- }
-
- return base.BindGetMember(binder);
- }
-
- public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) {
- if (IsOverridden("TrySetMember")) {
- return CallMethodReturnLast("TrySetMember", binder, NoArgs, value.Expression, (e) => binder.FallbackSetMember(this, value, e));
- }
-
- return base.BindSetMember(binder, value);
- }
-
- public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) {
- if (IsOverridden("TryDeleteMember")) {
- return CallMethodNoResult("TryDeleteMember", binder, NoArgs, (e) => binder.FallbackDeleteMember(this, e));
- }
-
- return base.BindDeleteMember(binder);
- }
-
- public override DynamicMetaObject BindConvert(ConvertBinder binder) {
- if (IsOverridden("TryConvert")) {
- return CallMethodWithResult("TryConvert", binder, NoArgs, (e) => binder.FallbackConvert(this, e));
- }
-
- return base.BindConvert(binder);
- }
-
- public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
- // Generate a tree like:
- //
- // {
- // object result;
- // TryInvokeMember(payload, out result)
- // ? result
- // : TryGetMember(payload, out result)
- // ? FallbackInvoke(result)
- // : fallbackResult
- // }
- //
- // Then it calls FallbackInvokeMember with this tree as the
- // "error", giving the language the option of using this
- // tree or doing .NET binding.
- //
- Fallback fallback = e => binder.FallbackInvokeMember(this, args, e);
-
- var call = BuildCallMethodWithResult(
- "TryInvokeMember",
- binder,
- DynamicMetaObject.GetExpressions(args),
- BuildCallMethodWithResult(
- "TryGetMember",
- new GetBinderAdapter(binder),
- NoArgs,
- fallback(null),
- (e) => binder.FallbackInvoke(e, args, null)
- ),
- null
- );
-
- return fallback(call);
- }
-
-
- public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) {
- if (IsOverridden("TryCreateInstance")) {
- return CallMethodWithResult("TryCreateInstance", binder, DynamicMetaObject.GetExpressions(args), (e) => binder.FallbackCreateInstance(this, args, e));
- }
-
- return base.BindCreateInstance(binder, args);
- }
-
- public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) {
- if (IsOverridden("TryInvoke")) {
- return CallMethodWithResult("TryInvoke", binder, DynamicMetaObject.GetExpressions(args), (e) => binder.FallbackInvoke(this, args, e));
- }
-
- return base.BindInvoke(binder, args);
- }
-
- public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg) {
- if (IsOverridden("TryBinaryOperation")) {
- return CallMethodWithResult("TryBinaryOperation", binder, DynamicMetaObject.GetExpressions(new DynamicMetaObject[] {arg}), (e) => binder.FallbackBinaryOperation(this, arg, e));
- }
-
- return base.BindBinaryOperation(binder, arg);
- }
-
- public override DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder) {
- if (IsOverridden("TryUnaryOperation")) {
- return CallMethodWithResult("TryUnaryOperation", binder, NoArgs, (e) => binder.FallbackUnaryOperation(this, e));
- }
-
- return base.BindUnaryOperation(binder);
- }
-
- public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) {
- if (IsOverridden("TryGetIndex")) {
- return CallMethodWithResult("TryGetIndex", binder, DynamicMetaObject.GetExpressions(indexes), (e) => binder.FallbackGetIndex(this, indexes, e));
- }
-
- return base.BindGetIndex(binder, indexes);
- }
-
- public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) {
- if (IsOverridden("TrySetIndex")) {
- return CallMethodReturnLast("TrySetIndex", binder, DynamicMetaObject.GetExpressions(indexes), value.Expression, (e) => binder.FallbackSetIndex(this, indexes, value, e));
- }
-
- return base.BindSetIndex(binder, indexes, value);
- }
-
- public override DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes) {
- if (IsOverridden("TryDeleteIndex")) {
- return CallMethodNoResult("TryDeleteIndex", binder, DynamicMetaObject.GetExpressions(indexes), (e) => binder.FallbackDeleteIndex(this, indexes, e));
- }
-
- return base.BindDeleteIndex(binder, indexes);
- }
-
- private delegate DynamicMetaObject Fallback(DynamicMetaObject errorSuggestion);
-
- private readonly static Expression[] NoArgs = new Expression[0];
-
- private static Expression[] GetConvertedArgs(params Expression[] args) {
- ReadOnlyCollectionBuilder<Expression> paramArgs = new ReadOnlyCollectionBuilder<Expression>(args.Length);
-
- for (int i = 0; i < args.Length; i++) {
- paramArgs.Add(Expression.Convert(args[i], typeof(object)));
- }
-
- return paramArgs.ToArray();
- }
-
- /// <summary>
- /// Helper method for generating expressions that assign byRef call
- /// parameters back to their original variables
- /// </summary>
- private static Expression ReferenceArgAssign(Expression callArgs, Expression[] args) {
- ReadOnlyCollectionBuilder<Expression> block = null;
-
- for (int i = 0; i < args.Length; i++) {
- ContractUtils.Requires(args[i] is ParameterExpression);
- if (((ParameterExpression)args[i]).IsByRef) {
- if (block == null)
- block = new ReadOnlyCollectionBuilder<Expression>();
-
- block.Add(
- Expression.Assign(
- args[i],
- Expression.Convert(
- Expression.ArrayIndex(
- callArgs,
- Expression.Constant(i)
- ),
- args[i].Type
- )
- )
- );
- }
- }
-
- if (block != null)
- return Expression.Block(block);
- else
- return Expression.Empty();
- }
-
- /// <summary>
- /// Helper method for generating arguments for calling methods
- /// on DynamicObject. parameters is either a list of ParameterExpressions
- /// to be passed to the method as an object[], or NoArgs to signify that
- /// the target method takes no object[] parameter.
- /// </summary>
- private static Expression[] BuildCallArgs(DynamicMetaObjectBinder binder, Expression[] parameters, Expression arg0, Expression arg1) {
- if (!object.ReferenceEquals(parameters, NoArgs))
- return arg1 != null ? new Expression[] { Constant(binder), arg0, arg1 } : new Expression[] { Constant(binder), arg0 };
- else
- return arg1 != null ? new Expression[] { Constant(binder), arg1 } : new Expression[] { Constant(binder) };
- }
-
- private static ConstantExpression Constant(DynamicMetaObjectBinder binder) {
- Type t = binder.GetType();
- while (!t.IsVisible) {
- t = t.BaseType;
- }
- return Expression.Constant(binder, t);
- }
-
- /// <summary>
- /// Helper method for generating a MetaObject which calls a
- /// specific method on Dynamic that returns a result
- /// </summary>
- private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback) {
- return CallMethodWithResult(methodName, binder, args, fallback, null);
- }
-
- /// <summary>
- /// Helper method for generating a MetaObject which calls a
- /// specific method on Dynamic that returns a result
- /// </summary>
- private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback, Fallback fallbackInvoke) {
- //
- // First, call fallback to do default binding
- // This produces either an error or a call to a .NET member
- //
- DynamicMetaObject fallbackResult = fallback(null);
-
- var callDynamic = BuildCallMethodWithResult(methodName, binder, args, fallbackResult, fallbackInvoke);
-
- //
- // Now, call fallback again using our new MO as the error
- // When we do this, one of two things can happen:
- // 1. Binding will succeed, and it will ignore our call to
- // the dynamic method, OR
- // 2. Binding will fail, and it will use the MO we created
- // above.
- //
- return fallback(callDynamic);
- }
-
- /// <summary>
- /// Helper method for generating a MetaObject which calls a
- /// specific method on DynamicObject that returns a result.
- ///
- /// args is either an array of arguments to be passed
- /// to the method as an object[] or NoArgs to signify that
- /// the target method takes no parameters.
- /// </summary>
- private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke) {
- if (!IsOverridden(methodName)) {
- return fallbackResult;
- }
-
- //
- // Build a new expression like:
- // {
- // object result;
- // TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult
- // }
- //
- var result = Expression.Parameter(typeof(object), null);
- ParameterExpression callArgs = methodName != "TryBinaryOperation" ? Expression.Parameter(typeof(object[]), null) : Expression.Parameter(typeof(object), null);
- var callArgsValue = GetConvertedArgs(args);
-
- var resultMO = new DynamicMetaObject(result, BindingRestrictions.Empty);
-
- // Need to add a conversion if calling TryConvert
- if (binder.ReturnType != typeof(object)) {
- Debug.Assert(binder is ConvertBinder && fallbackInvoke == null);
-
- var convert = Expression.Convert(resultMO.Expression, binder.ReturnType);
- // will always be a cast or unbox
- Debug.Assert(convert.Method == null);
-
- // Prepare a good exception message in case the convert will fail
- string convertFailed = Strings.DynamicObjectResultNotAssignable(
- "{0}",
- this.Value.GetType(),
- binder.GetType(),
- binder.ReturnType
- );
-
-#if MONO // referencesource version
- Expression condition;
- // If the return type can not be assigned null then just check for type assignablity otherwise allow null.
- if (binder.ReturnType.IsValueType && Nullable.GetUnderlyingType(binder.ReturnType) == null) {
- condition = Expression.TypeIs(resultMO.Expression, binder.ReturnType);
- }
- else {
- condition = Expression.OrElse(
- Expression.Equal(resultMO.Expression, Expression.Constant(null)),
- Expression.TypeIs(resultMO.Expression, binder.ReturnType));
- }
-
- var checkedConvert = Expression.Condition(
- condition,
- convert,
- Expression.Throw(
- Expression.New(typeof(InvalidCastException).GetConstructor(new Type[]{typeof(string)}),
- Expression.Call(
- typeof(string).GetMethod("Format", new Type[] {typeof(string), typeof(object[])}),
- Expression.Constant(convertFailed),
- Expression.NewArrayInit(typeof(object),
- Expression.Condition(
- Expression.Equal(resultMO.Expression, Expression.Constant(null)),
- Expression.Constant("null"),
- Expression.Call(
- resultMO.Expression,
- typeof(object).GetMethod("GetType")
- ),
- typeof(object)
- )
- )
- )
- ),
- binder.ReturnType
- ),
- binder.ReturnType
- );
-#else
- var checkedConvert = Expression.Condition(
- Expression.TypeIs(resultMO.Expression, binder.ReturnType),
- convert,
- Expression.Throw(
- Expression.New(typeof(InvalidCastException).GetConstructor(new Type[]{typeof(string)}),
- Expression.Call(
- typeof(string).GetMethod("Format", new Type[] {typeof(string), typeof(object)}),
- Expression.Constant(convertFailed),
- Expression.Condition(
- Expression.Equal(resultMO.Expression, Expression.Constant(null)),
- Expression.Constant("null"),
- Expression.Call(
- resultMO.Expression,
- typeof(object).GetMethod("GetType")
- ),
- typeof(object)
- )
- )
- ),
- binder.ReturnType
- ),
- binder.ReturnType
- );
-#endif
-
- resultMO = new DynamicMetaObject(checkedConvert, resultMO.Restrictions);
- }
-
- if (fallbackInvoke != null) {
- resultMO = fallbackInvoke(resultMO);
- }
-
- var callDynamic = new DynamicMetaObject(
- Expression.Block(
- new[] { result, callArgs },
- methodName != "TryBinaryOperation" ? Expression.Assign(callArgs, Expression.NewArrayInit(typeof(object), callArgsValue)) : Expression.Assign(callArgs, callArgsValue[0]),
- Expression.Condition(
- Expression.Call(
- GetLimitedSelf(),
- typeof(DynamicObject).GetMethod(methodName),
- BuildCallArgs(
- binder,
- args,
- callArgs,
- result
- )
- ),
- Expression.Block(
- methodName != "TryBinaryOperation" ? ReferenceArgAssign(callArgs, args) : Expression.Empty(),
- resultMO.Expression
- ),
- fallbackResult.Expression,
- binder.ReturnType
- )
- ),
- GetRestrictions().Merge(resultMO.Restrictions).Merge(fallbackResult.Restrictions)
- );
- return callDynamic;
- }
-
-
- /// <summary>
- /// Helper method for generating a MetaObject which calls a
- /// specific method on Dynamic, but uses one of the arguments for
- /// the result.
- ///
- /// args is either an array of arguments to be passed
- /// to the method as an object[] or NoArgs to signify that
- /// the target method takes no parameters.
- /// </summary>
- private DynamicMetaObject CallMethodReturnLast(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Expression value, Fallback fallback) {
- //
- // First, call fallback to do default binding
- // This produces either an error or a call to a .NET member
- //
- DynamicMetaObject fallbackResult = fallback(null);
-
- //
- // Build a new expression like:
- // {
- // object result;
- // TrySetMember(payload, result = value) ? result : fallbackResult
- // }
- //
-
- var result = Expression.Parameter(typeof(object), null);
- var callArgs = Expression.Parameter(typeof(object[]), null);
- var callArgsValue = GetConvertedArgs(args);
-
- var callDynamic = new DynamicMetaObject(
- Expression.Block(
- new[] { result, callArgs },
- Expression.Assign(callArgs, Expression.NewArrayInit(typeof(object), callArgsValue)),
- Expression.Condition(
- Expression.Call(
- GetLimitedSelf(),
- typeof(DynamicObject).GetMethod(methodName),
- BuildCallArgs(
- binder,
- args,
- callArgs,
- Expression.Assign(result, Expression.Convert(value, typeof(object)))
- )
- ),
- Expression.Block(
- ReferenceArgAssign(callArgs, args),
- result
- ),
- fallbackResult.Expression,
- typeof(object)
- )
- ),
- GetRestrictions().Merge(fallbackResult.Restrictions)
- );
-
- //
- // Now, call fallback again using our new MO as the error
- // When we do this, one of two things can happen:
- // 1. Binding will succeed, and it will ignore our call to
- // the dynamic method, OR
- // 2. Binding will fail, and it will use the MO we created
- // above.
- //
- return fallback(callDynamic);
- }
-
-
- /// <summary>
- /// Helper method for generating a MetaObject which calls a
- /// specific method on Dynamic, but uses one of the arguments for
- /// the result.
- ///
- /// args is either an array of arguments to be passed
- /// to the method as an object[] or NoArgs to signify that
- /// the target method takes no parameters.
- /// </summary>
- private DynamicMetaObject CallMethodNoResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback) {
- //
- // First, call fallback to do default binding
- // This produces either an error or a call to a .NET member
- //
- DynamicMetaObject fallbackResult = fallback(null);
- var callArgs = Expression.Parameter(typeof(object[]), null);
- var callArgsValue = GetConvertedArgs(args);
-
- //
- // Build a new expression like:
- // if (TryDeleteMember(payload)) { } else { fallbackResult }
- //
- var callDynamic = new DynamicMetaObject(
- Expression.Block(
- new[] { callArgs },
- Expression.Assign(callArgs, Expression.NewArrayInit(typeof(object), callArgsValue)),
- Expression.Condition(
- Expression.Call(
- GetLimitedSelf(),
- typeof(DynamicObject).GetMethod(methodName),
- BuildCallArgs(
- binder,
- args,
- callArgs,
- null
- )
- ),
- Expression.Block(
- ReferenceArgAssign(callArgs, args),
- Expression.Empty()
- ),
- fallbackResult.Expression,
- typeof(void)
- )
- ),
- GetRestrictions().Merge(fallbackResult.Restrictions)
- );
-
- //
- // Now, call fallback again using our new MO as the error
- // When we do this, one of two things can happen:
- // 1. Binding will succeed, and it will ignore our call to
- // the dynamic method, OR
- // 2. Binding will fail, and it will use the MO we created
- // above.
- //
- return fallback(callDynamic);
- }
-
- /// <summary>
- /// Checks if the derived type has overridden the specified method. If there is no
- /// implementation for the method provided then Dynamic falls back to the base class
- /// behavior which lets the call site determine how the binder is performed.
- /// </summary>
- private bool IsOverridden(string method) {
- var methods = Value.GetType().GetMember(method, MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance);
-
- foreach (MethodInfo mi in methods) {
- if (mi.DeclaringType != typeof(DynamicObject) && mi.GetBaseDefinition().DeclaringType == typeof(DynamicObject)) {
- return true;
- }
- }
-
- return false;
- }
-
- /// <summary>
- /// Returns a Restrictions object which includes our current restrictions merged
- /// with a restriction limiting our type
- /// </summary>
- private BindingRestrictions GetRestrictions() {
- Debug.Assert(Restrictions == BindingRestrictions.Empty, "We don't merge, restrictions are always empty");
-
- return BindingRestrictions.GetTypeRestriction(this);
- }
-
- /// <summary>
- /// Returns our Expression converted to DynamicObject
- /// </summary>
- private Expression GetLimitedSelf() {
- // Convert to DynamicObject rather than LimitType, because
- // the limit type might be non-public.
- if (TypeUtils.AreEquivalent(Expression.Type, typeof(DynamicObject))) {
- return Expression;
- }
- return Expression.Convert(Expression, typeof(DynamicObject));
- }
-
- private new DynamicObject Value {
- get {
- return (DynamicObject)base.Value;
- }
- }
-
- // It is okay to throw NotSupported from this binder. This object
- // is only used by DynamicObject.GetMember--it is not expected to
- // (and cannot) implement binding semantics. It is just so the DO
- // can use the Name and IgnoreCase properties.
- private sealed class GetBinderAdapter : GetMemberBinder {
- internal GetBinderAdapter(InvokeMemberBinder binder)
- : base(binder.Name, binder.IgnoreCase) {
- }
-
- public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) {
- throw new NotSupportedException();
- }
- }
- }
-
- #endregion
-
- #region IDynamicMetaObjectProvider Members
-
- /// <summary>
- /// The provided MetaObject will dispatch to the Dynamic virtual methods.
- /// The object can be encapsulated inside of another MetaObject to
- /// provide custom behavior for individual actions.
- /// </summary>
- public virtual DynamicMetaObject GetMetaObject(Expression parameter) {
- return new MetaDynamic(parameter, this);
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/ExpandoClass.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/ExpandoClass.cs
deleted file mode 100644
index 927dab7fbf1..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/ExpandoClass.cs
+++ /dev/null
@@ -1,183 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Text;
-
-namespace System.Dynamic {
- /// <summary>
- /// Represents a dynamically assigned class. Expando objects which share the same
- /// members will share the same class. Classes are dynamically assigned as the
- /// expando object gains members.
- /// </summary>
- internal class ExpandoClass {
- private readonly string[] _keys; // list of names associated with each element in the data array, sorted
- private readonly int _hashCode; // pre-calculated hash code of all the keys the class contains
- private Dictionary<int, List<WeakReference>> _transitions; // cached transitions
-
- private const int EmptyHashCode = 6551; // hash code of the empty ExpandoClass.
-
- internal static ExpandoClass Empty = new ExpandoClass(); // The empty Expando class - all Expando objects start off w/ this class.
-
- /// <summary>
- /// Constructs the empty ExpandoClass. This is the class used when an
- /// empty Expando object is initially constructed.
- /// </summary>
- internal ExpandoClass() {
- _hashCode = EmptyHashCode;
- _keys = new string[0];
- }
-
- /// <summary>
- /// Constructs a new ExpandoClass that can hold onto the specified keys. The
- /// keys must be sorted ordinally. The hash code must be precalculated for
- /// the keys.
- /// </summary>
- internal ExpandoClass(string[] keys, int hashCode) {
- _hashCode = hashCode;
- _keys = keys;
- }
-
- /// <summary>
- /// Finds or creates a new ExpandoClass given the existing set of keys
- /// in this ExpandoClass plus the new key to be added. Members in an
- /// ExpandoClass are always stored case sensitively.
- /// </summary>
- internal ExpandoClass FindNewClass(string newKey) {
- // just XOR the newKey hash code
- int hashCode = _hashCode ^ newKey.GetHashCode();
-
- lock (this) {
- List<WeakReference> infos = GetTransitionList(hashCode);
-
- for (int i = 0; i < infos.Count; i++) {
- ExpandoClass klass = infos[i].Target as ExpandoClass;
- if (klass == null) {
- infos.RemoveAt(i);
- i--;
- continue;
- }
-
- if (string.Equals(klass._keys[klass._keys.Length - 1], newKey, StringComparison.Ordinal)) {
- // the new key is the key we added in this transition
- return klass;
- }
- }
-
- // no applicable transition, create a new one
- string[] keys = new string[_keys.Length + 1];
- Array.Copy(_keys, keys, _keys.Length);
- keys[_keys.Length] = newKey;
- ExpandoClass ec = new ExpandoClass(keys, hashCode);
-
- infos.Add(new WeakReference(ec));
- return ec;
- }
- }
-
- /// <summary>
- /// Gets the lists of transitions that are valid from this ExpandoClass
- /// to an ExpandoClass whos keys hash to the apporopriate hash code.
- /// </summary>
- private List<WeakReference> GetTransitionList(int hashCode) {
- if (_transitions == null) {
- _transitions = new Dictionary<int, List<WeakReference>>();
- }
-
- List<WeakReference> infos;
- if (!_transitions.TryGetValue(hashCode, out infos)) {
- _transitions[hashCode] = infos = new List<WeakReference>();
- }
-
- return infos;
- }
-
- /// <summary>
- /// Gets the index at which the value should be stored for the specified name.
- /// </summary>
- internal int GetValueIndex(string name, bool caseInsensitive, ExpandoObject obj) {
- if (caseInsensitive) {
- return GetValueIndexCaseInsensitive(name, obj);
- } else {
- return GetValueIndexCaseSensitive(name);
- }
- }
-
- /// <summary>
- /// Gets the index at which the value should be stored for the specified name
- /// case sensitively. Returns the index even if the member is marked as deleted.
- /// </summary>
- internal int GetValueIndexCaseSensitive(string name) {
- for (int i = 0; i < _keys.Length; i++) {
- if (string.Equals(
- _keys[i],
- name,
- StringComparison.Ordinal)) {
- return i;
- }
- }
- return ExpandoObject.NoMatch;
- }
-
- /// <summary>
- /// Gets the index at which the value should be stored for the specified name,
- /// the method is only used in the case-insensitive case.
- /// </summary>
- /// <param name="name">the name of the member</param>
- /// <param name="obj">The ExpandoObject associated with the class
- /// that is used to check if a member has been deleted.</param>
- /// <returns>
- /// the exact match if there is one
- /// if there is exactly one member with case insensitive match, return it
- /// otherwise we throw AmbiguousMatchException.
- /// </returns>
- private int GetValueIndexCaseInsensitive(string name, ExpandoObject obj) {
- int caseInsensitiveMatch = ExpandoObject.NoMatch; //the location of the case-insensitive matching member
- lock (obj.LockObject) {
- for (int i = _keys.Length - 1; i >= 0; i--) {
- if (string.Equals(
- _keys[i],
- name,
- StringComparison.OrdinalIgnoreCase)) {
- //if the matching member is deleted, continue searching
- if (!obj.IsDeletedMember(i)) {
- if (caseInsensitiveMatch == ExpandoObject.NoMatch) {
- caseInsensitiveMatch = i;
- } else {
- //Ambigous match, stop searching
- return ExpandoObject.AmbiguousMatchFound;
- }
- }
- }
- }
- }
- //There is exactly one member with case insensitive match.
- return caseInsensitiveMatch;
- }
-
- /// <summary>
- /// Gets the names of the keys that can be stored in the Expando class. The
- /// list is sorted ordinally.
- /// </summary>
- internal string[] Keys {
- get {
- return _keys;
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/ExpandoObject.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/ExpandoObject.cs
deleted file mode 100644
index 5f452afc3f4..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/ExpandoObject.cs
+++ /dev/null
@@ -1,1097 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-using Microsoft.Scripting.Utils;
-#else
-using System.Linq.Expressions;
-#endif
-
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Dynamic;
-using System.Dynamic.Utils;
-using System.Runtime.CompilerServices;
-
-namespace System.Dynamic {
- /// <summary>
- /// Represents an object with members that can be dynamically added and removed at runtime.
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
- public sealed class ExpandoObject : IDynamicMetaObjectProvider, IDictionary<string, object>, INotifyPropertyChanged {
- internal readonly object LockObject; // the readonly field is used for locking the Expando object
- private ExpandoData _data; // the data currently being held by the Expando object
- private int _count; // the count of available members
-
- internal readonly static object Uninitialized = new object(); // A marker object used to identify that a value is uninitialized.
-
- internal const int AmbiguousMatchFound = -2; // The value is used to indicate there exists ambiguous match in the Expando object
- internal const int NoMatch = -1; // The value is used to indicate there is no matching member
-
- private PropertyChangedEventHandler _propertyChanged;
-
- /// <summary>
- /// Creates a new ExpandoObject with no members.
- /// </summary>
- public ExpandoObject() {
- _data = ExpandoData.Empty;
- LockObject = new object();
- }
-
- #region Get/Set/Delete Helpers
-
- /// <summary>
- /// Try to get the data stored for the specified class at the specified index. If the
- /// class has changed a full lookup for the slot will be performed and the correct
- /// value will be retrieved.
- /// </summary>
- internal bool TryGetValue(object indexClass, int index, string name, bool ignoreCase, out object value) {
- // read the data now. The data is immutable so we get a consistent view.
- // If there's a concurrent writer they will replace data and it just appears
- // that we won the race
- ExpandoData data = _data;
- if (data.Class != indexClass || ignoreCase) {
- /* Re-search for the index matching the name here if
- * 1) the class has changed, we need to get the correct index and return
- * the value there.
- * 2) the search is case insensitive:
- * a. the member specified by index may be deleted, but there might be other
- * members matching the name if the binder is case insensitive.
- * b. the member that exactly matches the name didn't exist before and exists now,
- * need to find the exact match.
- */
- index = data.Class.GetValueIndex(name, ignoreCase, this);
- if (index == ExpandoObject.AmbiguousMatchFound) {
- throw Error.AmbiguousMatchInExpandoObject(name);
- }
- }
-
- if (index == ExpandoObject.NoMatch) {
- value = null;
- return false;
- }
-
- // Capture the value into a temp, so it doesn't get mutated after we check
- // for Uninitialized.
- object temp = data[index];
- if (temp == Uninitialized) {
- value = null;
- return false;
- }
-
- // index is now known to be correct
- value = temp;
- return true;
- }
-
- /// <summary>
- /// Sets the data for the specified class at the specified index. If the class has
- /// changed then a full look for the slot will be performed. If the new class does
- /// not have the provided slot then the Expando's class will change. Only case sensitive
- /// setter is supported in ExpandoObject.
- /// </summary>
- internal void TrySetValue(object indexClass, int index, object value, string name, bool ignoreCase, bool add) {
- ExpandoData data;
- object oldValue;
-
- lock (LockObject) {
- data = _data;
-
- if (data.Class != indexClass || ignoreCase) {
- // The class has changed or we are doing a case-insensitive search,
- // we need to get the correct index and set the value there. If we
- // don't have the value then we need to promote the class - that
- // should only happen when we have multiple concurrent writers.
- index = data.Class.GetValueIndex(name, ignoreCase, this);
- if (index == ExpandoObject.AmbiguousMatchFound) {
- throw Error.AmbiguousMatchInExpandoObject(name);
- }
- if (index == ExpandoObject.NoMatch) {
- // Before creating a new class with the new member, need to check
- // if there is the exact same member but is deleted. We should reuse
- // the class if there is such a member.
- int exactMatch = ignoreCase ?
- data.Class.GetValueIndexCaseSensitive(name) :
- index;
- if (exactMatch != ExpandoObject.NoMatch) {
- Debug.Assert(data[exactMatch] == Uninitialized);
- index = exactMatch;
- } else {
- ExpandoClass newClass = data.Class.FindNewClass(name);
- data = PromoteClassCore(data.Class, newClass);
- // After the class promotion, there must be an exact match,
- // so we can do case-sensitive search here.
- index = data.Class.GetValueIndexCaseSensitive(name);
- Debug.Assert(index != ExpandoObject.NoMatch);
- }
- }
- }
-
- // Setting an uninitialized member increases the count of available members
- oldValue = data[index];
- if (oldValue == Uninitialized) {
- _count++;
- } else if (add) {
- throw Error.SameKeyExistsInExpando(name);
- }
-
- data[index] = value;
- }
-
- // Notify property changed, outside of the lock.
- var propertyChanged = _propertyChanged;
- if (propertyChanged != null && value != oldValue) {
- // Use the canonical case for the key.
- propertyChanged(this, new PropertyChangedEventArgs(data.Class.Keys[index]));
- }
- }
-
- /// <summary>
- /// Deletes the data stored for the specified class at the specified index.
- /// </summary>
- internal bool TryDeleteValue(object indexClass, int index, string name, bool ignoreCase, object deleteValue) {
- ExpandoData data;
- lock (LockObject) {
- data = _data;
-
- if (data.Class != indexClass || ignoreCase) {
- // the class has changed or we are doing a case-insensitive search,
- // we need to get the correct index. If there is no associated index
- // we simply can't have the value and we return false.
- index = data.Class.GetValueIndex(name, ignoreCase, this);
- if (index == ExpandoObject.AmbiguousMatchFound) {
- throw Error.AmbiguousMatchInExpandoObject(name);
- }
- }
- if (index == ExpandoObject.NoMatch) {
- return false;
- }
-
- object oldValue = data[index];
- if (oldValue == Uninitialized) {
- return false;
- }
-
- // Make sure the value matches, if requested.
- //
- // It's a shame we have to call Equals with the lock held but
- // there doesn't seem to be a good way around that, and
- // ConcurrentDictionary in mscorlib does the same thing.
- if (deleteValue != Uninitialized && !object.Equals(oldValue, deleteValue)) {
- return false;
- }
-
- data[index] = Uninitialized;
-
- // Deleting an available member decreases the count of available members
- _count--;
- }
-
- // Notify property changed, outside of the lock.
- var propertyChanged = _propertyChanged;
- if (propertyChanged != null) {
- // Use the canonical case for the key.
- propertyChanged(this, new PropertyChangedEventArgs(data.Class.Keys[index]));
- }
-
- return true;
- }
-
- /// <summary>
- /// Returns true if the member at the specified index has been deleted,
- /// otherwise false. Call this function holding the lock.
- /// </summary>
- internal bool IsDeletedMember(int index) {
- Debug.Assert(index >= 0 && index <= _data.Length);
-
- if (index == _data.Length) {
- // The member is a newly added by SetMemberBinder and not in data yet
- return false;
- }
-
- return _data[index] == ExpandoObject.Uninitialized;
- }
-
- /// <summary>
- /// Exposes the ExpandoClass which we've associated with this
- /// Expando object. Used for type checks in rules.
- /// </summary>
- internal ExpandoClass Class {
- get {
- return _data.Class;
- }
- }
-
- /// <summary>
- /// Promotes the class from the old type to the new type and returns the new
- /// ExpandoData object.
- /// </summary>
- private ExpandoData PromoteClassCore(ExpandoClass oldClass, ExpandoClass newClass) {
- Debug.Assert(oldClass != newClass);
-
- lock (LockObject) {
- if (_data.Class == oldClass) {
- _data = _data.UpdateClass(newClass);
- }
- return _data;
- }
- }
-
- /// <summary>
- /// Internal helper to promote a class. Called from our RuntimeOps helper. This
- /// version simply doesn't expose the ExpandoData object which is a private
- /// data structure.
- /// </summary>
- internal void PromoteClass(object oldClass, object newClass) {
- PromoteClassCore((ExpandoClass)oldClass, (ExpandoClass)newClass);
- }
-
- #endregion
-
- #region IDynamicMetaObjectProvider Members
-
- DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) {
- return new MetaExpando(parameter, this);
- }
- #endregion
-
- #region Helper methods
- private void TryAddMember(string key, object value) {
- ContractUtils.RequiresNotNull(key, "key");
- // Pass null to the class, which forces lookup.
- TrySetValue(null, -1, value, key, false, true);
- }
-
- private bool TryGetValueForKey(string key, out object value) {
- // Pass null to the class, which forces lookup.
- return TryGetValue(null, -1, key, false, out value);
- }
-
- private bool ExpandoContainsKey(string key) {
- return _data.Class.GetValueIndexCaseSensitive(key) >= 0;
- }
-
- // We create a non-generic type for the debug view for each different collection type
- // that uses DebuggerTypeProxy, instead of defining a generic debug view type and
- // using different instantiations. The reason for this is that support for generics
- // with using DebuggerTypeProxy is limited. For C#, DebuggerTypeProxy supports only
- // open types (from MSDN http://msdn.microsoft.com/en-us/library/d8eyd8zc.aspx).
- private sealed class KeyCollectionDebugView {
- private ICollection<string> collection;
- public KeyCollectionDebugView(ICollection<string> collection) {
- Debug.Assert(collection != null);
- this.collection = collection;
- }
-
- [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public string[] Items {
- get {
- string[] items = new string[collection.Count];
- collection.CopyTo(items, 0);
- return items;
- }
- }
- }
-
- [DebuggerTypeProxy(typeof(KeyCollectionDebugView))]
- [DebuggerDisplay("Count = {Count}")]
- private class KeyCollection : ICollection<string> {
- private readonly ExpandoObject _expando;
- private readonly int _expandoVersion;
- private readonly int _expandoCount;
- private readonly ExpandoData _expandoData;
-
- internal KeyCollection(ExpandoObject expando) {
- lock (expando.LockObject) {
- _expando = expando;
- _expandoVersion = expando._data.Version;
- _expandoCount = expando._count;
- _expandoData = expando._data;
- }
- }
-
- private void CheckVersion() {
- if (_expando._data.Version != _expandoVersion || _expandoData != _expando._data) {
- //the underlying expando object has changed
- throw Error.CollectionModifiedWhileEnumerating();
- }
- }
-
- #region ICollection<string> Members
-
- public void Add(string item) {
- throw Error.CollectionReadOnly();
- }
-
- public void Clear() {
- throw Error.CollectionReadOnly();
- }
-
- public bool Contains(string item) {
- lock (_expando.LockObject) {
- CheckVersion();
- return _expando.ExpandoContainsKey(item);
- }
- }
-
- public void CopyTo(string[] array, int arrayIndex) {
- ContractUtils.RequiresNotNull(array, "array");
- ContractUtils.RequiresArrayRange(array, arrayIndex, _expandoCount, "arrayIndex", "Count");
- lock (_expando.LockObject) {
- CheckVersion();
- ExpandoData data = _expando._data;
- for (int i = 0; i < data.Class.Keys.Length; i++) {
- if (data[i] != Uninitialized) {
- array[arrayIndex++] = data.Class.Keys[i];
- }
- }
- }
- }
-
- public int Count {
- get {
- CheckVersion();
- return _expandoCount;
- }
- }
-
- public bool IsReadOnly {
- get { return true; }
- }
-
- public bool Remove(string item) {
- throw Error.CollectionReadOnly();
- }
-
- #endregion
-
- #region IEnumerable<string> Members
-
- public IEnumerator<string> GetEnumerator() {
- for (int i = 0, n = _expandoData.Class.Keys.Length; i < n; i++) {
- CheckVersion();
- if (_expandoData[i] != Uninitialized) {
- yield return _expandoData.Class.Keys[i];
- }
- }
- }
-
- #endregion
-
- #region IEnumerable Members
-
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
- return GetEnumerator();
- }
-
- #endregion
- }
-
- // We create a non-generic type for the debug view for each different collection type
- // that uses DebuggerTypeProxy, instead of defining a generic debug view type and
- // using different instantiations. The reason for this is that support for generics
- // with using DebuggerTypeProxy is limited. For C#, DebuggerTypeProxy supports only
- // open types (from MSDN http://msdn.microsoft.com/en-us/library/d8eyd8zc.aspx).
- private sealed class ValueCollectionDebugView {
- private ICollection<object> collection;
- public ValueCollectionDebugView(ICollection<object> collection) {
- Debug.Assert(collection != null);
- this.collection = collection;
- }
-
- [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public object[] Items {
- get {
- object[] items = new object[collection.Count];
- collection.CopyTo(items, 0);
- return items;
- }
- }
- }
-
- [DebuggerTypeProxy(typeof(ValueCollectionDebugView))]
- [DebuggerDisplay("Count = {Count}")]
- private class ValueCollection : ICollection<object> {
- private readonly ExpandoObject _expando;
- private readonly int _expandoVersion;
- private readonly int _expandoCount;
- private readonly ExpandoData _expandoData;
-
- internal ValueCollection(ExpandoObject expando) {
- lock (expando.LockObject) {
- _expando = expando;
- _expandoVersion = expando._data.Version;
- _expandoCount = expando._count;
- _expandoData = expando._data;
- }
- }
-
- private void CheckVersion() {
- if (_expando._data.Version != _expandoVersion || _expandoData != _expando._data) {
- //the underlying expando object has changed
- throw Error.CollectionModifiedWhileEnumerating();
- }
- }
-
- #region ICollection<string> Members
-
- public void Add(object item) {
- throw Error.CollectionReadOnly();
- }
-
- public void Clear() {
- throw Error.CollectionReadOnly();
- }
-
- public bool Contains(object item) {
- lock (_expando.LockObject) {
- CheckVersion();
-
- ExpandoData data = _expando._data;
- for (int i = 0; i < data.Class.Keys.Length; i++) {
-
- // See comment in TryDeleteValue; it's okay to call
- // object.Equals with the lock held.
- if (object.Equals(data[i], item)) {
- return true;
- }
- }
- return false;
- }
- }
-
- public void CopyTo(object[] array, int arrayIndex) {
- ContractUtils.RequiresNotNull(array, "array");
- ContractUtils.RequiresArrayRange(array, arrayIndex, _expandoCount, "arrayIndex", "Count");
- lock (_expando.LockObject) {
- CheckVersion();
- ExpandoData data = _expando._data;
- for (int i = 0; i < data.Class.Keys.Length; i++) {
- if (data[i] != Uninitialized) {
- array[arrayIndex++] = data[i];
- }
- }
- }
- }
-
- public int Count {
- get {
- CheckVersion();
- return _expandoCount;
- }
- }
-
- public bool IsReadOnly {
- get { return true; }
- }
-
- public bool Remove(object item) {
- throw Error.CollectionReadOnly();
- }
-
- #endregion
-
- #region IEnumerable<string> Members
-
- public IEnumerator<object> GetEnumerator() {
- ExpandoData data = _expando._data;
- for (int i = 0; i < data.Class.Keys.Length; i++) {
- CheckVersion();
- // Capture the value into a temp so we don't inadvertently
- // return Uninitialized.
- object temp = data[i];
- if (temp != Uninitialized) {
- yield return temp;
- }
- }
- }
-
- #endregion
-
- #region IEnumerable Members
-
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
- return GetEnumerator();
- }
-
- #endregion
- }
-
- #endregion
-
- #region IDictionary<string, object> Members
- ICollection<string> IDictionary<string, object>.Keys {
- get {
- return new KeyCollection(this);
- }
- }
-
- ICollection<object> IDictionary<string, object>.Values {
- get {
- return new ValueCollection(this);
- }
- }
-
- object IDictionary<string, object>.this[string key] {
- get {
- object value;
- if (!TryGetValueForKey(key, out value)) {
- throw Error.KeyDoesNotExistInExpando(key);
- }
- return value;
- }
- set {
- ContractUtils.RequiresNotNull(key, "key");
- // Pass null to the class, which forces lookup.
- TrySetValue(null, -1, value, key, false, false);
- }
- }
-
- void IDictionary<string, object>.Add(string key, object value) {
- this.TryAddMember(key, value);
- }
-
- bool IDictionary<string, object>.ContainsKey(string key) {
- ContractUtils.RequiresNotNull(key, "key");
-
- ExpandoData data = _data;
- int index = data.Class.GetValueIndexCaseSensitive(key);
- return index >= 0 && data[index] != Uninitialized;
- }
-
- bool IDictionary<string, object>.Remove(string key) {
- ContractUtils.RequiresNotNull(key, "key");
- // Pass null to the class, which forces lookup.
- return TryDeleteValue(null, -1, key, false, Uninitialized);
- }
-
- bool IDictionary<string, object>.TryGetValue(string key, out object value) {
- return TryGetValueForKey(key, out value);
- }
-
- #endregion
-
- #region ICollection<KeyValuePair<string, object>> Members
- int ICollection<KeyValuePair<string, object>>.Count {
- get {
- return _count;
- }
- }
-
- bool ICollection<KeyValuePair<string, object>>.IsReadOnly {
- get { return false; }
- }
-
- void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item) {
- TryAddMember(item.Key, item.Value);
- }
-
- void ICollection<KeyValuePair<string, object>>.Clear() {
- // We remove both class and data!
- ExpandoData data;
- lock (LockObject) {
- data = _data;
- _data = ExpandoData.Empty;
- _count = 0;
- }
-
- // Notify property changed for all properties.
- var propertyChanged = _propertyChanged;
- if (propertyChanged != null) {
- for (int i = 0, n = data.Class.Keys.Length; i < n; i++) {
- if (data[i] != Uninitialized) {
- propertyChanged(this, new PropertyChangedEventArgs(data.Class.Keys[i]));
- }
- }
- }
- }
-
- bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item) {
- object value;
- if (!TryGetValueForKey(item.Key, out value)) {
- return false;
- }
-
- return object.Equals(value, item.Value);
- }
-
- void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) {
- ContractUtils.RequiresNotNull(array, "array");
- ContractUtils.RequiresArrayRange(array, arrayIndex, _count, "arrayIndex", "Count");
-
- // We want this to be atomic and not throw
- lock (LockObject) {
- foreach (KeyValuePair<string, object> item in this) {
- array[arrayIndex++] = item;
- }
- }
- }
-
- bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item) {
- return TryDeleteValue(null, -1, item.Key, false, item.Value);
- }
- #endregion
-
- #region IEnumerable<KeyValuePair<string, object>> Member
-
- IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() {
- ExpandoData data = _data;
- return GetExpandoEnumerator(data, data.Version);
- }
-
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
- ExpandoData data = _data;
- return GetExpandoEnumerator(data, data.Version);
- }
-
- // Note: takes the data and version as parameters so they will be
- // captured before the first call to MoveNext().
- private IEnumerator<KeyValuePair<string, object>> GetExpandoEnumerator(ExpandoData data, int version) {
- for (int i = 0; i < data.Class.Keys.Length; i++) {
- if (_data.Version != version || data != _data) {
- // The underlying expando object has changed:
- // 1) the version of the expando data changed
- // 2) the data object is changed
- throw Error.CollectionModifiedWhileEnumerating();
- }
- // Capture the value into a temp so we don't inadvertently
- // return Uninitialized.
- object temp = data[i];
- if (temp != Uninitialized) {
- yield return new KeyValuePair<string,object>(data.Class.Keys[i], temp);
- }
- }
- }
- #endregion
-
- #region MetaExpando
-
- private class MetaExpando : DynamicMetaObject {
- public MetaExpando(Expression expression, ExpandoObject value)
- : base(expression, BindingRestrictions.Empty, value) {
- }
-
- private DynamicMetaObject BindGetOrInvokeMember(DynamicMetaObjectBinder binder, string name, bool ignoreCase, DynamicMetaObject fallback, Func<DynamicMetaObject, DynamicMetaObject> fallbackInvoke) {
- ExpandoClass klass = Value.Class;
-
- //try to find the member, including the deleted members
- int index = klass.GetValueIndex(name, ignoreCase, Value);
-
- ParameterExpression value = Expression.Parameter(typeof(object), "value");
-
- Expression tryGetValue = Expression.Call(
- typeof(RuntimeOps).GetMethod("ExpandoTryGetValue"),
- GetLimitedSelf(),
- Expression.Constant(klass, typeof(object)),
- Expression.Constant(index),
- Expression.Constant(name),
- Expression.Constant(ignoreCase),
- value
- );
-
- var result = new DynamicMetaObject(value, BindingRestrictions.Empty);
- if (fallbackInvoke != null) {
- result = fallbackInvoke(result);
- }
-
- result = new DynamicMetaObject(
- Expression.Block(
- new[] { value },
- Expression.Condition(
- tryGetValue,
- result.Expression,
- fallback.Expression,
- typeof(object)
- )
- ),
- result.Restrictions.Merge(fallback.Restrictions)
- );
-
- return AddDynamicTestAndDefer(binder, Value.Class, null, result);
- }
-
- public override DynamicMetaObject BindGetMember(GetMemberBinder binder) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return BindGetOrInvokeMember(
- binder,
- binder.Name,
- binder.IgnoreCase,
- binder.FallbackGetMember(this),
- null
- );
- }
-
- public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(binder, "binder");
- return BindGetOrInvokeMember(
- binder,
- binder.Name,
- binder.IgnoreCase,
- binder.FallbackInvokeMember(this, args),
- value => binder.FallbackInvoke(value, args, null)
- );
- }
-
- public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) {
- ContractUtils.RequiresNotNull(binder, "binder");
- ContractUtils.RequiresNotNull(value, "value");
-
- ExpandoClass klass;
- int index;
-
- ExpandoClass originalClass = GetClassEnsureIndex(binder.Name, binder.IgnoreCase, Value, out klass, out index);
-
- return AddDynamicTestAndDefer(
- binder,
- klass,
- originalClass,
- new DynamicMetaObject(
- Expression.Call(
- typeof(RuntimeOps).GetMethod("ExpandoTrySetValue"),
- GetLimitedSelf(),
- Expression.Constant(klass, typeof(object)),
- Expression.Constant(index),
- Expression.Convert(value.Expression, typeof(object)),
- Expression.Constant(binder.Name),
- Expression.Constant(binder.IgnoreCase)
- ),
- BindingRestrictions.Empty
- )
- );
- }
-
- public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) {
- ContractUtils.RequiresNotNull(binder, "binder");
-
- int index = Value.Class.GetValueIndex(binder.Name, binder.IgnoreCase, Value);
-
- Expression tryDelete = Expression.Call(
- typeof(RuntimeOps).GetMethod("ExpandoTryDeleteValue"),
- GetLimitedSelf(),
- Expression.Constant(Value.Class, typeof(object)),
- Expression.Constant(index),
- Expression.Constant(binder.Name),
- Expression.Constant(binder.IgnoreCase)
- );
- DynamicMetaObject fallback = binder.FallbackDeleteMember(this);
-
- DynamicMetaObject target = new DynamicMetaObject(
- Expression.IfThen(Expression.Not(tryDelete), fallback.Expression),
- fallback.Restrictions
- );
-
- return AddDynamicTestAndDefer(binder, Value.Class, null, target);
- }
-
- public override IEnumerable<string> GetDynamicMemberNames() {
- var expandoData = Value._data;
- var klass = expandoData.Class;
- for (int i = 0; i < klass.Keys.Length; i++) {
- object val = expandoData[i];
- if (val != ExpandoObject.Uninitialized) {
- yield return klass.Keys[i];
- }
- }
- }
-
- /// <summary>
- /// Adds a dynamic test which checks if the version has changed. The test is only necessary for
- /// performance as the methods will do the correct thing if called with an incorrect version.
- /// </summary>
- private DynamicMetaObject AddDynamicTestAndDefer(DynamicMetaObjectBinder binder, ExpandoClass klass, ExpandoClass originalClass, DynamicMetaObject succeeds) {
-
- Expression ifTestSucceeds = succeeds.Expression;
- if (originalClass != null) {
- // we are accessing a member which has not yet been defined on this class.
- // We force a class promotion after the type check. If the class changes the
- // promotion will fail and the set/delete will do a full lookup using the new
- // class to discover the name.
- Debug.Assert(originalClass != klass);
-
- ifTestSucceeds = Expression.Block(
- Expression.Call(
- null,
- typeof(RuntimeOps).GetMethod("ExpandoPromoteClass"),
- GetLimitedSelf(),
- Expression.Constant(originalClass, typeof(object)),
- Expression.Constant(klass, typeof(object))
- ),
- succeeds.Expression
- );
- }
-
- return new DynamicMetaObject(
- Expression.Condition(
- Expression.Call(
- null,
- typeof(RuntimeOps).GetMethod("ExpandoCheckVersion"),
- GetLimitedSelf(),
- Expression.Constant(originalClass ?? klass, typeof(object))
- ),
- ifTestSucceeds,
- binder.GetUpdateExpression(ifTestSucceeds.Type)
- ),
- GetRestrictions().Merge(succeeds.Restrictions)
- );
- }
-
- /// <summary>
- /// Gets the class and the index associated with the given name. Does not update the expando object. Instead
- /// this returns both the original and desired new class. A rule is created which includes the test for the
- /// original class, the promotion to the new class, and the set/delete based on the class post-promotion.
- /// </summary>
- private ExpandoClass GetClassEnsureIndex(string name, bool caseInsensitive, ExpandoObject obj, out ExpandoClass klass, out int index) {
- ExpandoClass originalClass = Value.Class;
-
- index = originalClass.GetValueIndex(name, caseInsensitive, obj) ;
- if (index == ExpandoObject.AmbiguousMatchFound) {
- klass = originalClass;
- return null;
- }
- if (index == ExpandoObject.NoMatch) {
- // go ahead and find a new class now...
- ExpandoClass newClass = originalClass.FindNewClass(name);
-
- klass = newClass;
- index = newClass.GetValueIndexCaseSensitive(name);
-
- Debug.Assert(index != ExpandoObject.NoMatch);
- return originalClass;
- } else {
- klass = originalClass;
- return null;
- }
- }
-
- /// <summary>
- /// Returns our Expression converted to our known LimitType
- /// </summary>
- private Expression GetLimitedSelf() {
- if (TypeUtils.AreEquivalent(Expression.Type, LimitType)) {
- return Expression;
- }
- return Expression.Convert(Expression, LimitType);
- }
-
- /// <summary>
- /// Returns a Restrictions object which includes our current restrictions merged
- /// with a restriction limiting our type
- /// </summary>
- private BindingRestrictions GetRestrictions() {
- Debug.Assert(Restrictions == BindingRestrictions.Empty, "We don't merge, restrictions are always empty");
-
- return BindingRestrictions.GetTypeRestriction(this);
- }
-
- public new ExpandoObject Value {
- get {
- return (ExpandoObject)base.Value;
- }
- }
- }
-
- #endregion
-
- #region ExpandoData
-
- /// <summary>
- /// Stores the class and the data associated with the class as one atomic
- /// pair. This enables us to do a class check in a thread safe manner w/o
- /// requiring locks.
- /// </summary>
- private class ExpandoData {
- internal static ExpandoData Empty = new ExpandoData();
-
- /// <summary>
- /// the dynamically assigned class associated with the Expando object
- /// </summary>
- internal readonly ExpandoClass Class;
-
- /// <summary>
- /// data stored in the expando object, key names are stored in the class.
- ///
- /// Expando._data must be locked when mutating the value. Otherwise a copy of it
- /// could be made and lose values.
- /// </summary>
- private readonly object[] _dataArray;
-
- /// <summary>
- /// Indexer for getting/setting the data
- /// </summary>
- internal object this[int index] {
- get {
- return _dataArray[index];
- }
- set {
- //when the array is updated, version increases, even the new value is the same
- //as previous. Dictionary type has the same behavior.
- _version++;
- _dataArray[index] = value;
- }
- }
-
- internal int Version {
- get { return _version; }
- }
-
- internal int Length {
- get { return _dataArray.Length; }
- }
-
- /// <summary>
- /// Constructs an empty ExpandoData object with the empty class and no data.
- /// </summary>
- private ExpandoData() {
- Class = ExpandoClass.Empty;
- _dataArray = new object[0];
- }
-
- /// <summary>
- /// the version of the ExpandoObject that tracks set and delete operations
- /// </summary>
- private int _version;
-
- /// <summary>
- /// Constructs a new ExpandoData object with the specified class and data.
- /// </summary>
- internal ExpandoData(ExpandoClass klass, object[] data, int version) {
- Class = klass;
- _dataArray = data;
- _version = version;
- }
-
- /// <summary>
- /// Update the associated class and increases the storage for the data array if needed.
- /// </summary>
- /// <returns></returns>
- internal ExpandoData UpdateClass(ExpandoClass newClass) {
- if (_dataArray.Length >= newClass.Keys.Length) {
- // we have extra space in our buffer, just initialize it to Uninitialized.
- this[newClass.Keys.Length - 1] = ExpandoObject.Uninitialized;
- return new ExpandoData(newClass, this._dataArray, this._version);
- } else {
- // we've grown too much - we need a new object array
- int oldLength = _dataArray.Length;
- object[] arr = new object[GetAlignedSize(newClass.Keys.Length)];
- Array.Copy(_dataArray, arr, _dataArray.Length);
- ExpandoData newData = new ExpandoData(newClass, arr, this._version);
- newData[oldLength] = ExpandoObject.Uninitialized;
- return newData;
- }
- }
-
- private static int GetAlignedSize(int len) {
- // the alignment of the array for storage of values (must be a power of two)
- const int DataArrayAlignment = 8;
-
- // round up and then mask off lower bits
- return (len + (DataArrayAlignment - 1)) & (~(DataArrayAlignment - 1));
- }
- }
-
- #endregion
-
- #region INotifyPropertyChanged Members
-
- event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged {
- add { _propertyChanged += value; }
- remove { _propertyChanged -= value; }
- }
-
- #endregion
- }
-}
-
-namespace System.Runtime.CompilerServices {
-
- //
- // Note: these helpers are kept as simple wrappers so they have a better
- // chance of being inlined.
- //
- public static partial class RuntimeOps {
-
- /// <summary>
- /// Gets the value of an item in an expando object.
- /// </summary>
- /// <param name="expando">The expando object.</param>
- /// <param name="indexClass">The class of the expando object.</param>
- /// <param name="index">The index of the member.</param>
- /// <param name="name">The name of the member.</param>
- /// <param name="ignoreCase">true if the name should be matched ignoring case; false otherwise.</param>
- /// <param name="value">The out parameter containing the value of the member.</param>
- /// <returns>True if the member exists in the expando object, otherwise false.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static bool ExpandoTryGetValue(ExpandoObject expando, object indexClass, int index, string name, bool ignoreCase, out object value) {
- return expando.TryGetValue(indexClass, index, name, ignoreCase, out value);
- }
-
- /// <summary>
- /// Sets the value of an item in an expando object.
- /// </summary>
- /// <param name="expando">The expando object.</param>
- /// <param name="indexClass">The class of the expando object.</param>
- /// <param name="index">The index of the member.</param>
- /// <param name="value">The value of the member.</param>
- /// <param name="name">The name of the member.</param>
- /// <param name="ignoreCase">true if the name should be matched ignoring case; false otherwise.</param>
- /// <returns>
- /// Returns the index for the set member.
- /// </returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static object ExpandoTrySetValue(ExpandoObject expando, object indexClass, int index, object value, string name, bool ignoreCase) {
- expando.TrySetValue(indexClass, index, value, name, ignoreCase, false);
- return value;
- }
-
- /// <summary>
- /// Deletes the value of an item in an expando object.
- /// </summary>
- /// <param name="expando">The expando object.</param>
- /// <param name="indexClass">The class of the expando object.</param>
- /// <param name="index">The index of the member.</param>
- /// <param name="name">The name of the member.</param>
- /// <param name="ignoreCase">true if the name should be matched ignoring case; false otherwise.</param>
- /// <returns>true if the item was successfully removed; otherwise, false.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static bool ExpandoTryDeleteValue(ExpandoObject expando, object indexClass, int index, string name, bool ignoreCase) {
- return expando.TryDeleteValue(indexClass, index, name, ignoreCase, ExpandoObject.Uninitialized);
- }
-
- /// <summary>
- /// Checks the version of the expando object.
- /// </summary>
- /// <param name="expando">The expando object.</param>
- /// <param name="version">The version to check.</param>
- /// <returns>true if the version is equal; otherwise, false.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static bool ExpandoCheckVersion(ExpandoObject expando, object version) {
- return expando.Class == version;
- }
-
- /// <summary>
- /// Promotes an expando object from one class to a new class.
- /// </summary>
- /// <param name="expando">The expando object.</param>
- /// <param name="oldClass">The old class of the expando object.</param>
- /// <param name="newClass">The new class of the expando object.</param>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static void ExpandoPromoteClass(ExpandoObject expando, object oldClass, object newClass) {
- expando.PromoteClass(oldClass, newClass);
- }
- }
-}
-
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/GetIndexBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/GetIndexBinder.cs
deleted file mode 100644
index 56f625968b3..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/GetIndexBinder.cs
+++ /dev/null
@@ -1,88 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Dynamic.Utils;
-
-namespace System.Dynamic {
-
- /// <summary>
- /// Represents the dynamic get index operation at the call site, providing the binding semantic and the details about the operation.
- /// </summary>
- public abstract class GetIndexBinder : DynamicMetaObjectBinder {
- private readonly CallInfo _callInfo;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="GetIndexBinder" />.
- /// </summary>
- /// <param name="callInfo">The signature of the arguments at the call site.</param>
- protected GetIndexBinder(CallInfo callInfo) {
- ContractUtils.RequiresNotNull(callInfo, "callInfo");
- _callInfo = callInfo;
- }
-
- /// <summary>
- /// The result type of the operation.
- /// </summary>
- public override sealed Type ReturnType {
- get { return typeof(object); }
- }
-
- /// <summary>
- /// Gets the signature of the arguments at the call site.
- /// </summary>
- public CallInfo CallInfo {
- get { return _callInfo; }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic get index operation.
- /// </summary>
- /// <param name="target">The target of the dynamic get index operation.</param>
- /// <param name="args">An array of arguments of the dynamic get index operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(target, "target");
- ContractUtils.RequiresNotNullItems(args, "args");
-
- return target.BindGetIndex(this, args);
- }
-
- // this is a standard DynamicMetaObjectBinder
- internal override sealed bool IsStandardBinder {
- get {
- return true;
- }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic get index operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic get index operation.</param>
- /// <param name="indexes">The arguments of the dynamic get index operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes) {
- return FallbackGetIndex(target, indexes, null);
- }
-
- /// <summary>
- /// When overridden in the derived class, performs the binding of the dynamic get index operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic get index operation.</param>
- /// <param name="indexes">The arguments of the dynamic get index operation.</param>
- /// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public abstract DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject errorSuggestion);
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/GetMemberBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/GetMemberBinder.cs
deleted file mode 100644
index f02ca86ab2b..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/GetMemberBinder.cs
+++ /dev/null
@@ -1,100 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Dynamic.Utils;
-
-namespace System.Dynamic {
- /// <summary>
- /// Represents the dynamic get member operation at the call site, providing the binding semantic and the details about the operation.
- /// </summary>
- public abstract class GetMemberBinder : DynamicMetaObjectBinder {
- private readonly string _name;
- private readonly bool _ignoreCase;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="GetMemberBinder" />.
- /// </summary>
- /// <param name="name">The name of the member to get.</param>
- /// <param name="ignoreCase">true if the name should be matched ignoring case; false otherwise.</param>
- protected GetMemberBinder(string name, bool ignoreCase) {
- ContractUtils.RequiresNotNull(name, "name");
-
- _name = name;
- _ignoreCase = ignoreCase;
- }
-
- /// <summary>
- /// The result type of the operation.
- /// </summary>
- public override sealed Type ReturnType {
- get { return typeof(object); }
- }
-
- /// <summary>
- /// Gets the name of the member to get.
- /// </summary>
- public string Name {
- get {
- return _name;
- }
- }
-
- /// <summary>
- /// Gets the value indicating if the string comparison should ignore the case of the member name.
- /// </summary>
- public bool IgnoreCase {
- get {
- return _ignoreCase;
- }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic get member operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic get member operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject FallbackGetMember(DynamicMetaObject target) {
- return FallbackGetMember(target, null);
- }
-
- /// <summary>
- /// When overridden in the derived class, performs the binding of the dynamic get member operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic get member operation.</param>
- /// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public abstract DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion);
-
- /// <summary>
- /// Performs the binding of the dynamic get member operation.
- /// </summary>
- /// <param name="target">The target of the dynamic get member operation.</param>
- /// <param name="args">An array of arguments of the dynamic get member operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public sealed override DynamicMetaObject Bind(DynamicMetaObject target, params DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(target, "target");
- ContractUtils.Requires(args == null || args.Length == 0, "args");
-
- return target.BindGetMember(this);
- }
-
- // this is a standard DynamicMetaObjectBinder
- internal override sealed bool IsStandardBinder {
- get {
- return true;
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/IDynamicMetaObjectProvider.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/IDynamicMetaObjectProvider.cs
deleted file mode 100644
index 2977c2cb1bf..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/IDynamicMetaObjectProvider.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-namespace System.Dynamic {
- /// <summary>
- /// Represents a dynamic object, that can have its operations bound at runtime.
- /// </summary>
- /// <remarks>
- /// Objects that want to participate in the binding process should implement an IDynamicMetaObjectProvider interface,
- /// and implement <see cref="IDynamicMetaObjectProvider.GetMetaObject" /> to return a <see cref="DynamicMetaObject" />.
- /// </remarks>
- public interface IDynamicMetaObjectProvider {
- /// <summary>
- /// Returns the <see cref="DynamicMetaObject" /> responsible for binding operations performed on this object.
- /// </summary>
- /// <param name="parameter">The expression tree representation of the runtime value.</param>
- /// <returns>The <see cref="DynamicMetaObject" /> to bind this object.</returns>
- DynamicMetaObject GetMetaObject(Expression parameter);
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/IInvokeOnGetBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/IInvokeOnGetBinder.cs
deleted file mode 100644
index 49d2765be80..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/IInvokeOnGetBinder.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-namespace System.Dynamic {
- /// <summary>
- /// Represents information about a dynamic get member operation, indicating
- /// if the get member should invoke properties when performing the get.
- /// </summary>
- public interface IInvokeOnGetBinder {
- /// <summary>
- /// Gets the value indicating if this GetMember should invoke properties
- /// when performing the get. The default value when this interface is not present
- /// is true.
- /// </summary>
- /// <remarks>
- /// This property is used by some languages to get a better COM interop experience.
- /// When the value is set to false, the dynamic COM object won't invoke the object
- /// but will instead bind to the name, and return an object that can be invoked or
- /// indexed later. This is useful for indexed properties and languages that don't
- /// produce InvokeMember call sites.
- /// </remarks>
- bool InvokeOnGet { get; }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeBinder.cs
deleted file mode 100644
index 248bb542b02..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeBinder.cs
+++ /dev/null
@@ -1,88 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Dynamic.Utils;
-
-namespace System.Dynamic {
-
- /// <summary>
- /// Represents the invoke dynamic operation at the call site, providing the binding semantic and the details about the operation.
- /// </summary>
- public abstract class InvokeBinder : DynamicMetaObjectBinder {
- private readonly CallInfo _callInfo;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="InvokeBinder" />.
- /// </summary>
- /// <param name="callInfo">The signature of the arguments at the call site.</param>
- protected InvokeBinder(CallInfo callInfo) {
- ContractUtils.RequiresNotNull(callInfo, "callInfo");
- _callInfo = callInfo;
- }
-
- /// <summary>
- /// The result type of the operation.
- /// </summary>
- public override sealed Type ReturnType {
- get { return typeof(object); }
- }
-
- /// <summary>
- /// Gets the signature of the arguments at the call site.
- /// </summary>
- public CallInfo CallInfo {
- get { return _callInfo; }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic invoke operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic invoke operation.</param>
- /// <param name="args">The arguments of the dynamic invoke operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args) {
- return FallbackInvoke(target, args, null);
- }
-
- /// <summary>
- /// Performs the binding of the dynamic invoke operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic invoke operation.</param>
- /// <param name="args">The arguments of the dynamic invoke operation.</param>
- /// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public abstract DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion);
-
- /// <summary>
- /// Performs the binding of the dynamic invoke operation.
- /// </summary>
- /// <param name="target">The target of the dynamic invoke operation.</param>
- /// <param name="args">An array of arguments of the dynamic invoke operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(target, "target");
- ContractUtils.RequiresNotNullItems(args, "args");
-
- return target.BindInvoke(this, args);
- }
-
- // this is a standard DynamicMetaObjectBinder
- internal override sealed bool IsStandardBinder {
- get {
- return true;
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeMemberBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeMemberBinder.cs
deleted file mode 100644
index 404ff50bbf2..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeMemberBinder.cs
+++ /dev/null
@@ -1,129 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Dynamic.Utils;
-
-namespace System.Dynamic {
-
- /// <summary>
- /// Represents the invoke member dynamic operation at the call site,
- /// providing the binding semantic and the details about the operation.
- /// </summary>
- public abstract class InvokeMemberBinder : DynamicMetaObjectBinder {
- private readonly string _name;
- private readonly bool _ignoreCase;
- private readonly CallInfo _callInfo;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="InvokeMemberBinder" />.
- /// </summary>
- /// <param name="name">The name of the member to invoke.</param>
- /// <param name="ignoreCase">true if the name should be matched ignoring case; false otherwise.</param>
- /// <param name="callInfo">The signature of the arguments at the call site.</param>
- protected InvokeMemberBinder(string name, bool ignoreCase, CallInfo callInfo) {
- ContractUtils.RequiresNotNull(name, "name");
- ContractUtils.RequiresNotNull(callInfo, "callInfo");
-
- _name = name;
- _ignoreCase = ignoreCase;
- _callInfo = callInfo;
- }
-
- /// <summary>
- /// The result type of the operation.
- /// </summary>
- public override sealed Type ReturnType {
- get { return typeof(object); }
- }
-
- /// <summary>
- /// Gets the name of the member to invoke.
- /// </summary>
- public string Name {
- get {
- return _name;
- }
- }
-
- /// <summary>
- /// Gets the value indicating if the string comparison should ignore the case of the member name.
- /// </summary>
- public bool IgnoreCase {
- get {
- return _ignoreCase;
- }
- }
-
- /// <summary>
- /// Gets the signature of the arguments at the call site.
- /// </summary>
- public CallInfo CallInfo {
- get { return _callInfo; }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic invoke member operation.
- /// </summary>
- /// <param name="target">The target of the dynamic invoke member operation.</param>
- /// <param name="args">An array of arguments of the dynamic invoke member operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(target, "target");
- ContractUtils.RequiresNotNullItems(args, "args");
-
- return target.BindInvokeMember(this, args);
- }
-
- // this is a standard DynamicMetaObjectBinder
- internal override sealed bool IsStandardBinder {
- get {
- return true;
- }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic invoke member operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic invoke member operation.</param>
- /// <param name="args">The arguments of the dynamic invoke member operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args) {
- return FallbackInvokeMember(target, args, null);
- }
-
- /// <summary>
- /// When overridden in the derived class, performs the binding of the dynamic invoke member operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic invoke member operation.</param>
- /// <param name="args">The arguments of the dynamic invoke member operation.</param>
- /// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public abstract DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion);
-
- /// <summary>
- /// When overridden in the derived class, performs the binding of the dynamic invoke operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic invoke operation.</param>
- /// <param name="args">The arguments of the dynamic invoke operation.</param>
- /// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- /// <remarks>
- /// This method is called by the target when the target implements the invoke member operation
- /// as a sequence of get member, and invoke, to let the <see cref="DynamicMetaObject"/>
- /// request the binding of the invoke operation only.
- /// </remarks>
- public abstract DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion);
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/RuleCache.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/RuleCache.cs
deleted file mode 100644
index a7865f7e6e1..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/RuleCache.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-namespace System.Runtime.CompilerServices {
- /// <summary>
- /// This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
- /// Represents a cache of runtime binding rules.
- /// </summary>
- /// <typeparam name="T">The delegate type.</typeparam>
- [EditorBrowsable(EditorBrowsableState.Never), DebuggerStepThrough]
- public class RuleCache<T> where T : class {
- private T[] _rules = new T[0];
- private readonly Object cacheLock = new Object();
-
- private const int MaxRules = 128;
-
- internal RuleCache() { }
-
- internal T[] GetRules() {
- return _rules;
- }
-
- // move the rule +2 up.
- // this is called on every successful rule.
- internal void MoveRule(T rule, int i) {
- // limit search to MaxSearch elements.
- // Rule should not get too far unless it has been already moved up.
- // need a lock to make sure we are moving the right rule and not loosing any.
- lock (cacheLock) {
- const int MaxSearch = 8;
- int count = _rules.Length - i;
- if (count > MaxSearch) {
- count = MaxSearch;
- }
-
- int oldIndex = -1;
- int max = Math.Min(_rules.Length, i + count);
- for (int index = i; index < max; index++) {
- if (_rules[index] == rule) {
- oldIndex = index;
- break;
- }
- }
- if (oldIndex < 0) {
- return;
- }
- T oldRule = _rules[oldIndex];
- _rules[oldIndex] = _rules[oldIndex - 1];
- _rules[oldIndex - 1] = _rules[oldIndex - 2];
- _rules[oldIndex - 2] = oldRule;
- }
- }
-
- internal void AddRule(T newRule) {
- // need a lock to make sure we are not loosing rules.
- lock (cacheLock) {
- _rules = AddOrInsert(_rules, newRule);
- }
- }
-
- internal void ReplaceRule(T oldRule, T newRule) {
- // need a lock to make sure we are replacing the right rule
- lock (cacheLock) {
- int i = Array.IndexOf(_rules, oldRule);
- if (i >= 0) {
- _rules[i] = newRule;
- return; // DONE
- }
-
- // could not find it.
- _rules = AddOrInsert(_rules, newRule);
- }
- }
-
-
- // Adds to end or or inserts items at InsertPosition
- private const int InsertPosition = MaxRules / 2;
-
- private static T[] AddOrInsert(T[] rules, T item) {
- if (rules.Length < InsertPosition) {
- return rules.AddLast(item);
- }
-
- T[] newRules;
-
- int newLength = rules.Length + 1;
- if (newLength > MaxRules) {
- newLength = MaxRules;
- newRules = rules;
- } else {
- newRules = new T[newLength];
- }
-
- Array.Copy(rules, 0, newRules, 0, InsertPosition);
- newRules[InsertPosition] = item;
- Array.Copy(rules, InsertPosition, newRules, InsertPosition + 1, newLength - InsertPosition - 1);
- return newRules;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/SetIndexBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/SetIndexBinder.cs
deleted file mode 100644
index f1e8952bef3..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/SetIndexBinder.cs
+++ /dev/null
@@ -1,97 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Dynamic.Utils;
-
-namespace System.Dynamic {
-
- /// <summary>
- /// Represents the dynamic set index operation at the call site, providing the binding semantic and the details about the operation.
- /// </summary>
- public abstract class SetIndexBinder : DynamicMetaObjectBinder {
- private readonly CallInfo _callInfo;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="SetIndexBinder" />.
- /// </summary>
- /// <param name="callInfo">The signature of the arguments at the call site.</param>
- protected SetIndexBinder(CallInfo callInfo) {
- ContractUtils.RequiresNotNull(callInfo, "callInfo");
- _callInfo = callInfo;
- }
-
- /// <summary>
- /// The result type of the operation.
- /// </summary>
- public override sealed Type ReturnType {
- get { return typeof(object); }
- }
-
- /// <summary>
- /// Gets the signature of the arguments at the call site.
- /// </summary>
- public CallInfo CallInfo {
- get { return _callInfo; }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic set index operation.
- /// </summary>
- /// <param name="target">The target of the dynamic set index operation.</param>
- /// <param name="args">An array of arguments of the dynamic set index operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(target, "target");
- ContractUtils.RequiresNotNull(args, "args");
- ContractUtils.Requires(args.Length >= 2, "args");
-
- DynamicMetaObject value = args[args.Length - 1];
- DynamicMetaObject[] indexes = args.RemoveLast();
-
- ContractUtils.RequiresNotNull(value, "args");
- ContractUtils.RequiresNotNullItems(indexes, "args");
-
- return target.BindSetIndex(this, indexes, value);
- }
-
- // this is a standard DynamicMetaObjectBinder
- internal override sealed bool IsStandardBinder {
- get {
- return true;
- }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic set index operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic set index operation.</param>
- /// <param name="indexes">The arguments of the dynamic set index operation.</param>
- /// <param name="value">The value to set to the collection.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject FallbackSetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject value) {
- return FallbackSetIndex(target, indexes, value, null);
- }
-
- /// <summary>
- /// When overridden in the derived class, performs the binding of the dynamic set index operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic set index operation.</param>
- /// <param name="indexes">The arguments of the dynamic set index operation.</param>
- /// <param name="value">The value to set to the collection.</param>
- /// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public abstract DynamicMetaObject FallbackSetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject value, DynamicMetaObject errorSuggestion);
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/SetMemberBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/SetMemberBinder.cs
deleted file mode 100644
index dcda1058803..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/SetMemberBinder.cs
+++ /dev/null
@@ -1,106 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Dynamic.Utils;
-
-namespace System.Dynamic {
- /// <summary>
- /// Represents the dynamic set member operation at the call site, providing the binding semantic and the details about the operation.
- /// </summary>
- public abstract class SetMemberBinder : DynamicMetaObjectBinder {
- private readonly string _name;
- private readonly bool _ignoreCase;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="SetMemberBinder" />.
- /// </summary>
- /// <param name="name">The name of the member to get.</param>
- /// <param name="ignoreCase">true if the name should be matched ignoring case; false otherwise.</param>
- protected SetMemberBinder(string name, bool ignoreCase) {
- ContractUtils.RequiresNotNull(name, "name");
-
- _name = name;
- _ignoreCase = ignoreCase;
- }
-
- /// <summary>
- /// The result type of the operation.
- /// </summary>
- public override sealed Type ReturnType {
- get { return typeof(object); }
- }
-
- /// <summary>
- /// Gets the name of the member to get.
- /// </summary>
- public string Name {
- get {
- return _name;
- }
- }
-
- /// <summary>
- /// Gets the value indicating if the string comparison should ignore the case of the member name.
- /// </summary>
- public bool IgnoreCase {
- get {
- return _ignoreCase;
- }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic set member operation.
- /// </summary>
- /// <param name="target">The target of the dynamic set member operation.</param>
- /// <param name="args">An array of arguments of the dynamic set member operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(target, "target");
- ContractUtils.RequiresNotNull(args, "args");
- ContractUtils.Requires(args.Length == 1, "args");
-
- var arg0 = args[0];
- ContractUtils.RequiresNotNull(arg0, "args");
-
- return target.BindSetMember(this, arg0);
- }
-
- // this is a standard DynamicMetaObjectBinder
- internal override sealed bool IsStandardBinder {
- get {
- return true;
- }
- }
-
- /// <summary>
- /// Performs the binding of the dynamic set member operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic set member operation.</param>
- /// <param name="value">The value to set to the member.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject FallbackSetMember(DynamicMetaObject target, DynamicMetaObject value) {
- return FallbackSetMember(target, value, null);
- }
-
- /// <summary>
- /// Performs the binding of the dynamic set member operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic set member operation.</param>
- /// <param name="value">The value to set to the member.</param>
- /// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public abstract DynamicMetaObject FallbackSetMember(DynamicMetaObject target, DynamicMetaObject value, DynamicMetaObject errorSuggestion);
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/UnaryOperationBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/UnaryOperationBinder.cs
deleted file mode 100644
index 5d5d45c1a91..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/UnaryOperationBinder.cs
+++ /dev/null
@@ -1,129 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-#else
-using System.Linq.Expressions;
-#endif
-
-using System.Dynamic.Utils;
-
-namespace System.Dynamic {
- /// <summary>
- /// Represents the unary dynamic operation at the call site, providing the binding semantic and the details about the operation.
- /// </summary>
- public abstract class UnaryOperationBinder : DynamicMetaObjectBinder {
- private ExpressionType _operation;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="BinaryOperationBinder"/> class.
- /// </summary>
- /// <param name="operation">The unary operation kind.</param>
- protected UnaryOperationBinder(ExpressionType operation) {
- ContractUtils.Requires(OperationIsValid(operation), "operation");
- _operation = operation;
- }
-
- /// <summary>
- /// The result type of the operation.
- /// </summary>
- public override sealed Type ReturnType {
- get {
- switch(_operation) {
- case ExpressionType.IsFalse:
- case ExpressionType.IsTrue:
- return typeof(bool);
- default:
- return typeof(object);
- }
- }
- }
-
- /// <summary>
- /// The unary operation kind.
- /// </summary>
- public ExpressionType Operation {
- get {
- return _operation;
- }
- }
-
- /// <summary>
- /// Performs the binding of the unary dynamic operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic unary operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject target) {
- return FallbackUnaryOperation(target, null);
- }
-
- /// <summary>
- /// Performs the binding of the unary dynamic operation if the target dynamic object cannot bind.
- /// </summary>
- /// <param name="target">The target of the dynamic unary operation.</param>
- /// <param name="errorSuggestion">The binding result in case the binding fails, or null.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public abstract DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject target, DynamicMetaObject errorSuggestion);
-
- /// <summary>
- /// Performs the binding of the dynamic unary operation.
- /// </summary>
- /// <param name="target">The target of the dynamic operation.</param>
- /// <param name="args">An array of arguments of the dynamic operation.</param>
- /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
- public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) {
- ContractUtils.RequiresNotNull(target, "target");
- ContractUtils.Requires(args == null || args.Length == 0, "args");
-
- return target.BindUnaryOperation(this);
- }
-
- // this is a standard DynamicMetaObjectBinder
- internal override sealed bool IsStandardBinder {
- get {
- return true;
- }
- }
-
- internal static bool OperationIsValid(ExpressionType operation) {
- switch (operation) {
- #region Generated Unary Operation Binder Validator
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_unop_validator from: generate_tree.py
-
- case ExpressionType.Negate:
- case ExpressionType.UnaryPlus:
- case ExpressionType.Not:
- case ExpressionType.Decrement:
- case ExpressionType.Increment:
- case ExpressionType.OnesComplement:
- case ExpressionType.IsTrue:
- case ExpressionType.IsFalse:
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- case ExpressionType.Extension:
- return true;
-
- default:
- return false;
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/UpdateDelegates.Generated.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/UpdateDelegates.Generated.cs
deleted file mode 100644
index 3143d6e4efb..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/UpdateDelegates.Generated.cs
+++ /dev/null
@@ -1,2658 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Utils;
-#endif
-
-using System.Runtime.CompilerServices;
-using System.Threading;
-
-namespace System.Dynamic {
- internal static partial class UpdateDelegates {
-
- //
- // WARNING: do not edit these methods here. The real source code lives
- // in two places: generate_dynsites.py, which generates the methods in
- // this file, and UpdateDelegates.cs, which dynamically generates
- // methods like these at run time. If you want to make a change, edit
- // *both* of those files instead
- //
-
- #region Generated UpdateAndExecute Methods
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_update_targets from: generate_dynsites.py
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static TRet UpdateAndExecute0<TRet>(CallSite site) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Func<CallSite, TRet>>)site;
- Func<CallSite, TRet>[] applicable;
- Func<CallSite, TRet> rule, originalRule = @this.Target;
- TRet result;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- result = rule(site);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return result;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- result = rule(site);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- result = rule(site);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static TRet NoMatch0<TRet>(CallSite site) {
- site._match = false;
- return default(TRet);
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static TRet UpdateAndExecute1<T0, TRet>(CallSite site, T0 arg0) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Func<CallSite, T0, TRet>>)site;
- Func<CallSite, T0, TRet>[] applicable;
- Func<CallSite, T0, TRet> rule, originalRule = @this.Target;
- TRet result;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- result = rule(site, arg0);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return result;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- result = rule(site, arg0);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- result = rule(site, arg0);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static TRet NoMatch1<T0, TRet>(CallSite site, T0 arg0) {
- site._match = false;
- return default(TRet);
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static TRet UpdateAndExecute2<T0, T1, TRet>(CallSite site, T0 arg0, T1 arg1) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Func<CallSite, T0, T1, TRet>>)site;
- Func<CallSite, T0, T1, TRet>[] applicable;
- Func<CallSite, T0, T1, TRet> rule, originalRule = @this.Target;
- TRet result;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- result = rule(site, arg0, arg1);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return result;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- result = rule(site, arg0, arg1);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- result = rule(site, arg0, arg1);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static TRet NoMatch2<T0, T1, TRet>(CallSite site, T0 arg0, T1 arg1) {
- site._match = false;
- return default(TRet);
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static TRet UpdateAndExecute3<T0, T1, T2, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Func<CallSite, T0, T1, T2, TRet>>)site;
- Func<CallSite, T0, T1, T2, TRet>[] applicable;
- Func<CallSite, T0, T1, T2, TRet> rule, originalRule = @this.Target;
- TRet result;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- result = rule(site, arg0, arg1, arg2);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return result;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- result = rule(site, arg0, arg1, arg2);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- result = rule(site, arg0, arg1, arg2);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static TRet NoMatch3<T0, T1, T2, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2) {
- site._match = false;
- return default(TRet);
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static TRet UpdateAndExecute4<T0, T1, T2, T3, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Func<CallSite, T0, T1, T2, T3, TRet>>)site;
- Func<CallSite, T0, T1, T2, T3, TRet>[] applicable;
- Func<CallSite, T0, T1, T2, T3, TRet> rule, originalRule = @this.Target;
- TRet result;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- result = rule(site, arg0, arg1, arg2, arg3);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return result;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static TRet NoMatch4<T0, T1, T2, T3, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3) {
- site._match = false;
- return default(TRet);
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static TRet UpdateAndExecute5<T0, T1, T2, T3, T4, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Func<CallSite, T0, T1, T2, T3, T4, TRet>>)site;
- Func<CallSite, T0, T1, T2, T3, T4, TRet>[] applicable;
- Func<CallSite, T0, T1, T2, T3, T4, TRet> rule, originalRule = @this.Target;
- TRet result;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- result = rule(site, arg0, arg1, arg2, arg3, arg4);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return result;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3, arg4);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3, arg4 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3, arg4);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static TRet NoMatch5<T0, T1, T2, T3, T4, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4) {
- site._match = false;
- return default(TRet);
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static TRet UpdateAndExecute6<T0, T1, T2, T3, T4, T5, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Func<CallSite, T0, T1, T2, T3, T4, T5, TRet>>)site;
- Func<CallSite, T0, T1, T2, T3, T4, T5, TRet>[] applicable;
- Func<CallSite, T0, T1, T2, T3, T4, T5, TRet> rule, originalRule = @this.Target;
- TRet result;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return result;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3, arg4, arg5 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static TRet NoMatch6<T0, T1, T2, T3, T4, T5, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) {
- site._match = false;
- return default(TRet);
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static TRet UpdateAndExecute7<T0, T1, T2, T3, T4, T5, T6, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Func<CallSite, T0, T1, T2, T3, T4, T5, T6, TRet>>)site;
- Func<CallSite, T0, T1, T2, T3, T4, T5, T6, TRet>[] applicable;
- Func<CallSite, T0, T1, T2, T3, T4, T5, T6, TRet> rule, originalRule = @this.Target;
- TRet result;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return result;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3, arg4, arg5, arg6 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static TRet NoMatch7<T0, T1, T2, T3, T4, T5, T6, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) {
- site._match = false;
- return default(TRet);
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static TRet UpdateAndExecute8<T0, T1, T2, T3, T4, T5, T6, T7, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Func<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, TRet>>)site;
- Func<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, TRet>[] applicable;
- Func<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, TRet> rule, originalRule = @this.Target;
- TRet result;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return result;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static TRet NoMatch8<T0, T1, T2, T3, T4, T5, T6, T7, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7) {
- site._match = false;
- return default(TRet);
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static TRet UpdateAndExecute9<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Func<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>>)site;
- Func<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>[] applicable;
- Func<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet> rule, originalRule = @this.Target;
- TRet result;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return result;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static TRet NoMatch9<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8) {
- site._match = false;
- return default(TRet);
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static TRet UpdateAndExecute10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Func<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>>)site;
- Func<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>[] applicable;
- Func<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet> rule, originalRule = @this.Target;
- TRet result;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return result;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- result = rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
- if (CallSiteOps.GetMatch(site)) {
- return result;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static TRet NoMatch10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9) {
- site._match = false;
- return default(TRet);
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static void UpdateAndExecuteVoid1<T0>(CallSite site, T0 arg0) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Action<CallSite, T0>>)site;
- Action<CallSite, T0>[] applicable;
- Action<CallSite, T0> rule, originalRule = @this.Target;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- rule(site, arg0);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- rule(site, arg0);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- rule(site, arg0);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static void NoMatchVoid1<T0>(CallSite site, T0 arg0) {
- site._match = false;
- return;
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static void UpdateAndExecuteVoid2<T0, T1>(CallSite site, T0 arg0, T1 arg1) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Action<CallSite, T0, T1>>)site;
- Action<CallSite, T0, T1>[] applicable;
- Action<CallSite, T0, T1> rule, originalRule = @this.Target;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- rule(site, arg0, arg1);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- rule(site, arg0, arg1);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- rule(site, arg0, arg1);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static void NoMatchVoid2<T0, T1>(CallSite site, T0 arg0, T1 arg1) {
- site._match = false;
- return;
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static void UpdateAndExecuteVoid3<T0, T1, T2>(CallSite site, T0 arg0, T1 arg1, T2 arg2) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Action<CallSite, T0, T1, T2>>)site;
- Action<CallSite, T0, T1, T2>[] applicable;
- Action<CallSite, T0, T1, T2> rule, originalRule = @this.Target;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- rule(site, arg0, arg1, arg2);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- rule(site, arg0, arg1, arg2);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- rule(site, arg0, arg1, arg2);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static void NoMatchVoid3<T0, T1, T2>(CallSite site, T0 arg0, T1 arg1, T2 arg2) {
- site._match = false;
- return;
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static void UpdateAndExecuteVoid4<T0, T1, T2, T3>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Action<CallSite, T0, T1, T2, T3>>)site;
- Action<CallSite, T0, T1, T2, T3>[] applicable;
- Action<CallSite, T0, T1, T2, T3> rule, originalRule = @this.Target;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- rule(site, arg0, arg1, arg2, arg3);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- rule(site, arg0, arg1, arg2, arg3);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- rule(site, arg0, arg1, arg2, arg3);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static void NoMatchVoid4<T0, T1, T2, T3>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3) {
- site._match = false;
- return;
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static void UpdateAndExecuteVoid5<T0, T1, T2, T3, T4>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Action<CallSite, T0, T1, T2, T3, T4>>)site;
- Action<CallSite, T0, T1, T2, T3, T4>[] applicable;
- Action<CallSite, T0, T1, T2, T3, T4> rule, originalRule = @this.Target;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- rule(site, arg0, arg1, arg2, arg3, arg4);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- rule(site, arg0, arg1, arg2, arg3, arg4);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3, arg4 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- rule(site, arg0, arg1, arg2, arg3, arg4);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static void NoMatchVoid5<T0, T1, T2, T3, T4>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4) {
- site._match = false;
- return;
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static void UpdateAndExecuteVoid6<T0, T1, T2, T3, T4, T5>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Action<CallSite, T0, T1, T2, T3, T4, T5>>)site;
- Action<CallSite, T0, T1, T2, T3, T4, T5>[] applicable;
- Action<CallSite, T0, T1, T2, T3, T4, T5> rule, originalRule = @this.Target;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3, arg4, arg5 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static void NoMatchVoid6<T0, T1, T2, T3, T4, T5>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) {
- site._match = false;
- return;
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static void UpdateAndExecuteVoid7<T0, T1, T2, T3, T4, T5, T6>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Action<CallSite, T0, T1, T2, T3, T4, T5, T6>>)site;
- Action<CallSite, T0, T1, T2, T3, T4, T5, T6>[] applicable;
- Action<CallSite, T0, T1, T2, T3, T4, T5, T6> rule, originalRule = @this.Target;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3, arg4, arg5, arg6 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static void NoMatchVoid7<T0, T1, T2, T3, T4, T5, T6>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) {
- site._match = false;
- return;
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static void UpdateAndExecuteVoid8<T0, T1, T2, T3, T4, T5, T6, T7>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Action<CallSite, T0, T1, T2, T3, T4, T5, T6, T7>>)site;
- Action<CallSite, T0, T1, T2, T3, T4, T5, T6, T7>[] applicable;
- Action<CallSite, T0, T1, T2, T3, T4, T5, T6, T7> rule, originalRule = @this.Target;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static void NoMatchVoid8<T0, T1, T2, T3, T4, T5, T6, T7>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7) {
- site._match = false;
- return;
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static void UpdateAndExecuteVoid9<T0, T1, T2, T3, T4, T5, T6, T7, T8>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Action<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, T8>>)site;
- Action<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, T8>[] applicable;
- Action<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, T8> rule, originalRule = @this.Target;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static void NoMatchVoid9<T0, T1, T2, T3, T4, T5, T6, T7, T8>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8) {
- site._match = false;
- return;
- }
-
-
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- internal static void UpdateAndExecuteVoid10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9) {
- //
- // Declare the locals here upfront. It actually saves JIT stack space.
- //
- var @this = (CallSite<Action<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>>)site;
- Action<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>[] applicable;
- Action<CallSite, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9> rule, originalRule = @this.Target;
-
-
- //
- // Create matchmaker and its site. We'll need them regardless.
- //
- site = CallSiteOps.CreateMatchmaker(@this);
-
- //
- // Level 1 cache lookup
- //
- if ((applicable = CallSiteOps.GetRules(@this)) != null) {
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
-
- // if we've already tried it skip it...
- if ((object)rule != (object)originalRule) {
- @this.Target = rule;
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
-
- if (CallSiteOps.GetMatch(site)) {
- CallSiteOps.UpdateRules(@this, i);
- return;
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
- }
- }
-
- //
- // Level 2 cache lookup
- //
-
- //
- // Any applicable rules in level 2 cache?
- //
-
- var cache = CallSiteOps.GetRuleCache(@this);
-
- applicable = cache.GetRules();
- for (int i = 0; i < applicable.Length; i++) {
- rule = applicable[i];
-
- //
- // Execute the rule
- //
- @this.Target = rule;
-
- try {
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // Rule worked. Add it to level 1 cache
- //
- CallSiteOps.AddRule(@this, rule);
- // and then move it to the front of the L2 cache
- CallSiteOps.MoveRule(cache, rule, i);
- }
- }
-
- // Rule didn't match, try the next one
- CallSiteOps.ClearMatch(site);
- }
-
- //
- // Miss on Level 0, 1 and 2 caches. Create new rule
- //
-
- rule = null;
- var args = new object[] { arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 };
-
- for (; ; ) {
- @this.Target = originalRule;
- rule = @this.Target = @this.Binder.BindCore(@this, args);
-
- //
- // Execute the rule on the matchmaker site
- //
-
- try {
- rule(site, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
- if (CallSiteOps.GetMatch(site)) {
- return;
- }
- } finally {
- if (CallSiteOps.GetMatch(site)) {
- //
- // The rule worked. Add it to level 1 cache.
- //
- CallSiteOps.AddRule(@this, rule);
- }
- }
-
- // Rule we got back didn't work, try another one
- CallSiteOps.ClearMatch(site);
- }
- }
-
- [Obsolete("pregenerated CallSite<T>.Update delegate", true)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
- internal static void NoMatchVoid10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9) {
- site._match = false;
- return;
- }
-
-
-
- // *** END GENERATED CODE ***
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/BinaryExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/BinaryExpression.cs
deleted file mode 100644
index 28d06baa662..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/BinaryExpression.cs
+++ /dev/null
@@ -1,2652 +0,0 @@
-
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- /// <summary>
- /// Represents an expression that has a binary operator.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.BinaryExpressionProxy))]
- public class BinaryExpression : Expression {
- private readonly Expression _left;
- private readonly Expression _right;
-
- internal BinaryExpression(Expression left, Expression right) {
- _left = left;
- _right = right;
- }
-
- /// <summary>
- /// Gets a value that indicates whether the expression tree node can be reduced.
- /// </summary>
- public override bool CanReduce {
- get {
- // Only OpAssignments are reducible.
- return IsOpAssignment(NodeType);
- }
- }
-
- private static bool IsOpAssignment(ExpressionType op) {
- switch (op) {
- case ExpressionType.AddAssign:
- case ExpressionType.SubtractAssign:
- case ExpressionType.MultiplyAssign:
- case ExpressionType.AddAssignChecked:
- case ExpressionType.SubtractAssignChecked:
- case ExpressionType.MultiplyAssignChecked:
- case ExpressionType.DivideAssign:
- case ExpressionType.ModuloAssign:
- case ExpressionType.PowerAssign:
- case ExpressionType.AndAssign:
- case ExpressionType.OrAssign:
- case ExpressionType.RightShiftAssign:
- case ExpressionType.LeftShiftAssign:
- case ExpressionType.ExclusiveOrAssign:
- return true;
- }
- return false;
- }
-
- /// <summary>
- /// Gets the right operand of the binary operation.
- /// </summary>
- public Expression Right {
- get { return _right; }
- }
-
- /// <summary>
- /// Gets the left operand of the binary operation.
- /// </summary>
- public Expression Left {
- get { return _left; }
- }
-
- /// <summary>
- /// Gets the implementing method for the binary operation.
- /// </summary>
- public MethodInfo Method {
- get { return GetMethod(); }
- }
-
- internal virtual MethodInfo GetMethod() {
- return null;
- }
-
- // Note: takes children in evaluation order, which is also the order
- // that ExpressionVisitor visits them. Having them this way reduces the
- // chances people will make a mistake and use an inconsistent order in
- // derived visitors.
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="left">The <see cref="Left" /> property of the result.</param>
- /// <param name="conversion">The <see cref="Conversion" /> property of the result.</param>
- /// <param name="right">The <see cref="Right" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public BinaryExpression Update(Expression left, LambdaExpression conversion, Expression right) {
- if (left == Left && right == Right && conversion == Conversion) {
- return this;
- }
- if (IsReferenceComparison) {
- if (NodeType == ExpressionType.Equal) {
- return Expression.ReferenceEqual(left, right);
- } else {
- return Expression.ReferenceNotEqual(left, right);
- }
- }
- return Expression.MakeBinary(NodeType, left, right, IsLiftedToNull, Method, conversion);
- }
-
- /// <summary>
- /// Reduces the binary expression node to a simpler expression.
- /// If CanReduce returns true, this should return a valid expression.
- /// This method is allowed to return another node which itself
- /// must be reduced.
- /// </summary>
- /// <returns>The reduced expression.</returns>
- public override Expression Reduce() {
- // Only reduce OpAssignment expressions.
- if (IsOpAssignment(NodeType)) {
- switch (_left.NodeType) {
- case ExpressionType.MemberAccess:
- return ReduceMember();
-
- case ExpressionType.Index:
- return ReduceIndex();
-
- default:
- return ReduceVariable();
- }
- }
- return this;
- }
-
- // Return the corresponding Op of an assignment op.
- private static ExpressionType GetBinaryOpFromAssignmentOp(ExpressionType op) {
- Debug.Assert(IsOpAssignment(op));
- switch (op) {
- case ExpressionType.AddAssign:
- return ExpressionType.Add;
- case ExpressionType.AddAssignChecked:
- return ExpressionType.AddChecked;
- case ExpressionType.SubtractAssign:
- return ExpressionType.Subtract;
- case ExpressionType.SubtractAssignChecked:
- return ExpressionType.SubtractChecked;
- case ExpressionType.MultiplyAssign:
- return ExpressionType.Multiply;
- case ExpressionType.MultiplyAssignChecked:
- return ExpressionType.MultiplyChecked;
- case ExpressionType.DivideAssign:
- return ExpressionType.Divide;
- case ExpressionType.ModuloAssign:
- return ExpressionType.Modulo;
- case ExpressionType.PowerAssign:
- return ExpressionType.Power;
- case ExpressionType.AndAssign:
- return ExpressionType.And;
- case ExpressionType.OrAssign:
- return ExpressionType.Or;
- case ExpressionType.RightShiftAssign:
- return ExpressionType.RightShift;
- case ExpressionType.LeftShiftAssign:
- return ExpressionType.LeftShift;
- case ExpressionType.ExclusiveOrAssign:
- return ExpressionType.ExclusiveOr;
- default:
- // must be an error
- throw Error.InvalidOperation("op");
- }
-
- }
-
- private Expression ReduceVariable() {
- // v (op)= r
- // ... is reduced into ...
- // v = v (op) r
- ExpressionType op = GetBinaryOpFromAssignmentOp(NodeType);
- Expression r = Expression.MakeBinary(op, _left, _right, false, Method);
- LambdaExpression conversion = GetConversion();
- if (conversion != null) {
- r = Expression.Invoke(conversion, r);
- }
- return Expression.Assign(_left, r);
- }
-
- private Expression ReduceMember() {
- MemberExpression member = (MemberExpression)_left;
-
- if (member.Expression == null) {
- // static member, reduce the same as variable
- return ReduceVariable();
- } else {
- // left.b (op)= r
- // ... is reduced into ...
- // temp1 = left
- // temp2 = temp1.b (op) r
- // temp1.b = temp2
- // temp2
- ParameterExpression temp1 = Variable(member.Expression.Type, "temp1");
-
- // 1. temp1 = left
- Expression e1 = Expression.Assign(temp1, member.Expression);
-
- // 2. temp2 = temp1.b (op) r
- ExpressionType op = GetBinaryOpFromAssignmentOp(NodeType);
- Expression e2 = Expression.MakeBinary(op, Expression.MakeMemberAccess(temp1, member.Member), _right, false, Method);
- LambdaExpression conversion = GetConversion();
- if (conversion != null) {
- e2 = Expression.Invoke(conversion, e2);
- }
- ParameterExpression temp2 = Variable(e2.Type, "temp2");
- e2 = Expression.Assign(temp2, e2);
-
- // 3. temp1.b = temp2
- Expression e3 = Expression.Assign(Expression.MakeMemberAccess(temp1, member.Member), temp2);
-
- // 3. temp2
- Expression e4 = temp2;
-
- return Expression.Block(
- new ParameterExpression[] { temp1, temp2 },
- e1, e2, e3, e4
- );
- }
- }
-
- private Expression ReduceIndex() {
- // left[a0, a1, ... aN] (op)= r
- //
- // ... is reduced into ...
- //
- // tempObj = left
- // tempArg0 = a0
- // ...
- // tempArgN = aN
- // tempValue = tempObj[tempArg0, ... tempArgN] (op) r
- // tempObj[tempArg0, ... tempArgN] = tempValue
-
- var index = (IndexExpression)_left;
-
- var vars = new List<ParameterExpression>(index.Arguments.Count + 2);
- var exprs = new List<Expression>(index.Arguments.Count + 3);
-
- var tempObj = Expression.Variable(index.Object.Type, "tempObj");
- vars.Add(tempObj);
- exprs.Add(Expression.Assign(tempObj, index.Object));
-
- var tempArgs = new List<Expression>(index.Arguments.Count);
- foreach (var arg in index.Arguments) {
- var tempArg = Expression.Variable(arg.Type, "tempArg" + tempArgs.Count);
- vars.Add(tempArg);
- tempArgs.Add(tempArg);
- exprs.Add(Expression.Assign(tempArg, arg));
- }
-
- var tempIndex = Expression.MakeIndex(tempObj, index.Indexer, tempArgs);
-
- // tempValue = tempObj[tempArg0, ... tempArgN] (op) r
- ExpressionType binaryOp = GetBinaryOpFromAssignmentOp(NodeType);
- Expression op = Expression.MakeBinary(binaryOp, tempIndex, _right, false, Method);
- LambdaExpression conversion = GetConversion();
- if (conversion != null) {
- op = Expression.Invoke(conversion, op);
- }
- var tempValue = Expression.Variable(op.Type, "tempValue");
- vars.Add(tempValue);
- exprs.Add(Expression.Assign(tempValue, op));
-
- // tempObj[tempArg0, ... tempArgN] = tempValue
- exprs.Add(Expression.Assign(tempIndex, tempValue));
-
- return Expression.Block(vars, exprs);
- }
-
- /// <summary>
- /// Gets the type conversion function that is used by a coalescing or compound assignment operation.
- /// </summary>
- public LambdaExpression Conversion {
- get { return GetConversion(); }
- }
-
- internal virtual LambdaExpression GetConversion() {
- return null;
- }
-
- /// <summary>
- /// Gets a value that indicates whether the expression tree node represents a lifted call to an operator.
- /// </summary>
- public bool IsLifted {
- get {
- if (NodeType == ExpressionType.Coalesce || NodeType == ExpressionType.Assign) {
- return false;
- }
- if (TypeUtils.IsNullableType(_left.Type)) {
- MethodInfo method = GetMethod();
- return method == null ||
- !TypeUtils.AreEquivalent(method.GetParametersCached()[0].ParameterType.GetNonRefType(), _left.Type);
- }
- return false;
- }
- }
- /// <summary>
- /// Gets a value that indicates whether the expression tree node represents a lifted call to an operator whose return type is lifted to a nullable type.
- /// </summary>
- public bool IsLiftedToNull {
- get {
- return IsLifted && TypeUtils.IsNullableType(Type);
- }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitBinary(this);
- }
-
- internal static Expression Create(ExpressionType nodeType, Expression left, Expression right, Type type, MethodInfo method, LambdaExpression conversion) {
- if (nodeType == ExpressionType.Assign) {
- Debug.Assert(method == null && TypeUtils.AreEquivalent(type, left.Type));
- return new AssignBinaryExpression(left, right);
- }
- if (conversion != null) {
- Debug.Assert(method == null && TypeUtils.AreEquivalent(type, right.Type) && nodeType == ExpressionType.Coalesce);
- return new CoalesceConversionBinaryExpression(left, right, conversion);
- }
- if (method != null) {
- return new MethodBinaryExpression(nodeType, left, right, type, method);
- }
- if (type == typeof(bool)) {
- return new LogicalBinaryExpression(nodeType, left, right);
- }
- return new SimpleBinaryExpression(nodeType, left, right, type);
- }
-
- internal bool IsLiftedLogical {
- get {
- Type left = _left.Type;
- Type right = _right.Type;
- MethodInfo method = GetMethod();
- ExpressionType kind = NodeType;
-
- return
- (kind == ExpressionType.AndAlso || kind == ExpressionType.OrElse) &&
- TypeUtils.AreEquivalent(right, left) &&
- TypeUtils.IsNullableType(left) &&
- method != null &&
- TypeUtils.AreEquivalent(method.ReturnType, TypeUtils.GetNonNullableType(left));
- }
- }
-
- internal bool IsReferenceComparison {
- get {
- Type left = _left.Type;
- Type right = _right.Type;
- MethodInfo method = GetMethod();
- ExpressionType kind = NodeType;
-
- return (kind == ExpressionType.Equal || kind == ExpressionType.NotEqual) &&
- method == null && !left.IsValueType && !right.IsValueType;
- }
- }
-
- //
- // For a userdefined type T which has op_False defined and L, R are
- // nullable, (L AndAlso R) is computed as:
- //
- // L.HasValue
- // ? T.op_False(L.GetValueOrDefault())
- // ? L
- // : R.HasValue
- // ? (T?)(T.op_BitwiseAnd(L.GetValueOrDefault(), R.GetValueOrDefault()))
- // : null
- // : null
- //
- // For a userdefined type T which has op_True defined and L, R are
- // nullable, (L OrElse R) is computed as:
- //
- // L.HasValue
- // ? T.op_True(L.GetValueOrDefault())
- // ? L
- // : R.HasValue
- // ? (T?)(T.op_BitwiseOr(L.GetValueOrDefault(), R.GetValueOrDefault()))
- // : null
- // : null
- //
- //
- // This is the same behavior as VB. If you think about it, it makes
- // sense: it's combining the normal pattern for short-circuiting
- // operators, with the normal pattern for lifted operations: if either
- // of the operands is null, the result is also null.
- //
- internal Expression ReduceUserdefinedLifted() {
- Debug.Assert(IsLiftedLogical);
-
- var left = Parameter(_left.Type, "left");
- var right = Parameter(Right.Type, "right");
- string opName = NodeType == ExpressionType.AndAlso ? "op_False" : "op_True";
- MethodInfo opTrueFalse = TypeUtils.GetBooleanOperator(Method.DeclaringType, opName);
- Debug.Assert(opTrueFalse != null);
-
- return Block(
- new[] { left },
- Assign(left, _left),
- Condition(
- Property(left, "HasValue"),
- Condition(
- Call(opTrueFalse, Call(left, "GetValueOrDefault", null)),
- left,
- Block(
- new[] { right },
- Assign(right, _right),
- Condition(
- Property(right, "HasValue"),
- Convert(
- Call(
- Method,
- Call(left, "GetValueOrDefault", null),
- Call(right, "GetValueOrDefault", null)
- ),
- Type
- ),
- Constant(null, Type)
- )
- )
- ),
- Constant(null, Type)
- )
- );
- }
- }
-
- // Optimized representation of simple logical expressions:
- // && || == != > < >= <=
- internal sealed class LogicalBinaryExpression : BinaryExpression {
- private readonly ExpressionType _nodeType;
-
- internal LogicalBinaryExpression(ExpressionType nodeType, Expression left, Expression right)
- : base(left, right) {
- _nodeType = nodeType;
- }
-
- public sealed override Type Type {
- get { return typeof(bool); }
- }
-
- public sealed override ExpressionType NodeType {
- get { return _nodeType; }
- }
- }
-
- // Optimized assignment node, only holds onto children
- internal sealed class AssignBinaryExpression : BinaryExpression {
- internal AssignBinaryExpression(Expression left, Expression right)
- : base(left, right) {
- }
-
- public sealed override Type Type {
- get { return Left.Type; }
- }
-
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Assign; }
- }
- }
-
- // Coalesce with conversion
- // This is not a frequently used node, but rather we want to save every
- // other BinaryExpression from holding onto the null conversion lambda
- internal sealed class CoalesceConversionBinaryExpression : BinaryExpression {
- private readonly LambdaExpression _conversion;
-
- internal CoalesceConversionBinaryExpression(Expression left, Expression right, LambdaExpression conversion)
- : base(left, right) {
- _conversion = conversion;
- }
-
- internal override LambdaExpression GetConversion() {
- return _conversion;
- }
-
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Coalesce; }
- }
-
- public sealed override Type Type {
- get { return Right.Type; }
- }
- }
-
- // OpAssign with conversion
- // This is not a frequently used node, but rather we want to save every
- // other BinaryExpression from holding onto the null conversion lambda
- internal sealed class OpAssignMethodConversionBinaryExpression : MethodBinaryExpression {
- private readonly LambdaExpression _conversion;
-
- internal OpAssignMethodConversionBinaryExpression(ExpressionType nodeType, Expression left, Expression right, Type type, MethodInfo method, LambdaExpression conversion)
- : base(nodeType, left, right, type, method) {
- _conversion = conversion;
- }
-
- internal override LambdaExpression GetConversion() {
- return _conversion;
- }
- }
-
- // Class that handles most binary expressions
- // If needed, it can be optimized even more (often Type == left.Type)
- internal class SimpleBinaryExpression : BinaryExpression {
- private readonly ExpressionType _nodeType;
- private readonly Type _type;
-
- internal SimpleBinaryExpression(ExpressionType nodeType, Expression left, Expression right, Type type)
- : base(left, right) {
- _nodeType = nodeType;
- _type = type;
- }
-
- public sealed override ExpressionType NodeType {
- get { return _nodeType; }
- }
-
- public sealed override Type Type {
- get { return _type; }
- }
- }
-
- // Class that handles binary expressions with a method
- // If needed, it can be optimized even more (often Type == method.ReturnType)
- internal class MethodBinaryExpression : SimpleBinaryExpression {
- private readonly MethodInfo _method;
-
- internal MethodBinaryExpression(ExpressionType nodeType, Expression left, Expression right, Type type, MethodInfo method)
- : base(nodeType, left, right, type) {
- _method = method;
- }
-
- internal override MethodInfo GetMethod() {
- return _method;
- }
- }
-
- public partial class Expression {
-
- #region Assign
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see ref="F:ExpressionType.Assign"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression Assign(Expression left, Expression right) {
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- TypeUtils.ValidateType(left.Type);
- TypeUtils.ValidateType(right.Type);
- if (!TypeUtils.AreReferenceAssignable(left.Type, right.Type)) {
- throw Error.ExpressionTypeDoesNotMatchAssignment(right.Type, left.Type);
- }
- return new AssignBinaryExpression(left, right);
- }
-
- #endregion
-
-
- private static BinaryExpression GetUserDefinedBinaryOperator(ExpressionType binaryType, string name, Expression left, Expression right, bool liftToNull) {
- // try exact match first
- MethodInfo method = GetUserDefinedBinaryOperator(binaryType, left.Type, right.Type, name);
- if (method != null) {
- return new MethodBinaryExpression(binaryType, left, right, method.ReturnType, method);
- }
- // try lifted call
- if (TypeUtils.IsNullableType(left.Type) && TypeUtils.IsNullableType(right.Type)) {
- Type nnLeftType = TypeUtils.GetNonNullableType(left.Type);
- Type nnRightType = TypeUtils.GetNonNullableType(right.Type);
- method = GetUserDefinedBinaryOperator(binaryType, nnLeftType, nnRightType, name);
- if (method != null && method.ReturnType.IsValueType && !TypeUtils.IsNullableType(method.ReturnType)) {
- if (method.ReturnType != typeof(bool) || liftToNull) {
- return new MethodBinaryExpression(binaryType, left, right, TypeUtils.GetNullableType(method.ReturnType), method);
- } else {
- return new MethodBinaryExpression(binaryType, left, right, typeof(bool), method);
- }
- }
- }
- return null;
- }
-
-
- private static BinaryExpression GetMethodBasedBinaryOperator(ExpressionType binaryType, Expression left, Expression right, MethodInfo method, bool liftToNull) {
- System.Diagnostics.Debug.Assert(method != null);
- ValidateOperator(method);
- ParameterInfo[] pms = method.GetParametersCached();
- if (pms.Length != 2)
- throw Error.IncorrectNumberOfMethodCallArguments(method);
- if (ParameterIsAssignable(pms[0], left.Type) && ParameterIsAssignable(pms[1], right.Type)) {
- ValidateParamswithOperandsOrThrow(pms[0].ParameterType, left.Type, binaryType, method.Name);
- ValidateParamswithOperandsOrThrow(pms[1].ParameterType, right.Type, binaryType, method.Name);
- return new MethodBinaryExpression(binaryType, left, right, method.ReturnType, method);
-
- }
- // check for lifted call
- if (TypeUtils.IsNullableType(left.Type) && TypeUtils.IsNullableType(right.Type) &&
- ParameterIsAssignable(pms[0], TypeUtils.GetNonNullableType(left.Type)) &&
- ParameterIsAssignable(pms[1], TypeUtils.GetNonNullableType(right.Type)) &&
- method.ReturnType.IsValueType && !TypeUtils.IsNullableType(method.ReturnType)) {
- if (method.ReturnType != typeof(bool) || liftToNull) {
- return new MethodBinaryExpression(binaryType, left, right, TypeUtils.GetNullableType(method.ReturnType), method);
- } else {
- return new MethodBinaryExpression(binaryType, left, right, typeof(bool), method);
- }
- }
- throw Error.OperandTypesDoNotMatchParameters(binaryType, method.Name);
- }
-
- private static BinaryExpression GetMethodBasedAssignOperator(ExpressionType binaryType, Expression left, Expression right, MethodInfo method, LambdaExpression conversion, bool liftToNull) {
- BinaryExpression b = GetMethodBasedBinaryOperator(binaryType, left, right, method, liftToNull);
- if (conversion == null) {
- // return type must be assignable back to the left type
- if (!TypeUtils.AreReferenceAssignable(left.Type, b.Type)) {
- throw Error.UserDefinedOpMustHaveValidReturnType(binaryType, b.Method.Name);
- }
- } else {
- // add the conversion to the result
- ValidateOpAssignConversionLambda(conversion, b.Left, b.Method, b.NodeType);
- b = new OpAssignMethodConversionBinaryExpression(b.NodeType, b.Left, b.Right, b.Left.Type, b.Method, conversion);
- }
- return b;
- }
-
-
- private static BinaryExpression GetUserDefinedBinaryOperatorOrThrow(ExpressionType binaryType, string name, Expression left, Expression right, bool liftToNull) {
- BinaryExpression b = GetUserDefinedBinaryOperator(binaryType, name, left, right, liftToNull);
- if (b != null) {
- ParameterInfo[] pis = b.Method.GetParametersCached();
- ValidateParamswithOperandsOrThrow(pis[0].ParameterType, left.Type, binaryType, name);
- ValidateParamswithOperandsOrThrow(pis[1].ParameterType, right.Type, binaryType, name);
- return b;
- }
- throw Error.BinaryOperatorNotDefined(binaryType, left.Type, right.Type);
- }
-
- private static BinaryExpression GetUserDefinedAssignOperatorOrThrow(ExpressionType binaryType, string name, Expression left, Expression right, LambdaExpression conversion, bool liftToNull) {
- BinaryExpression b = GetUserDefinedBinaryOperatorOrThrow(binaryType, name, left, right, liftToNull);
- if (conversion == null) {
- // return type must be assignable back to the left type
- if (!TypeUtils.AreReferenceAssignable(left.Type, b.Type)) {
- throw Error.UserDefinedOpMustHaveValidReturnType(binaryType, b.Method.Name);
- }
- } else {
- // add the conversion to the result
- ValidateOpAssignConversionLambda(conversion, b.Left, b.Method, b.NodeType);
- b = new OpAssignMethodConversionBinaryExpression(b.NodeType, b.Left, b.Right, b.Left.Type, b.Method, conversion);
- }
- return b;
- }
-
-
- private static MethodInfo GetUserDefinedBinaryOperator(ExpressionType binaryType, Type leftType, Type rightType, string name) {
- // UNDONE: This algorithm is wrong, we should be checking for uniqueness and erroring if
- // UNDONE: it is defined on both types.
- Type[] types = new Type[] { leftType, rightType };
- Type nnLeftType = TypeUtils.GetNonNullableType(leftType);
- Type nnRightType = TypeUtils.GetNonNullableType(rightType);
- BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
- MethodInfo method = nnLeftType.GetMethodValidated(name, flags, null, types, null);
- if (method == null && !TypeUtils.AreEquivalent(leftType, rightType)) {
- method = nnRightType.GetMethodValidated(name, flags, null, types, null);
- }
-
- if (IsLiftingConditionalLogicalOperator(leftType, rightType, method, binaryType)) {
- method = GetUserDefinedBinaryOperator(binaryType, nnLeftType, nnRightType, name);
- }
- return method;
- }
-
-
- private static bool IsLiftingConditionalLogicalOperator(Type left, Type right, MethodInfo method, ExpressionType binaryType) {
- return TypeUtils.IsNullableType(right) &&
- TypeUtils.IsNullableType(left) &&
- method == null &&
- (binaryType == ExpressionType.AndAlso || binaryType == ExpressionType.OrElse);
- }
-
-
- internal static bool ParameterIsAssignable(ParameterInfo pi, Type argType) {
- Type pType = pi.ParameterType;
- if (pType.IsByRef)
- pType = pType.GetElementType();
- return TypeUtils.AreReferenceAssignable(pType, argType);
- }
-
-
- private static void ValidateParamswithOperandsOrThrow(Type paramType, Type operandType, ExpressionType exprType, string name) {
- if (TypeUtils.IsNullableType(paramType) && !TypeUtils.IsNullableType(operandType)) {
- throw Error.OperandTypesDoNotMatchParameters(exprType, name);
- }
- }
-
-
- private static void ValidateOperator(MethodInfo method) {
- System.Diagnostics.Debug.Assert(method != null);
- ValidateMethodInfo(method);
- if (!method.IsStatic)
- throw Error.UserDefinedOperatorMustBeStatic(method);
- if (method.ReturnType == typeof(void))
- throw Error.UserDefinedOperatorMustNotBeVoid(method);
- }
-
-
- private static void ValidateMethodInfo(MethodInfo method) {
- if (method.IsGenericMethodDefinition)
- throw Error.MethodIsGeneric(method);
- if (method.ContainsGenericParameters)
- throw Error.MethodContainsGenericParameters(method);
- }
-
-
- private static bool IsNullComparison(Expression left, Expression right) {
- // If we have x==null, x!=null, null==x or null!=x where x is
- // nullable but not null, then this is treated as a call to x.HasValue
- // and is legal even if there is no equality operator defined on the
- // type of x.
- if (IsNullConstant(left) && !IsNullConstant(right) && TypeUtils.IsNullableType(right.Type)) {
- return true;
- }
- if (IsNullConstant(right) && !IsNullConstant(left) && TypeUtils.IsNullableType(left.Type)) {
- return true;
- }
- return false;
- }
-
-
- // Note: this has different meaning than ConstantCheck.IsNull
- // That function attempts to determine if the result of a tree will be
- // null at runtime. This function is used at tree construction time and
- // only looks for a ConstantExpression with a null Value. It can't
- // become "smarter" or that would break tree construction.
- private static bool IsNullConstant(Expression e) {
- var c = e as ConstantExpression;
- return c != null && c.Value == null;
- }
-
-
- private static void ValidateUserDefinedConditionalLogicOperator(ExpressionType nodeType, Type left, Type right, MethodInfo method) {
- ValidateOperator(method);
- ParameterInfo[] pms = method.GetParametersCached();
- if (pms.Length != 2)
- throw Error.IncorrectNumberOfMethodCallArguments(method);
- if (!ParameterIsAssignable(pms[0], left)) {
- if (!(TypeUtils.IsNullableType(left) && ParameterIsAssignable(pms[0], TypeUtils.GetNonNullableType(left))))
- throw Error.OperandTypesDoNotMatchParameters(nodeType, method.Name);
- }
- if (!ParameterIsAssignable(pms[1], right)) {
- if (!(TypeUtils.IsNullableType(right) && ParameterIsAssignable(pms[1], TypeUtils.GetNonNullableType(right))))
- throw Error.OperandTypesDoNotMatchParameters(nodeType, method.Name);
- }
- if (pms[0].ParameterType != pms[1].ParameterType) {
- throw Error.UserDefinedOpMustHaveConsistentTypes(nodeType, method.Name);
- }
- if (method.ReturnType != pms[0].ParameterType) {
- throw Error.UserDefinedOpMustHaveConsistentTypes(nodeType, method.Name);
- }
- if (IsValidLiftedConditionalLogicalOperator(left, right, pms)) {
- left = TypeUtils.GetNonNullableType(left);
- right = TypeUtils.GetNonNullableType(left);
- }
- MethodInfo opTrue = TypeUtils.GetBooleanOperator(method.DeclaringType, "op_True");
- MethodInfo opFalse = TypeUtils.GetBooleanOperator(method.DeclaringType, "op_False");
- if (opTrue == null || opTrue.ReturnType != typeof(bool) ||
- opFalse == null || opFalse.ReturnType != typeof(bool)) {
- throw Error.LogicalOperatorMustHaveBooleanOperators(nodeType, method.Name);
- }
- VerifyOpTrueFalse(nodeType, left, opFalse);
- VerifyOpTrueFalse(nodeType, left, opTrue);
- }
-
- private static void VerifyOpTrueFalse(ExpressionType nodeType, Type left, MethodInfo opTrue) {
- ParameterInfo[] pmsOpTrue = opTrue.GetParametersCached();
- if (pmsOpTrue.Length != 1)
- throw Error.IncorrectNumberOfMethodCallArguments(opTrue);
-
- if (!ParameterIsAssignable(pmsOpTrue[0], left)) {
- if (!(TypeUtils.IsNullableType(left) && ParameterIsAssignable(pmsOpTrue[0], TypeUtils.GetNonNullableType(left))))
- throw Error.OperandTypesDoNotMatchParameters(nodeType, opTrue.Name);
- }
- }
-
- private static bool IsValidLiftedConditionalLogicalOperator(Type left, Type right, ParameterInfo[] pms) {
- return TypeUtils.AreEquivalent(left, right) &&
- TypeUtils.IsNullableType(right) &&
- TypeUtils.AreEquivalent(pms[1].ParameterType, TypeUtils.GetNonNullableType(right));
- }
-
-
- /// <summary>
- /// Creates a BinaryExpression, given the left and right operands, by calling an appropriate factory method.
- /// </summary>
- /// <param name="binaryType">The ExpressionType that specifies the type of binary operation.</param>
- /// <param name="left">An Expression that represents the left operand.</param>
- /// <param name="right">An Expression that represents the right operand.</param>
- /// <returns>The BinaryExpression that results from calling the appropriate factory method.</returns>
- public static BinaryExpression MakeBinary(ExpressionType binaryType, Expression left, Expression right) {
- return MakeBinary(binaryType, left, right, false, null, null);
- }
-
- /// <summary>
- /// Creates a BinaryExpression, given the left and right operands, by calling an appropriate factory method.
- /// </summary>
- /// <param name="binaryType">The ExpressionType that specifies the type of binary operation.</param>
- /// <param name="left">An Expression that represents the left operand.</param>
- /// <param name="right">An Expression that represents the right operand.</param>
- /// <param name="liftToNull">true to set IsLiftedToNull to true; false to set IsLiftedToNull to false.</param>
- /// <param name="method">A MethodInfo that specifies the implementing method.</param>
- /// <returns>The BinaryExpression that results from calling the appropriate factory method.</returns>
- public static BinaryExpression MakeBinary(ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo method) {
- return MakeBinary(binaryType, left, right, liftToNull, method, null);
- }
-
- ///
- /// <summary>
- /// Creates a BinaryExpression, given the left and right operands, by calling an appropriate factory method.
- /// </summary>
- /// <param name="binaryType">The ExpressionType that specifies the type of binary operation.</param>
- /// <param name="left">An Expression that represents the left operand.</param>
- /// <param name="right">An Expression that represents the right operand.</param>
- /// <param name="liftToNull">true to set IsLiftedToNull to true; false to set IsLiftedToNull to false.</param>
- /// <param name="method">A MethodInfo that specifies the implementing method.</param>
- /// <param name="conversion">A LambdaExpression that represents a type conversion function. This parameter is used if binaryType is Coalesce or compound assignment.</param>
- /// <returns>The BinaryExpression that results from calling the appropriate factory method.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- public static BinaryExpression MakeBinary(ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo method, LambdaExpression conversion) {
- switch (binaryType) {
- case ExpressionType.Add:
- return Add(left, right, method);
- case ExpressionType.AddChecked:
- return AddChecked(left, right, method);
- case ExpressionType.Subtract:
- return Subtract(left, right, method);
- case ExpressionType.SubtractChecked:
- return SubtractChecked(left, right, method);
- case ExpressionType.Multiply:
- return Multiply(left, right, method);
- case ExpressionType.MultiplyChecked:
- return MultiplyChecked(left, right, method);
- case ExpressionType.Divide:
- return Divide(left, right, method);
- case ExpressionType.Modulo:
- return Modulo(left, right, method);
- case ExpressionType.Power:
- return Power(left, right, method);
- case ExpressionType.And:
- return And(left, right, method);
- case ExpressionType.AndAlso:
- return AndAlso(left, right, method);
- case ExpressionType.Or:
- return Or(left, right, method);
- case ExpressionType.OrElse:
- return OrElse(left, right, method);
- case ExpressionType.LessThan:
- return LessThan(left, right, liftToNull, method);
- case ExpressionType.LessThanOrEqual:
- return LessThanOrEqual(left, right, liftToNull, method);
- case ExpressionType.GreaterThan:
- return GreaterThan(left, right, liftToNull, method);
- case ExpressionType.GreaterThanOrEqual:
- return GreaterThanOrEqual(left, right, liftToNull, method);
- case ExpressionType.Equal:
- return Equal(left, right, liftToNull, method);
- case ExpressionType.NotEqual:
- return NotEqual(left, right, liftToNull, method);
- case ExpressionType.ExclusiveOr:
- return ExclusiveOr(left, right, method);
- case ExpressionType.Coalesce:
- return Coalesce(left, right, conversion);
- case ExpressionType.ArrayIndex:
- return ArrayIndex(left, right);
- case ExpressionType.RightShift:
- return RightShift(left, right, method);
- case ExpressionType.LeftShift:
- return LeftShift(left, right, method);
- case ExpressionType.Assign:
- return Assign(left, right);
- case ExpressionType.AddAssign:
- return AddAssign(left, right, method, conversion);
- case ExpressionType.AndAssign:
- return AndAssign(left, right, method, conversion);
- case ExpressionType.DivideAssign:
- return DivideAssign(left, right, method, conversion);
- case ExpressionType.ExclusiveOrAssign:
- return ExclusiveOrAssign(left, right, method, conversion);
- case ExpressionType.LeftShiftAssign:
- return LeftShiftAssign(left, right, method, conversion);
- case ExpressionType.ModuloAssign:
- return ModuloAssign(left, right, method, conversion);
- case ExpressionType.MultiplyAssign:
- return MultiplyAssign(left, right, method, conversion);
- case ExpressionType.OrAssign:
- return OrAssign(left, right, method, conversion);
- case ExpressionType.PowerAssign:
- return PowerAssign(left, right, method, conversion);
- case ExpressionType.RightShiftAssign:
- return RightShiftAssign(left, right, method, conversion);
- case ExpressionType.SubtractAssign:
- return SubtractAssign(left, right, method, conversion);
- case ExpressionType.AddAssignChecked:
- return AddAssignChecked(left, right, method, conversion);
- case ExpressionType.SubtractAssignChecked:
- return SubtractAssignChecked(left, right, method, conversion);
- case ExpressionType.MultiplyAssignChecked:
- return MultiplyAssignChecked(left, right, method, conversion);
- default:
- throw Error.UnhandledBinary(binaryType);
- }
- }
-
- #region Equality Operators
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an equality comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Equal"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression Equal(Expression left, Expression right) {
- return Equal(left, right, false, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an equality comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="liftToNull">true to set IsLiftedToNull to true; false to set IsLiftedToNull to false.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Equal"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.IsLiftedToNull"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression Equal(Expression left, Expression right, bool liftToNull, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- return GetEqualityComparisonOperator(ExpressionType.Equal, "op_Equality", left, right, liftToNull);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.Equal, left, right, method, liftToNull);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a reference equality comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Equal"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression ReferenceEqual(Expression left, Expression right) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (TypeUtils.HasReferenceEquality(left.Type, right.Type)) {
- return new LogicalBinaryExpression(ExpressionType.Equal, left, right);
- }
- throw Error.ReferenceEqualityNotDefined(left.Type, right.Type);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an inequality comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.NotEqual"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression NotEqual(Expression left, Expression right) {
- return NotEqual(left, right, false, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an inequality comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="liftToNull">true to set IsLiftedToNull to true; false to set IsLiftedToNull to false.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.NotEqual"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.IsLiftedToNull"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression NotEqual(Expression left, Expression right, bool liftToNull, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- return GetEqualityComparisonOperator(ExpressionType.NotEqual, "op_Inequality", left, right, liftToNull);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.NotEqual, left, right, method, liftToNull);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a reference inequality comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.NotEqual"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression ReferenceNotEqual(Expression left, Expression right) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (TypeUtils.HasReferenceEquality(left.Type, right.Type)) {
- return new LogicalBinaryExpression(ExpressionType.NotEqual, left, right);
- }
- throw Error.ReferenceEqualityNotDefined(left.Type, right.Type);
- }
-
- private static BinaryExpression GetEqualityComparisonOperator(ExpressionType binaryType, string opName, Expression left, Expression right, bool liftToNull) {
- // known comparison - numeric types, bools, object, enums
- if (left.Type == right.Type && (TypeUtils.IsNumeric(left.Type) ||
- left.Type == typeof(object) ||
- TypeUtils.IsBool(left.Type) ||
- TypeUtils.GetNonNullableType(left.Type).IsEnum)) {
- if (TypeUtils.IsNullableType(left.Type) && liftToNull) {
- return new SimpleBinaryExpression(binaryType, left, right, typeof(bool?));
- } else {
- return new LogicalBinaryExpression(binaryType, left, right);
- }
- }
- // look for user defined operator
- BinaryExpression b = GetUserDefinedBinaryOperator(binaryType, opName, left, right, liftToNull);
- if (b != null) {
- return b;
- }
- if (TypeUtils.HasBuiltInEqualityOperator(left.Type, right.Type) || IsNullComparison(left, right)) {
- if (TypeUtils.IsNullableType(left.Type) && liftToNull) {
- return new SimpleBinaryExpression(binaryType, left, right, typeof(bool?));
- } else {
- return new LogicalBinaryExpression(binaryType, left, right);
- }
- }
- throw Error.BinaryOperatorNotDefined(binaryType, left.Type, right.Type);
- }
-
- #endregion
-
- #region Comparison Expressions
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a "greater than" numeric comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.GreaterThan"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression GreaterThan(Expression left, Expression right) {
- return GreaterThan(left, right, false, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a "greater than" numeric comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="liftToNull">true to set IsLiftedToNull to true; false to set IsLiftedToNull to false.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.GreaterThan"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.IsLiftedToNull"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression GreaterThan(Expression left, Expression right, bool liftToNull, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- return GetComparisonOperator(ExpressionType.GreaterThan, "op_GreaterThan", left, right, liftToNull);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.GreaterThan, left, right, method, liftToNull);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a "less than" numeric comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.LessThan"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
-
- public static BinaryExpression LessThan(Expression left, Expression right) {
- return LessThan(left, right, false, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a "less than" numeric comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="liftToNull">true to set IsLiftedToNull to true; false to set IsLiftedToNull to false.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.LessThan"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.IsLiftedToNull"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression LessThan(Expression left, Expression right, bool liftToNull, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- return GetComparisonOperator(ExpressionType.LessThan, "op_LessThan", left, right, liftToNull);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.LessThan, left, right, method, liftToNull);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a "greater than or equal" numeric comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.GreaterThanOrEqual"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression GreaterThanOrEqual(Expression left, Expression right) {
- return GreaterThanOrEqual(left, right, false, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a "greater than or equal" numeric comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="liftToNull">true to set IsLiftedToNull to true; false to set IsLiftedToNull to false.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.GreaterThanOrEqual"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.IsLiftedToNull"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression GreaterThanOrEqual(Expression left, Expression right, bool liftToNull, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- return GetComparisonOperator(ExpressionType.GreaterThanOrEqual, "op_GreaterThanOrEqual", left, right, liftToNull);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.GreaterThanOrEqual, left, right, method, liftToNull);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a "less than or equal" numeric comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.LessThanOrEqual"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression LessThanOrEqual(Expression left, Expression right) {
- return LessThanOrEqual(left, right, false, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a "less than or equal" numeric comparison.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="liftToNull">true to set IsLiftedToNull to true; false to set IsLiftedToNull to false.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.LessThanOrEqual"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.IsLiftedToNull"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression LessThanOrEqual(Expression left, Expression right, bool liftToNull, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- return GetComparisonOperator(ExpressionType.LessThanOrEqual, "op_LessThanOrEqual", left, right, liftToNull);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.LessThanOrEqual, left, right, method, liftToNull);
- }
-
-
- private static BinaryExpression GetComparisonOperator(ExpressionType binaryType, string opName, Expression left, Expression right, bool liftToNull) {
- if (left.Type == right.Type && TypeUtils.IsNumeric(left.Type)) {
- if (TypeUtils.IsNullableType(left.Type) && liftToNull) {
- return new SimpleBinaryExpression(binaryType, left, right, typeof(bool?));
- } else {
- return new LogicalBinaryExpression(binaryType, left, right);
- }
- }
- return GetUserDefinedBinaryOperatorOrThrow(binaryType, opName, left, right, liftToNull);
- }
-
- #endregion
-
- #region Boolean Expressions
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a conditional AND operation that evaluates the second operand only if it has to.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.AndAlso"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression AndAlso(Expression left, Expression right) {
- return AndAlso(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a conditional AND operation that evaluates the second operand only if it has to.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.AndAlso"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression AndAlso(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- Type returnType;
- if (method == null) {
- if (left.Type == right.Type) {
- if (left.Type == typeof(bool)) {
- return new LogicalBinaryExpression(ExpressionType.AndAlso, left, right);
- } else if (left.Type == typeof(bool?)) {
- return new SimpleBinaryExpression(ExpressionType.AndAlso, left, right, left.Type);
- }
- }
- method = GetUserDefinedBinaryOperator(ExpressionType.AndAlso, left.Type, right.Type, "op_BitwiseAnd");
- if (method != null) {
- ValidateUserDefinedConditionalLogicOperator(ExpressionType.AndAlso, left.Type, right.Type, method);
- returnType = (TypeUtils.IsNullableType(left.Type) && TypeUtils.AreEquivalent(method.ReturnType, TypeUtils.GetNonNullableType(left.Type))) ? left.Type : method.ReturnType;
- return new MethodBinaryExpression(ExpressionType.AndAlso, left, right, returnType, method);
- }
- throw Error.BinaryOperatorNotDefined(ExpressionType.AndAlso, left.Type, right.Type);
- }
- ValidateUserDefinedConditionalLogicOperator(ExpressionType.AndAlso, left.Type, right.Type, method);
- returnType = (TypeUtils.IsNullableType(left.Type) && TypeUtils.AreEquivalent(method.ReturnType, TypeUtils.GetNonNullableType(left.Type))) ? left.Type : method.ReturnType;
- return new MethodBinaryExpression(ExpressionType.AndAlso, left, right, returnType, method);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a conditional OR operation that evaluates the second operand only if it has to.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.OrElse"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression OrElse(Expression left, Expression right) {
- return OrElse(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a conditional OR operation that evaluates the second operand only if it has to.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.OrElse"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression OrElse(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- Type returnType;
- if (method == null) {
- if (left.Type == right.Type) {
- if (left.Type == typeof(bool)) {
- return new LogicalBinaryExpression(ExpressionType.OrElse, left, right);
- } else if (left.Type == typeof(bool?)) {
- return new SimpleBinaryExpression(ExpressionType.OrElse, left, right, left.Type);
- }
- }
- method = GetUserDefinedBinaryOperator(ExpressionType.OrElse, left.Type, right.Type, "op_BitwiseOr");
- if (method != null) {
- ValidateUserDefinedConditionalLogicOperator(ExpressionType.OrElse, left.Type, right.Type, method);
- returnType = (TypeUtils.IsNullableType(left.Type) && method.ReturnType == TypeUtils.GetNonNullableType(left.Type)) ? left.Type : method.ReturnType;
- return new MethodBinaryExpression(ExpressionType.OrElse, left, right, returnType, method);
- }
- throw Error.BinaryOperatorNotDefined(ExpressionType.OrElse, left.Type, right.Type);
- }
- ValidateUserDefinedConditionalLogicOperator(ExpressionType.OrElse, left.Type, right.Type, method);
- returnType = (TypeUtils.IsNullableType(left.Type) && method.ReturnType == TypeUtils.GetNonNullableType(left.Type)) ? left.Type : method.ReturnType;
- return new MethodBinaryExpression(ExpressionType.OrElse, left, right, returnType, method);
- }
-
- #endregion
-
- #region Coalescing Expressions
-
-
- /// <summary>
- /// Creates a BinaryExpression that represents a coalescing operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A BinaryExpression that has the NodeType property equal to Coalesce and the Left and Right properties set to the specified values.</returns>
- public static BinaryExpression Coalesce(Expression left, Expression right) {
- return Coalesce(left, right, null);
- }
-
-
- /// <summary>
- /// Creates a BinaryExpression that represents a coalescing operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="conversion">A LambdaExpression to set the Conversion property equal to.</param>
- /// <returns>A BinaryExpression that has the NodeType property equal to Coalesce and the Left, Right and Conversion properties set to the specified values.
- /// </returns>
- public static BinaryExpression Coalesce(Expression left, Expression right, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
-
- if (conversion == null) {
- Type resultType = ValidateCoalesceArgTypes(left.Type, right.Type);
- return new SimpleBinaryExpression(ExpressionType.Coalesce, left, right, resultType);
- }
-
- if (left.Type.IsValueType && !TypeUtils.IsNullableType(left.Type)) {
- throw Error.CoalesceUsedOnNonNullType();
- }
-
- Type delegateType = conversion.Type;
- Debug.Assert(typeof(System.MulticastDelegate).IsAssignableFrom(delegateType) && delegateType != typeof(System.MulticastDelegate));
- MethodInfo method = delegateType.GetMethod("Invoke");
- if (method.ReturnType == typeof(void)) {
- throw Error.UserDefinedOperatorMustNotBeVoid(conversion);
- }
- ParameterInfo[] pms = method.GetParametersCached();
- Debug.Assert(pms.Length == conversion.Parameters.Count);
- if (pms.Length != 1) {
- throw Error.IncorrectNumberOfMethodCallArguments(conversion);
- }
- // The return type must match exactly.
- // CONSIDER: We could weaken this restriction and
- // CONSIDER: say that the return type must be assignable to from
- // CONSIDER: the return type of the lambda.
- if (!TypeUtils.AreEquivalent(method.ReturnType, right.Type)) {
- throw Error.OperandTypesDoNotMatchParameters(ExpressionType.Coalesce, conversion.ToString());
- }
- // The parameter of the conversion lambda must either be assignable
- // from the erased or unerased type of the left hand side.
- if (!ParameterIsAssignable(pms[0], TypeUtils.GetNonNullableType(left.Type)) &&
- !ParameterIsAssignable(pms[0], left.Type)) {
- throw Error.OperandTypesDoNotMatchParameters(ExpressionType.Coalesce, conversion.ToString());
- }
- return new CoalesceConversionBinaryExpression(left, right, conversion);
- }
-
-
- private static Type ValidateCoalesceArgTypes(Type left, Type right) {
- Type leftStripped = TypeUtils.GetNonNullableType(left);
- if (left.IsValueType && !TypeUtils.IsNullableType(left)) {
- throw Error.CoalesceUsedOnNonNullType();
- } else if (TypeUtils.IsNullableType(left) && TypeUtils.IsImplicitlyConvertible(right, leftStripped)) {
- return leftStripped;
- } else if (TypeUtils.IsImplicitlyConvertible(right, left)) {
- return left;
- } else if (TypeUtils.IsImplicitlyConvertible(leftStripped, right)) {
- return right;
- } else {
- throw Error.ArgumentTypesMustMatch();
- }
- }
-
-
-
- #endregion
-
- #region Arithmetic Expressions
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic addition operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Add"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression Add(Expression left, Expression right) {
- return Add(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic addition operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Add"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression Add(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- return new SimpleBinaryExpression(ExpressionType.Add, left, right, left.Type);
- }
- return GetUserDefinedBinaryOperatorOrThrow(ExpressionType.Add, "op_Addition", left, right, true);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.Add, left, right, method, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an addition assignment operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.AddAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression AddAssign(Expression left, Expression right) {
- return AddAssign(left, right, null, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an addition assignment operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.AddAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression AddAssign(Expression left, Expression right, MethodInfo method) {
- return AddAssign(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an addition assignment operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.AddAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
-
- public static BinaryExpression AddAssign(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- // conversion is not supported for binary ops on arithmetic types without operator overloading
- if (conversion != null) {
- throw Error.ConversionIsNotSupportedForArithmeticTypes();
- }
- return new SimpleBinaryExpression(ExpressionType.AddAssign, left, right, left.Type);
- }
- return GetUserDefinedAssignOperatorOrThrow(ExpressionType.AddAssign, "op_Addition", left, right, conversion, true);
- }
- return GetMethodBasedAssignOperator(ExpressionType.AddAssign, left, right, method, conversion, true);
- }
-
- private static void ValidateOpAssignConversionLambda(LambdaExpression conversion, Expression left, MethodInfo method, ExpressionType nodeType) {
- Type delegateType = conversion.Type;
- Debug.Assert(typeof(System.MulticastDelegate).IsAssignableFrom(delegateType) && delegateType != typeof(System.MulticastDelegate));
- MethodInfo mi = delegateType.GetMethod("Invoke");
- ParameterInfo[] pms = mi.GetParametersCached();
- Debug.Assert(pms.Length == conversion.Parameters.Count);
- if (pms.Length != 1) {
- throw Error.IncorrectNumberOfMethodCallArguments(conversion);
- }
- if (!TypeUtils.AreEquivalent(mi.ReturnType, left.Type)) {
- throw Error.OperandTypesDoNotMatchParameters(nodeType, conversion.ToString());
- }
- if (method != null) {
- // The parameter type of conversion lambda must be the same as the return type of the overload method
- if (!TypeUtils.AreEquivalent(pms[0].ParameterType, method.ReturnType)) {
- throw Error.OverloadOperatorTypeDoesNotMatchConversionType(nodeType, conversion.ToString());
- }
- }
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an addition assignment operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to
- /// <see cref="F:ExpressionType.AddAssignChecked"/> and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/>
- /// properties set to the specified values.
- /// </returns>
- public static BinaryExpression AddAssignChecked(Expression left, Expression right) {
- return AddAssignChecked(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an addition assignment operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.AddAssignChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression AddAssignChecked(Expression left, Expression right, MethodInfo method) {
- return AddAssignChecked(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an addition assignment operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.AddAssignChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression AddAssignChecked(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
-
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- // conversion is not supported for binary ops on arithmetic types without operator overloading
- if (conversion != null) {
- throw Error.ConversionIsNotSupportedForArithmeticTypes();
- }
- return new SimpleBinaryExpression(ExpressionType.AddAssignChecked, left, right, left.Type);
- }
- return GetUserDefinedAssignOperatorOrThrow(ExpressionType.AddAssignChecked, "op_Addition", left, right, conversion, true);
- }
- return GetMethodBasedAssignOperator(ExpressionType.AddAssignChecked, left, right, method, conversion, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic addition operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.AddChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression AddChecked(Expression left, Expression right) {
- return AddChecked(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic addition operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.AddChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression AddChecked(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- return new SimpleBinaryExpression(ExpressionType.AddChecked, left, right, left.Type);
- }
- return GetUserDefinedBinaryOperatorOrThrow(ExpressionType.AddChecked, "op_Addition", left, right, false);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.AddChecked, left, right, method, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic subtraction operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Subtract"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression Subtract(Expression left, Expression right) {
- return Subtract(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic subtraction operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Subtract"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression Subtract(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- return new SimpleBinaryExpression(ExpressionType.Subtract, left, right, left.Type);
- }
- return GetUserDefinedBinaryOperatorOrThrow(ExpressionType.Subtract, "op_Subtraction", left, right, true);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.Subtract, left, right, method, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a subtraction assignment operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.SubtractAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression SubtractAssign(Expression left, Expression right) {
- return SubtractAssign(left, right, null, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a subtraction assignment operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.SubtractAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression SubtractAssign(Expression left, Expression right, MethodInfo method) {
- return SubtractAssign(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a subtraction assignment operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.SubtractAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression SubtractAssign(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- // conversion is not supported for binary ops on arithmetic types without operator overloading
- if (conversion != null) {
- throw Error.ConversionIsNotSupportedForArithmeticTypes();
- }
- return new SimpleBinaryExpression(ExpressionType.SubtractAssign, left, right, left.Type);
- }
- return GetUserDefinedAssignOperatorOrThrow(ExpressionType.SubtractAssign, "op_Subtraction", left, right, conversion, true);
- }
- return GetMethodBasedAssignOperator(ExpressionType.SubtractAssign, left, right, method, conversion, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a subtraction assignment operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.SubtractAssignChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression SubtractAssignChecked(Expression left, Expression right) {
- return SubtractAssignChecked(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a subtraction assignment operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.SubtractAssignChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression SubtractAssignChecked(Expression left, Expression right, MethodInfo method) {
- return SubtractAssignChecked(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a subtraction assignment operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.SubtractAssignChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression SubtractAssignChecked(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- // conversion is not supported for binary ops on arithmetic types without operator overloading
- if (conversion != null) {
- throw Error.ConversionIsNotSupportedForArithmeticTypes();
- }
- return new SimpleBinaryExpression(ExpressionType.SubtractAssignChecked, left, right, left.Type);
- }
- return GetUserDefinedAssignOperatorOrThrow(ExpressionType.SubtractAssignChecked, "op_Subtraction", left, right, conversion, true);
- }
- return GetMethodBasedAssignOperator(ExpressionType.SubtractAssignChecked, left, right, method, conversion, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic subtraction operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.SubtractChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression SubtractChecked(Expression left, Expression right) {
- return SubtractChecked(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic subtraction operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.SubtractChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression SubtractChecked(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- return new SimpleBinaryExpression(ExpressionType.SubtractChecked, left, right, left.Type);
- }
- return GetUserDefinedBinaryOperatorOrThrow(ExpressionType.SubtractChecked, "op_Subtraction", left, right, true);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.SubtractChecked, left, right, method, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic division operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Divide"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression Divide(Expression left, Expression right) {
- return Divide(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic division operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Divide"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression Divide(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- return new SimpleBinaryExpression(ExpressionType.Divide, left, right, left.Type);
- }
- return GetUserDefinedBinaryOperatorOrThrow(ExpressionType.Divide, "op_Division", left, right, true);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.Divide, left, right, method, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a division assignment operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.DivideAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression DivideAssign(Expression left, Expression right) {
- return DivideAssign(left, right, null, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a division assignment operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.DivideAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression DivideAssign(Expression left, Expression right, MethodInfo method) {
- return DivideAssign(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a division assignment operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.DivideAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression DivideAssign(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- // conversion is not supported for binary ops on arithmetic types without operator overloading
- if (conversion != null) {
- throw Error.ConversionIsNotSupportedForArithmeticTypes();
- }
- return new SimpleBinaryExpression(ExpressionType.DivideAssign, left, right, left.Type);
- }
- return GetUserDefinedAssignOperatorOrThrow(ExpressionType.DivideAssign, "op_Division", left, right, conversion, true);
- }
- return GetMethodBasedAssignOperator(ExpressionType.DivideAssign, left, right, method, conversion, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic remainder operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Modulo"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression Modulo(Expression left, Expression right) {
- return Modulo(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic remainder operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Modulo"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression Modulo(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- return new SimpleBinaryExpression(ExpressionType.Modulo, left, right, left.Type);
- }
- return GetUserDefinedBinaryOperatorOrThrow(ExpressionType.Modulo, "op_Modulus", left, right, true);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.Modulo, left, right, method, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a remainder assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.ModuloAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression ModuloAssign(Expression left, Expression right) {
- return ModuloAssign(left, right, null, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a remainder assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.ModuloAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression ModuloAssign(Expression left, Expression right, MethodInfo method) {
- return ModuloAssign(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a remainder assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.ModuloAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression ModuloAssign(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- // conversion is not supported for binary ops on arithmetic types without operator overloading
- if (conversion != null) {
- throw Error.ConversionIsNotSupportedForArithmeticTypes();
- }
- return new SimpleBinaryExpression(ExpressionType.ModuloAssign, left, right, left.Type);
- }
- return GetUserDefinedAssignOperatorOrThrow(ExpressionType.ModuloAssign, "op_Modulus", left, right, conversion, true);
- }
- return GetMethodBasedAssignOperator(ExpressionType.ModuloAssign, left, right, method, conversion, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic multiplication operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Multiply"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression Multiply(Expression left, Expression right) {
- return Multiply(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic multiplication operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Multiply"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression Multiply(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- return new SimpleBinaryExpression(ExpressionType.Multiply, left, right, left.Type);
- }
- return GetUserDefinedBinaryOperatorOrThrow(ExpressionType.Multiply, "op_Multiply", left, right, true);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.Multiply, left, right, method, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a multiplication assignment operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.MultiplyAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression MultiplyAssign(Expression left, Expression right) {
- return MultiplyAssign(left, right, null, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a multiplication assignment operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.MultiplyAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression MultiplyAssign(Expression left, Expression right, MethodInfo method) {
- return MultiplyAssign(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a multiplication assignment operation that does not have overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.MultiplyAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression MultiplyAssign(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- // conversion is not supported for binary ops on arithmetic types without operator overloading
- if (conversion != null) {
- throw Error.ConversionIsNotSupportedForArithmeticTypes();
- }
- return new SimpleBinaryExpression(ExpressionType.MultiplyAssign, left, right, left.Type);
- }
- return GetUserDefinedAssignOperatorOrThrow(ExpressionType.MultiplyAssign, "op_Multiply", left, right, conversion, true);
- }
- return GetMethodBasedAssignOperator(ExpressionType.MultiplyAssign, left, right, method, conversion, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a multiplication assignment operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.MultiplyAssignChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression MultiplyAssignChecked(Expression left, Expression right) {
- return MultiplyAssignChecked(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a multiplication assignment operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.MultiplyAssignChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression MultiplyAssignChecked(Expression left, Expression right, MethodInfo method) {
- return MultiplyAssignChecked(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a multiplication assignment operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.MultiplyAssignChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression MultiplyAssignChecked(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- // conversion is not supported for binary ops on arithmetic types without operator overloading
- if (conversion != null) {
- throw Error.ConversionIsNotSupportedForArithmeticTypes();
- }
- return new SimpleBinaryExpression(ExpressionType.MultiplyAssignChecked, left, right, left.Type);
- }
- return GetUserDefinedAssignOperatorOrThrow(ExpressionType.MultiplyAssignChecked, "op_Multiply", left, right, conversion, true);
- }
- return GetMethodBasedAssignOperator(ExpressionType.MultiplyAssignChecked, left, right, method, conversion, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic multiplication operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.MultiplyChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression MultiplyChecked(Expression left, Expression right) {
- return MultiplyChecked(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an arithmetic multiplication operation that has overflow checking.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.MultiplyChecked"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression MultiplyChecked(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)) {
- return new SimpleBinaryExpression(ExpressionType.MultiplyChecked, left, right, left.Type);
- }
- return GetUserDefinedBinaryOperatorOrThrow(ExpressionType.MultiplyChecked, "op_Multiply", left, right, true);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.MultiplyChecked, left, right, method, true);
- }
-
- private static bool IsSimpleShift(Type left, Type right) {
- return TypeUtils.IsInteger(left)
- && TypeUtils.GetNonNullableType(right) == typeof(int);
- }
-
- private static Type GetResultTypeOfShift(Type left, Type right) {
- if (!left.IsNullableType() && right.IsNullableType()) {
- // lift the result type to Nullable<T>
- return typeof(Nullable<>).MakeGenericType(left);
- }
- return left;
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an bitwise left-shift operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.LeftShift"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression LeftShift(Expression left, Expression right) {
- return LeftShift(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an bitwise left-shift operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.LeftShift"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression LeftShift(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (IsSimpleShift(left.Type, right.Type)) {
- Type resultType = GetResultTypeOfShift(left.Type, right.Type);
- return new SimpleBinaryExpression(ExpressionType.LeftShift, left, right, resultType);
- }
- return GetUserDefinedBinaryOperatorOrThrow(ExpressionType.LeftShift, "op_LeftShift", left, right, true);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.LeftShift, left, right, method, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise left-shift assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.LeftShiftAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression LeftShiftAssign(Expression left, Expression right) {
- return LeftShiftAssign(left, right, null, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise left-shift assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.LeftShiftAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression LeftShiftAssign(Expression left, Expression right, MethodInfo method) {
- return LeftShiftAssign(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise left-shift assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.LeftShiftAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression LeftShiftAssign(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (IsSimpleShift(left.Type, right.Type)) {
- // conversion is not supported for binary ops on arithmetic types without operator overloading
- if (conversion != null) {
- throw Error.ConversionIsNotSupportedForArithmeticTypes();
- }
- Type resultType = GetResultTypeOfShift(left.Type, right.Type);
- return new SimpleBinaryExpression(ExpressionType.LeftShiftAssign, left, right, resultType);
- }
- return GetUserDefinedAssignOperatorOrThrow(ExpressionType.LeftShiftAssign, "op_LeftShift", left, right, conversion, true);
- }
- return GetMethodBasedAssignOperator(ExpressionType.LeftShiftAssign, left, right, method, conversion, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an bitwise right-shift operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.RightShift"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression RightShift(Expression left, Expression right) {
- return RightShift(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an bitwise right-shift operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.RightShift"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression RightShift(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (IsSimpleShift(left.Type, right.Type)) {
- Type resultType = GetResultTypeOfShift(left.Type, right.Type);
- return new SimpleBinaryExpression(ExpressionType.RightShift, left, right, resultType);
- }
- return GetUserDefinedBinaryOperatorOrThrow(ExpressionType.RightShift, "op_RightShift", left, right, true);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.RightShift, left, right, method, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise right-shift assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.RightShiftAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression RightShiftAssign(Expression left, Expression right) {
- return RightShiftAssign(left, right, null, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise right-shift assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.RightShiftAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression RightShiftAssign(Expression left, Expression right, MethodInfo method) {
- return RightShiftAssign(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise right-shift assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.RightShiftAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression RightShiftAssign(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (IsSimpleShift(left.Type, right.Type)) {
- // conversion is not supported for binary ops on arithmetic types without operator overloading
- if (conversion != null) {
- throw Error.ConversionIsNotSupportedForArithmeticTypes();
- }
- Type resultType = GetResultTypeOfShift(left.Type, right.Type);
- return new SimpleBinaryExpression(ExpressionType.RightShiftAssign, left, right, resultType);
- }
- return GetUserDefinedAssignOperatorOrThrow(ExpressionType.RightShiftAssign, "op_RightShift", left, right, conversion, true);
- }
- return GetMethodBasedAssignOperator(ExpressionType.RightShiftAssign, left, right, method, conversion, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an bitwise AND operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.And"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression And(Expression left, Expression right) {
- return And(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an bitwise AND operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.And"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression And(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsIntegerOrBool(left.Type)) {
- return new SimpleBinaryExpression(ExpressionType.And, left, right, left.Type);
- }
- return GetUserDefinedBinaryOperatorOrThrow(ExpressionType.And, "op_BitwiseAnd", left, right, true);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.And, left, right, method, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise AND assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.AndAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression AndAssign(Expression left, Expression right) {
- return AndAssign(left, right, null, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise AND assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.AndAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression AndAssign(Expression left, Expression right, MethodInfo method) {
- return AndAssign(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise AND assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.AndAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression AndAssign(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsIntegerOrBool(left.Type)) {
- // conversion is not supported for binary ops on arithmetic types without operator overloading
- if (conversion != null) {
- throw Error.ConversionIsNotSupportedForArithmeticTypes();
- }
- return new SimpleBinaryExpression(ExpressionType.AndAssign, left, right, left.Type);
- }
- return GetUserDefinedAssignOperatorOrThrow(ExpressionType.AndAssign, "op_BitwiseAnd", left, right, conversion, true);
- }
- return GetMethodBasedAssignOperator(ExpressionType.AndAssign, left, right, method, conversion, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an bitwise OR operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Or"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression Or(Expression left, Expression right) {
- return Or(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents an bitwise OR operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Or"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression Or(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsIntegerOrBool(left.Type)) {
- return new SimpleBinaryExpression(ExpressionType.Or, left, right, left.Type);
- }
- return GetUserDefinedBinaryOperatorOrThrow(ExpressionType.Or, "op_BitwiseOr", left, right, true);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.Or, left, right, method, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise OR assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.OrAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression OrAssign(Expression left, Expression right) {
- return OrAssign(left, right, null, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise OR assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.OrAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression OrAssign(Expression left, Expression right, MethodInfo method) {
- return OrAssign(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise OR assignment operation.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.OrAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression OrAssign(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsIntegerOrBool(left.Type)) {
- // conversion is not supported for binary ops on arithmetic types without operator overloading
- if (conversion != null) {
- throw Error.ConversionIsNotSupportedForArithmeticTypes();
- }
- return new SimpleBinaryExpression(ExpressionType.OrAssign, left, right, left.Type);
- }
- return GetUserDefinedAssignOperatorOrThrow(ExpressionType.OrAssign, "op_BitwiseOr", left, right, conversion, true);
- }
- return GetMethodBasedAssignOperator(ExpressionType.OrAssign, left, right, method, conversion, true);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise or logical XOR operation, using op_ExclusiveOr for user-defined types.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.ExclusiveOr"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression ExclusiveOr(Expression left, Expression right) {
- return ExclusiveOr(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise or logical XOR operation, using op_ExclusiveOr for user-defined types.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.ExclusiveOr"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression ExclusiveOr(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsIntegerOrBool(left.Type)) {
- return new SimpleBinaryExpression(ExpressionType.ExclusiveOr, left, right, left.Type);
- }
- return GetUserDefinedBinaryOperatorOrThrow(ExpressionType.ExclusiveOr, "op_ExclusiveOr", left, right, true);
- }
- return GetMethodBasedBinaryOperator(ExpressionType.ExclusiveOr, left, right, method, true);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise or logical XOR assignment operation, using op_ExclusiveOr for user-defined types.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.ExclusiveOrAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression ExclusiveOrAssign(Expression left, Expression right) {
- return ExclusiveOrAssign(left, right, null, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise or logical XOR assignment operation, using op_ExclusiveOr for user-defined types.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.ExclusiveOrAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression ExclusiveOrAssign(Expression left, Expression right, MethodInfo method) {
- return ExclusiveOrAssign(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents a bitwise or logical XOR assignment operation, using op_ExclusiveOr for user-defined types.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.ExclusiveOrAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression ExclusiveOrAssign(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- if (left.Type == right.Type && TypeUtils.IsIntegerOrBool(left.Type)) {
- // conversion is not supported for binary ops on arithmetic types without operator overloading
- if (conversion != null) {
- throw Error.ConversionIsNotSupportedForArithmeticTypes();
- }
- return new SimpleBinaryExpression(ExpressionType.ExclusiveOrAssign, left, right, left.Type);
- }
- return GetUserDefinedAssignOperatorOrThrow(ExpressionType.ExclusiveOrAssign, "op_ExclusiveOr", left, right, conversion, true);
- }
- return GetMethodBasedAssignOperator(ExpressionType.ExclusiveOrAssign, left, right, method, conversion, true);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents raising a number to a power.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Power"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression Power(Expression left, Expression right) {
- return Power(left, right, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents raising a number to a power.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.Power"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression Power(Expression left, Expression right, MethodInfo method) {
- RequiresCanRead(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- Type mathType = typeof(System.Math);
- method = mathType.GetMethod("Pow", BindingFlags.Static | BindingFlags.Public);
- if (method == null) {
- throw Error.BinaryOperatorNotDefined(ExpressionType.Power, left.Type, right.Type);
- }
- }
- return GetMethodBasedBinaryOperator(ExpressionType.Power, left, right, method, true);
- }
-
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents raising an expression to a power and assigning the result back to the expression.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.PowerAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/> and <see cref="P:BinaryExpression.Right"/> properties set to the specified values.</returns>
- public static BinaryExpression PowerAssign(Expression left, Expression right) {
- return PowerAssign(left, right, null, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents raising an expression to a power and assigning the result back to the expression.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.PowerAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, and <see cref="P:BinaryExpression.Method"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression PowerAssign(Expression left, Expression right, MethodInfo method) {
- return PowerAssign(left, right, method, null);
- }
-
- /// <summary>
- /// Creates a <see cref="BinaryExpression"/> that represents raising an expression to a power and assigning the result back to the expression.
- /// </summary>
- /// <param name="left">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Left"/> property equal to.</param>
- /// <param name="right">An <see cref="Expression"/> to set the <see cref="P:BinaryExpression.Right"/> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="P:BinaryExpression.Method"/> property equal to.</param>
- /// <param name="conversion">A <see cref="LambdaExpression"/> to set the <see cref="P:BinaryExpression.Conversion"/> property equal to.</param>
- /// <returns>A <see cref="BinaryExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to <see cref="F:ExpressionType.PowerAssign"/>
- /// and the <see cref="P:BinaryExpression.Left"/>, <see cref="P:BinaryExpression.Right"/>, <see cref="P:BinaryExpression.Method"/>,
- /// and <see cref="P:BinaryExpression.Conversion"/> properties set to the specified values.
- /// </returns>
- public static BinaryExpression PowerAssign(Expression left, Expression right, MethodInfo method, LambdaExpression conversion) {
- RequiresCanRead(left, "left");
- RequiresCanWrite(left, "left");
- RequiresCanRead(right, "right");
- if (method == null) {
- Type mathType = typeof(System.Math);
- method = mathType.GetMethod("Pow", BindingFlags.Static | BindingFlags.Public);
- if (method == null) {
- throw Error.BinaryOperatorNotDefined(ExpressionType.PowerAssign, left.Type, right.Type);
- }
- }
- return GetMethodBasedAssignOperator(ExpressionType.PowerAssign, left, right, method, conversion, true);
- }
-
- #endregion
-
- #region ArrayIndex Expression
-
-
- /// <summary>
- /// Creates a BinaryExpression that represents applying an array index operator to an array of rank one.
- /// </summary>
- /// <param name="array">An Expression to set the Left property equal to.</param>
- /// <param name="index">An Expression to set the Right property equal to.</param>
- /// <returns>A BinaryExpression that has the NodeType property equal to ArrayIndex and the Left and Right properties set to the specified values.</returns>
- public static BinaryExpression ArrayIndex(Expression array, Expression index) {
- RequiresCanRead(array, "array");
- RequiresCanRead(index, "index");
- if (index.Type != typeof(int)) {
- throw Error.ArgumentMustBeArrayIndexType();
- }
-
- Type arrayType = array.Type;
- if (!arrayType.IsArray) {
- throw Error.ArgumentMustBeArray();
- }
- if (arrayType.GetArrayRank() != 1) {
- throw Error.IncorrectNumberOfIndexes();
- }
-
- return new SimpleBinaryExpression(ExpressionType.ArrayIndex, array, index, arrayType.GetElementType());
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/BlockExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/BlockExpression.cs
deleted file mode 100644
index 372b05ec9da..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/BlockExpression.cs
+++ /dev/null
@@ -1,813 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Threading;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents a block that contains a sequence of expressions where variables can be defined.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.BlockExpressionProxy))]
- public class BlockExpression : Expression {
- /// <summary>
- /// Gets the expressions in this block.
- /// </summary>
- public ReadOnlyCollection<Expression> Expressions {
- get { return GetOrMakeExpressions(); }
- }
-
- /// <summary>
- /// Gets the variables defined in this block.
- /// </summary>
- public ReadOnlyCollection<ParameterExpression> Variables {
- get {
- return GetOrMakeVariables();
- }
- }
-
- /// <summary>
- /// Gets the last expression in this block.
- /// </summary>
- public Expression Result {
- get {
- Debug.Assert(ExpressionCount > 0);
- return GetExpression(ExpressionCount - 1);
- }
- }
-
- internal BlockExpression() {
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitBlock(this);
- }
-
- /// <summary>
- /// Returns the node type of this Expression. Extension nodes should return
- /// ExpressionType.Extension when overriding this method.
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Block; }
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents.
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public override Type Type {
- get { return GetExpression(ExpressionCount - 1).Type; }
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="variables">The <see cref="Variables" /> property of the result.</param>
- /// <param name="expressions">The <see cref="Expressions" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public BlockExpression Update(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) {
- if (variables == Variables && expressions == Expressions) {
- return this;
- }
-
- return Expression.Block(Type, variables, expressions);
- }
-
- internal virtual Expression GetExpression(int index) {
- throw ContractUtils.Unreachable;
- }
-
- internal virtual int ExpressionCount {
- get {
- throw ContractUtils.Unreachable;
- }
- }
-
- internal virtual ReadOnlyCollection<Expression> GetOrMakeExpressions() {
- throw ContractUtils.Unreachable;
- }
-
- internal virtual ParameterExpression GetVariable(int index) {
- throw ContractUtils.Unreachable;
- }
-
- internal virtual int VariableCount {
- get {
- return 0;
- }
- }
-
- internal virtual ReadOnlyCollection<ParameterExpression> GetOrMakeVariables() {
- return EmptyReadOnlyCollection<ParameterExpression>.Instance;
- }
-
- /// <summary>
- /// Makes a copy of this node replacing the parameters/args with the provided values. The
- /// shape of the parameters/args needs to match the shape of the current block - in other
- /// words there should be the same # of parameters and args.
- ///
- /// parameters can be null in which case the existing parameters are used.
- ///
- /// This helper is provided to allow re-writing of nodes to not depend on the specific optimized
- /// subclass of BlockExpression which is being used.
- /// </summary>
- internal virtual BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) {
- throw ContractUtils.Unreachable;
- }
-
- /// <summary>
- /// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T.
- ///
- /// This is similar to the ReturnReadOnly which only takes a single argument. This version
- /// supports nodes which hold onto 5 Expressions and puts all of the arguments into the
- /// ReadOnlyCollection.
- ///
- /// Ultimately this means if we create the readonly collection we will be slightly more wasteful as we'll
- /// have a readonly collection + some fields in the type. The DLR internally avoids accessing anything
- /// which would force the readonly collection to be created.
- ///
- /// This is used by BlockExpression5 and MethodCallExpression5.
- /// </summary>
- internal static ReadOnlyCollection<Expression> ReturnReadOnlyExpressions(BlockExpression provider, ref object collection) {
- Expression tObj = collection as Expression;
- if (tObj != null) {
- // otherwise make sure only one readonly collection ever gets exposed
- Interlocked.CompareExchange(
- ref collection,
- new ReadOnlyCollection<Expression>(new BlockExpressionList(provider, tObj)),
- tObj
- );
- }
-
- // and return what is not guaranteed to be a readonly collection
- return (ReadOnlyCollection<Expression>)collection;
- }
- }
-
- #region Specialized Subclasses
-
- internal sealed class Block2 : BlockExpression {
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
- private readonly Expression _arg1; // storage for the 2nd argument.
-
- internal Block2(Expression arg0, Expression arg1) {
- _arg0 = arg0;
- _arg1 = arg1;
- }
-
- internal override Expression GetExpression(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- case 1: return _arg1;
- default: throw new InvalidOperationException();
- }
- }
-
- internal override int ExpressionCount {
- get {
- return 2;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() {
- return ReturnReadOnlyExpressions(this, ref _arg0);
- }
-
- internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) {
- Debug.Assert(args.Length == 2);
- Debug.Assert(variables == null || variables.Count == 0);
-
- return new Block2(args[0], args[1]);
- }
- }
-
- internal sealed class Block3 : BlockExpression {
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
- private readonly Expression _arg1, _arg2; // storage for the 2nd and 3rd arguments.
-
- internal Block3(Expression arg0, Expression arg1, Expression arg2) {
- _arg0 = arg0;
- _arg1 = arg1;
- _arg2 = arg2;
- }
-
- internal override Expression GetExpression(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- case 1: return _arg1;
- case 2: return _arg2;
- default: throw new InvalidOperationException();
- }
- }
-
- internal override int ExpressionCount {
- get {
- return 3;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() {
- return ReturnReadOnlyExpressions(this, ref _arg0);
- }
-
- internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) {
- Debug.Assert(args.Length == 3);
- Debug.Assert(variables == null || variables.Count == 0);
-
- return new Block3(args[0], args[1], args[2]);
- }
- }
-
- internal sealed class Block4 : BlockExpression {
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
- private readonly Expression _arg1, _arg2, _arg3; // storarg for the 2nd, 3rd, and 4th arguments.
-
- internal Block4(Expression arg0, Expression arg1, Expression arg2, Expression arg3) {
- _arg0 = arg0;
- _arg1 = arg1;
- _arg2 = arg2;
- _arg3 = arg3;
- }
-
- internal override Expression GetExpression(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- case 1: return _arg1;
- case 2: return _arg2;
- case 3: return _arg3;
- default: throw new InvalidOperationException();
- }
- }
-
- internal override int ExpressionCount {
- get {
- return 4;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() {
- return ReturnReadOnlyExpressions(this, ref _arg0);
- }
-
- internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) {
- Debug.Assert(args.Length == 4);
- Debug.Assert(variables == null || variables.Count == 0);
-
- return new Block4(args[0], args[1], args[2], args[3]);
- }
- }
-
- internal sealed class Block5 : BlockExpression {
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
- private readonly Expression _arg1, _arg2, _arg3, _arg4; // storage for the 2nd - 5th args.
-
- internal Block5(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) {
- _arg0 = arg0;
- _arg1 = arg1;
- _arg2 = arg2;
- _arg3 = arg3;
- _arg4 = arg4;
- }
-
- internal override Expression GetExpression(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- case 1: return _arg1;
- case 2: return _arg2;
- case 3: return _arg3;
- case 4: return _arg4;
- default: throw new InvalidOperationException();
- }
- }
-
- internal override int ExpressionCount {
- get {
- return 5;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() {
- return ReturnReadOnlyExpressions(this, ref _arg0);
- }
-
- internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) {
- Debug.Assert(args.Length == 5);
- Debug.Assert(variables == null || variables.Count == 0);
-
- return new Block5(args[0], args[1], args[2], args[3], args[4]);
- }
- }
-
- internal class BlockN : BlockExpression {
- private IList<Expression> _expressions; // either the original IList<Expression> or a ReadOnlyCollection if the user has accessed it.
-
- internal BlockN(IList<Expression> expressions) {
- Debug.Assert(expressions.Count != 0);
-
- _expressions = expressions;
- }
-
- internal override Expression GetExpression(int index) {
- Debug.Assert(index >= 0 && index < _expressions.Count);
-
- return _expressions[index];
- }
-
- internal override int ExpressionCount {
- get {
- return _expressions.Count;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() {
- return ReturnReadOnly(ref _expressions);
- }
-
- internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) {
- Debug.Assert(variables == null || variables.Count == 0);
-
- return new BlockN(args);
- }
- }
-
- internal class ScopeExpression : BlockExpression {
- private IList<ParameterExpression> _variables; // list of variables or ReadOnlyCollection if the user has accessed the readonly collection
-
- internal ScopeExpression(IList<ParameterExpression> variables) {
- _variables = variables;
- }
-
- internal override int VariableCount {
- get {
- return _variables.Count;
- }
- }
-
- internal override ParameterExpression GetVariable(int index) {
- return _variables[index];
- }
-
- internal override ReadOnlyCollection<ParameterExpression> GetOrMakeVariables() {
- return ReturnReadOnly(ref _variables);
- }
-
- protected IList<ParameterExpression> VariablesList {
- get {
- return _variables;
- }
- }
-
- // Used for rewrite of the nodes to either reuse existing set of variables if not rewritten.
- internal IList<ParameterExpression> ReuseOrValidateVariables(ReadOnlyCollection<ParameterExpression> variables) {
- if (variables != null && variables != VariablesList) {
- // Need to validate the new variables (uniqueness, not byref)
- ValidateVariables(variables, "variables");
- return variables;
- } else {
- return VariablesList;
- }
- }
- }
-
- internal sealed class Scope1 : ScopeExpression {
- private object _body;
-
- internal Scope1(IList<ParameterExpression> variables, Expression body)
- : base(variables) {
- _body = body;
- }
-
- internal override Expression GetExpression(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_body);
- default: throw new InvalidOperationException();
- }
- }
-
- internal override int ExpressionCount {
- get {
- return 1;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() {
- return ReturnReadOnlyExpressions(this, ref _body);
- }
-
- internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) {
- Debug.Assert(args.Length == 1);
- Debug.Assert(variables == null || variables.Count == VariableCount);
-
- return new Scope1(ReuseOrValidateVariables(variables), args[0]);
- }
- }
-
- internal class ScopeN : ScopeExpression {
- private IList<Expression> _body;
-
- internal ScopeN(IList<ParameterExpression> variables, IList<Expression> body)
- : base(variables) {
- _body = body;
- }
-
- internal override Expression GetExpression(int index) {
- return _body[index];
- }
-
- internal override int ExpressionCount {
- get {
- return _body.Count;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() {
- return ReturnReadOnly(ref _body);
- }
-
- internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) {
- Debug.Assert(args.Length == ExpressionCount);
- Debug.Assert(variables == null || variables.Count == VariableCount);
-
- return new ScopeN(ReuseOrValidateVariables(variables), args);
- }
- }
-
- internal class ScopeWithType : ScopeN {
- private readonly Type _type;
-
- internal ScopeWithType(IList<ParameterExpression> variables, IList<Expression> expressions, Type type)
- : base(variables, expressions) {
- _type = type;
- }
-
- public sealed override Type Type {
- get { return _type; }
- }
-
- internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) {
- Debug.Assert(args.Length == ExpressionCount);
- Debug.Assert(variables == null || variables.Count == VariableCount);
-
- return new ScopeWithType(ReuseOrValidateVariables(variables), args, _type);
- }
- }
-
- #endregion
-
- #region Block List Classes
-
- /// <summary>
- /// Provides a wrapper around an IArgumentProvider which exposes the argument providers
- /// members out as an IList of Expression. This is used to avoid allocating an array
- /// which needs to be stored inside of a ReadOnlyCollection. Instead this type has
- /// the same amount of overhead as an array without duplicating the storage of the
- /// elements. This ensures that internally we can avoid creating and copying arrays
- /// while users of the Expression trees also don't pay a size penalty for this internal
- /// optimization. See IArgumentProvider for more general information on the Expression
- /// tree optimizations being used here.
- /// </summary>
- internal class BlockExpressionList : IList<Expression> {
- private readonly BlockExpression _block;
- private readonly Expression _arg0;
-
- internal BlockExpressionList(BlockExpression provider, Expression arg0) {
- _block = provider;
- _arg0 = arg0;
- }
-
- #region IList<Expression> Members
-
- public int IndexOf(Expression item) {
- if (_arg0 == item) {
- return 0;
- }
-
- for (int i = 1; i < _block.ExpressionCount; i++) {
- if (_block.GetExpression(i) == item) {
- return i;
- }
- }
-
- return -1;
- }
-
- public void Insert(int index, Expression item) {
- throw ContractUtils.Unreachable;
- }
-
- public void RemoveAt(int index) {
- throw ContractUtils.Unreachable;
- }
-
- public Expression this[int index] {
- get {
- if (index == 0) {
- return _arg0;
- }
-
- return _block.GetExpression(index);
- }
- set {
- throw ContractUtils.Unreachable;
- }
- }
-
- #endregion
-
- #region ICollection<Expression> Members
-
- public void Add(Expression item) {
- throw ContractUtils.Unreachable;
- }
-
- public void Clear() {
- throw ContractUtils.Unreachable;
- }
-
- public bool Contains(Expression item) {
- return IndexOf(item) != -1;
- }
-
- public void CopyTo(Expression[] array, int arrayIndex) {
- array[arrayIndex++] = _arg0;
- for (int i = 1; i < _block.ExpressionCount; i++) {
- array[arrayIndex++] = _block.GetExpression(i);
- }
- }
-
- public int Count {
- get { return _block.ExpressionCount; }
- }
-
- public bool IsReadOnly {
- get { return true; }
- }
-
- public bool Remove(Expression item) {
- throw ContractUtils.Unreachable;
- }
-
- #endregion
-
- #region IEnumerable<Expression> Members
-
- public IEnumerator<Expression> GetEnumerator() {
- yield return _arg0;
-
- for (int i = 1; i < _block.ExpressionCount; i++) {
- yield return _block.GetExpression(i);
- }
- }
-
- #endregion
-
- #region IEnumerable Members
-
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
- yield return _arg0;
-
- for (int i = 1; i < _block.ExpressionCount; i++) {
- yield return _block.GetExpression(i);
- }
- }
-
- #endregion
- }
-
- #endregion
-
- public partial class Expression {
-
- /// <summary>
- /// Creates a <see cref="BlockExpression"/> that contains two expressions and has no variables.
- /// </summary>
- /// <param name="arg0">The first expression in the block.</param>
- /// <param name="arg1">The second expression in the block.</param>
- /// <returns>The created <see cref="BlockExpression"/>.</returns>
- public static BlockExpression Block(Expression arg0, Expression arg1) {
- RequiresCanRead(arg0, "arg0");
- RequiresCanRead(arg1, "arg1");
-
- return new Block2(arg0, arg1);
- }
- /// <summary>
- /// Creates a <see cref="BlockExpression"/> that contains three expressions and has no variables.
- /// </summary>
- /// <param name="arg0">The first expression in the block.</param>
- /// <param name="arg1">The second expression in the block.</param>
- /// <param name="arg2">The third expression in the block.</param>
- /// <returns>The created <see cref="BlockExpression"/>.</returns>
- public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2) {
- RequiresCanRead(arg0, "arg0");
- RequiresCanRead(arg1, "arg1");
- RequiresCanRead(arg2, "arg2");
- return new Block3(arg0, arg1, arg2);
- }
-
- /// <summary>
- /// Creates a <see cref="BlockExpression"/> that contains four expressions and has no variables.
- /// </summary>
- /// <param name="arg0">The first expression in the block.</param>
- /// <param name="arg1">The second expression in the block.</param>
- /// <param name="arg2">The third expression in the block.</param>
- /// <param name="arg3">The fourth expression in the block.</param>
- /// <returns>The created <see cref="BlockExpression"/>.</returns>
- public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3) {
- RequiresCanRead(arg0, "arg0");
- RequiresCanRead(arg1, "arg1");
- RequiresCanRead(arg2, "arg2");
- RequiresCanRead(arg3, "arg3");
- return new Block4(arg0, arg1, arg2, arg3);
- }
-
- /// <summary>
- /// Creates a <see cref="BlockExpression"/> that contains five expressions and has no variables.
- /// </summary>
- /// <param name="arg0">The first expression in the block.</param>
- /// <param name="arg1">The second expression in the block.</param>
- /// <param name="arg2">The third expression in the block.</param>
- /// <param name="arg3">The fourth expression in the block.</param>
- /// <param name="arg4">The fifth expression in the block.</param>
- /// <returns>The created <see cref="BlockExpression"/>.</returns>
- public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) {
- RequiresCanRead(arg0, "arg0");
- RequiresCanRead(arg1, "arg1");
- RequiresCanRead(arg2, "arg2");
- RequiresCanRead(arg3, "arg3");
- RequiresCanRead(arg4, "arg4");
-
- return new Block5(arg0, arg1, arg2, arg3, arg4);
- }
-
- /// <summary>
- /// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables.
- /// </summary>
- /// <param name="expressions">The expressions in the block.</param>
- /// <returns>The created <see cref="BlockExpression"/>.</returns>
- public static BlockExpression Block(params Expression[] expressions) {
- ContractUtils.RequiresNotNull(expressions, "expressions");
-
- switch (expressions.Length) {
- case 2: return Block(expressions[0], expressions[1]);
- case 3: return Block(expressions[0], expressions[1], expressions[2]);
- case 4: return Block(expressions[0], expressions[1], expressions[2], expressions[3]);
- case 5: return Block(expressions[0], expressions[1], expressions[2], expressions[3], expressions[4]);
- default:
- ContractUtils.RequiresNotEmpty(expressions, "expressions");
- RequiresCanRead(expressions, "expressions");
- return new BlockN(expressions.Copy());
- }
- }
-
- /// <summary>
- /// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables.
- /// </summary>
- /// <param name="expressions">The expressions in the block.</param>
- /// <returns>The created <see cref="BlockExpression"/>.</returns>
- public static BlockExpression Block(IEnumerable<Expression> expressions) {
- return Block(EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions);
- }
-
- /// <summary>
- /// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type.
- /// </summary>
- /// <param name="type">The result type of the block.</param>
- /// <param name="expressions">The expressions in the block.</param>
- /// <returns>The created <see cref="BlockExpression"/>.</returns>
- public static BlockExpression Block(Type type, params Expression[] expressions) {
- ContractUtils.RequiresNotNull(expressions, "expressions");
- return Block(type, (IEnumerable<Expression>)expressions);
- }
-
- /// <summary>
- /// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type.
- /// </summary>
- /// <param name="type">The result type of the block.</param>
- /// <param name="expressions">The expressions in the block.</param>
- /// <returns>The created <see cref="BlockExpression"/>.</returns>
- public static BlockExpression Block(Type type, IEnumerable<Expression> expressions) {
- return Block(type, EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions);
- }
-
- /// <summary>
- /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
- /// </summary>
- /// <param name="variables">The variables in the block.</param>
- /// <param name="expressions">The expressions in the block.</param>
- /// <returns>The created <see cref="BlockExpression"/>.</returns>
- public static BlockExpression Block(IEnumerable<ParameterExpression> variables, params Expression[] expressions) {
- return Block(variables, (IEnumerable<Expression>)expressions);
- }
-
- /// <summary>
- /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
- /// </summary>
- /// <param name="type">The result type of the block.</param>
- /// <param name="variables">The variables in the block.</param>
- /// <param name="expressions">The expressions in the block.</param>
- /// <returns>The created <see cref="BlockExpression"/>.</returns>
- public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, params Expression[] expressions) {
- return Block(type, variables, (IEnumerable<Expression>)expressions);
- }
-
- /// <summary>
- /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
- /// </summary>
- /// <param name="variables">The variables in the block.</param>
- /// <param name="expressions">The expressions in the block.</param>
- /// <returns>The created <see cref="BlockExpression"/>.</returns>
- public static BlockExpression Block(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) {
- ContractUtils.RequiresNotNull(expressions, "expressions");
- var expressionList = expressions.ToReadOnly();
- ContractUtils.RequiresNotEmpty(expressionList, "expressions");
- RequiresCanRead(expressionList, "expressions");
-
- return Block(expressionList.Last().Type, variables, expressionList);
- }
-
- /// <summary>
- /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
- /// </summary>
- /// <param name="type">The result type of the block.</param>
- /// <param name="variables">The variables in the block.</param>
- /// <param name="expressions">The expressions in the block.</param>
- /// <returns>The created <see cref="BlockExpression"/>.</returns>
- public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) {
- ContractUtils.RequiresNotNull(type, "type");
- ContractUtils.RequiresNotNull(expressions, "expressions");
-
- var expressionList = expressions.ToReadOnly();
- var variableList = variables.ToReadOnly();
-
- ContractUtils.RequiresNotEmpty(expressionList, "expressions");
- RequiresCanRead(expressionList, "expressions");
- ValidateVariables(variableList, "variables");
-
- Expression last = expressionList.Last();
- if (type != typeof(void)) {
- if (!TypeUtils.AreReferenceAssignable(type, last.Type)) {
- throw Error.ArgumentTypesMustMatch();
- }
- }
-
- if (!TypeUtils.AreEquivalent(type, last.Type)) {
- return new ScopeWithType(variableList, expressionList, type);
- } else {
- if (expressionList.Count == 1) {
- return new Scope1(variableList, expressionList[0]);
- } else {
- return new ScopeN(variableList, expressionList);
- }
- }
- }
-
- // Checks that all variables are non-null, not byref, and unique.
- internal static void ValidateVariables(ReadOnlyCollection<ParameterExpression> varList, string collectionName) {
- if (varList.Count == 0) {
- return;
- }
-
- int count = varList.Count;
- var set = new Set<ParameterExpression>(count);
- for (int i = 0; i < count; i++) {
- ParameterExpression v = varList[i];
- if (v == null) {
- throw new ArgumentNullException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}[{1}]", collectionName, set.Count));
- }
- if (v.IsByRef) {
- throw Error.VariableMustNotBeByRef(v, v.Type);
- }
- if (set.Contains(v)) {
- throw Error.DuplicateVariable(v);
- }
- set.Add(v);
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/CatchBlock.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/CatchBlock.cs
deleted file mode 100644
index 08e2ab59502..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/CatchBlock.cs
+++ /dev/null
@@ -1,172 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- /// <summary>
- /// Represents a catch statement in a try block.
- /// This must have the same return type (i.e., the type of <see cref="P:CatchBlock.Body"/>) as the try block it is associated with.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.CatchBlockProxy))]
- public sealed class CatchBlock {
- private readonly Type _test;
- private readonly ParameterExpression _var;
- private readonly Expression _body;
- private readonly Expression _filter;
-
- internal CatchBlock(Type test, ParameterExpression variable, Expression body, Expression filter) {
- _test = test;
- _var = variable;
- _body = body;
- _filter = filter;
- }
-
- /// <summary>
- /// Gets a reference to the <see cref="Exception"/> object caught by this handler.
- /// </summary>
- public ParameterExpression Variable {
- get { return _var; }
- }
-
- /// <summary>
- /// Gets the type of <see cref="Exception"/> this handler catches.
- /// </summary>
- public Type Test {
- get { return _test; }
- }
-
- /// <summary>
- /// Gets the body of the catch block.
- /// </summary>
- public Expression Body {
- get { return _body; }
- }
-
- /// <summary>
- /// Gets the body of the <see cref="CatchBlock"/>'s filter.
- /// </summary>
- public Expression Filter {
- get {
- return _filter;
- }
- }
-
- /// <summary>
- /// Returns a <see cref="String"/> that represents the current <see cref="Object"/>.
- /// </summary>
- /// <returns>A <see cref="String"/> that represents the current <see cref="Object"/>. </returns>
- public override string ToString() {
- return ExpressionStringBuilder.CatchBlockToString(this);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="variable">The <see cref="Variable" /> property of the result.</param>
- /// <param name="filter">The <see cref="Filter" /> property of the result.</param>
- /// <param name="body">The <see cref="Body" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public CatchBlock Update(ParameterExpression variable, Expression filter, Expression body) {
- if (variable == Variable && filter == Filter && body == Body) {
- return this;
- }
- return Expression.MakeCatchBlock(Test, variable, body, filter);
- }
- }
-
- public partial class Expression {
- /// <summary>
- /// Creates a <see cref="CatchBlock"/> representing a catch statement.
- /// The <see cref="Type"/> of object to be caught can be specified but no reference to the object
- /// will be available for use in the <see cref="CatchBlock"/>.
- /// </summary>
- /// <param name="type">The <see cref="Type"/> of <see cref="Exception"/> this <see cref="CatchBlock"/> will handle.</param>
- /// <param name="body">The body of the catch statement.</param>
- /// <returns>The created <see cref="CatchBlock"/>.</returns>
- public static CatchBlock Catch(Type type, Expression body) {
- return MakeCatchBlock(type, null, body, null);
- }
-
- /// <summary>
- /// Creates a <see cref="CatchBlock"/> representing a catch statement with a reference to the caught object for use in the handler body.
- /// </summary>
- /// <param name="variable">A <see cref="ParameterExpression"/> representing a reference to the <see cref="Exception"/> object caught by this handler.</param>
- /// <param name="body">The body of the catch statement.</param>
- /// <returns>The created <see cref="CatchBlock"/>.</returns>
- public static CatchBlock Catch(ParameterExpression variable, Expression body) {
- ContractUtils.RequiresNotNull(variable, "variable");
- return MakeCatchBlock(variable.Type, variable, body, null);
- }
-
- /// <summary>
- /// Creates a <see cref="CatchBlock"/> representing a catch statement with
- /// an <see cref="Exception"/> filter but no reference to the caught <see cref="Exception"/> object.
- /// </summary>
- /// <param name="type">The <see cref="Type"/> of <see cref="Exception"/> this <see cref="CatchBlock"/> will handle.</param>
- /// <param name="body">The body of the catch statement.</param>
- /// <param name="filter">The body of the <see cref="Exception"/> filter.</param>
- /// <returns>The created <see cref="CatchBlock"/>.</returns>
- public static CatchBlock Catch(Type type, Expression body, Expression filter) {
- return MakeCatchBlock(type, null, body, filter);
- }
-
- /// <summary>
- /// Creates a <see cref="CatchBlock"/> representing a catch statement with
- /// an <see cref="Exception"/> filter and a reference to the caught <see cref="Exception"/> object.
- /// </summary>
- /// <param name="variable">A <see cref="ParameterExpression"/> representing a reference to the <see cref="Exception"/> object caught by this handler.</param>
- /// <param name="body">The body of the catch statement.</param>
- /// <param name="filter">The body of the <see cref="Exception"/> filter.</param>
- /// <returns>The created <see cref="CatchBlock"/>.</returns>
- public static CatchBlock Catch(ParameterExpression variable, Expression body, Expression filter) {
- ContractUtils.RequiresNotNull(variable, "variable");
- return MakeCatchBlock(variable.Type, variable, body, filter);
- }
-
- /// <summary>
- /// Creates a <see cref="CatchBlock"/> representing a catch statement with the specified elements.
- /// </summary>
- /// <param name="type">The <see cref="Type"/> of <see cref="Exception"/> this <see cref="CatchBlock"/> will handle.</param>
- /// <param name="variable">A <see cref="ParameterExpression"/> representing a reference to the <see cref="Exception"/> object caught by this handler.</param>
- /// <param name="body">The body of the catch statement.</param>
- /// <param name="filter">The body of the <see cref="Exception"/> filter.</param>
- /// <returns>The created <see cref="CatchBlock"/>.</returns>
- /// <remarks><paramref name="type"/> must be non-null and match the type of <paramref name="variable"/> (if it is supplied).</remarks>
- public static CatchBlock MakeCatchBlock(Type type, ParameterExpression variable, Expression body, Expression filter) {
- ContractUtils.RequiresNotNull(type, "type");
- ContractUtils.Requires(variable == null || TypeUtils.AreEquivalent(variable.Type, type), "variable");
- if (variable != null && variable.IsByRef) {
- throw Error.VariableMustNotBeByRef(variable, variable.Type);
- }
- RequiresCanRead(body, "body");
- if (filter != null) {
- RequiresCanRead(filter, "filter");
- if (filter.Type != typeof(bool)) throw Error.ArgumentMustBeBoolean();
- }
-
- return new CatchBlock(type, variable, body, filter);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ConditionalExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ConditionalExpression.cs
deleted file mode 100644
index 32d108d08ae..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ConditionalExpression.cs
+++ /dev/null
@@ -1,226 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Dynamic.Utils;
-using System.Diagnostics;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- /// <summary>
- /// Represents an expression that has a conditional operator.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.ConditionalExpressionProxy))]
- public class ConditionalExpression : Expression {
- private readonly Expression _test;
- private readonly Expression _true;
-
- internal ConditionalExpression(Expression test, Expression ifTrue) {
- _test = test;
- _true = ifTrue;
- }
-
- internal static ConditionalExpression Make(Expression test, Expression ifTrue, Expression ifFalse, Type type) {
- if (ifTrue.Type != type || ifFalse.Type != type) {
- return new FullConditionalExpressionWithType(test, ifTrue, ifFalse, type);
- } if (ifFalse is DefaultExpression && ifFalse.Type == typeof(void)) {
- return new ConditionalExpression(test, ifTrue);
- } else {
- return new FullConditionalExpression(test, ifTrue, ifFalse);
- }
- }
-
- /// <summary>
- /// Returns the node type of this Expression. Extension nodes should return
- /// ExpressionType.Extension when overriding this method.
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Conditional; }
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents.
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public override Type Type {
- get { return IfTrue.Type; }
- }
-
- /// <summary>
- /// Gets the test of the conditional operation.
- /// </summary>
- public Expression Test {
- get { return _test; }
- }
- /// <summary>
- /// Gets the expression to execute if the test evaluates to true.
- /// </summary>
- public Expression IfTrue {
- get { return _true; }
- }
- /// <summary>
- /// Gets the expression to execute if the test evaluates to false.
- /// </summary>
- public Expression IfFalse {
- get { return GetFalse(); }
- }
-
- internal virtual Expression GetFalse() {
- return Expression.Empty();
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitConditional(this);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="test">The <see cref="Test" /> property of the result.</param>
- /// <param name="ifTrue">The <see cref="IfTrue" /> property of the result.</param>
- /// <param name="ifFalse">The <see cref="IfFalse" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public ConditionalExpression Update(Expression test, Expression ifTrue, Expression ifFalse) {
- if (test == Test && ifTrue == IfTrue && ifFalse == IfFalse) {
- return this;
- }
- return Expression.Condition(test, ifTrue, ifFalse, Type);
- }
- }
-
- internal class FullConditionalExpression : ConditionalExpression {
- private readonly Expression _false;
-
- internal FullConditionalExpression(Expression test, Expression ifTrue, Expression ifFalse)
- : base(test, ifTrue) {
- _false = ifFalse;
- }
-
- internal override Expression GetFalse() {
- return _false;
- }
- }
-
- internal class FullConditionalExpressionWithType : FullConditionalExpression {
- private readonly Type _type;
-
- internal FullConditionalExpressionWithType(Expression test, Expression ifTrue, Expression ifFalse, Type type)
- : base(test, ifTrue, ifFalse) {
- _type = type;
- }
-
- public sealed override Type Type {
- get { return _type; }
- }
- }
-
- public partial class Expression {
-
- /// <summary>
- /// Creates a <see cref="ConditionalExpression"/>.
- /// </summary>
- /// <param name="test">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.Test"/> property equal to.</param>
- /// <param name="ifTrue">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfTrue"/> property equal to.</param>
- /// <param name="ifFalse">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfFalse"/> property equal to.</param>
- /// <returns>A <see cref="ConditionalExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to
- /// <see cref="F:ExpressionType.Conditional"/> and the <see cref="P:ConditionalExpression.Test"/>, <see cref="P:ConditionalExpression.IfTrue"/>,
- /// and <see cref="P:ConditionalExpression.IfFalse"/> properties set to the specified values.</returns>
- public static ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse) {
- RequiresCanRead(test, "test");
- RequiresCanRead(ifTrue, "ifTrue");
- RequiresCanRead(ifFalse, "ifFalse");
-
- if (test.Type != typeof(bool)) {
- throw Error.ArgumentMustBeBoolean();
- }
- if (!TypeUtils.AreEquivalent(ifTrue.Type, ifFalse.Type)) {
- throw Error.ArgumentTypesMustMatch();
- }
-
- return ConditionalExpression.Make(test, ifTrue, ifFalse, ifTrue.Type);
- }
-
-
- /// <summary>
- /// Creates a <see cref="ConditionalExpression"/>.
- /// </summary>
- /// <param name="test">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.Test"/> property equal to.</param>
- /// <param name="ifTrue">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfTrue"/> property equal to.</param>
- /// <param name="ifFalse">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfFalse"/> property equal to.</param>
- /// <param name="type">A <see cref="Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
- /// <returns>A <see cref="ConditionalExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to
- /// <see cref="F:ExpressionType.Conditional"/> and the <see cref="P:ConditionalExpression.Test"/>, <see cref="P:ConditionalExpression.IfTrue"/>,
- /// and <see cref="P:ConditionalExpression.IfFalse"/> properties set to the specified values.</returns>
- /// <remarks>This method allows explicitly unifying the result type of the conditional expression in cases where the types of <paramref name="ifTrue"/>
- /// and <paramref name="ifFalse"/> expressions are not equal. Types of both <paramref name="ifTrue"/> and <paramref name="ifFalse"/> must be implicitly
- /// reference assignable to the result type. The <paramref name="type"/> is allowed to be <see cref="System.Void"/>.</remarks>
- public static ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse, Type type) {
- RequiresCanRead(test, "test");
- RequiresCanRead(ifTrue, "ifTrue");
- RequiresCanRead(ifFalse, "ifFalse");
- ContractUtils.RequiresNotNull(type, "type");
-
- if (test.Type != typeof(bool)) {
- throw Error.ArgumentMustBeBoolean();
- }
-
- if (type != typeof(void)) {
- if (!TypeUtils.AreReferenceAssignable(type, ifTrue.Type) ||
- !TypeUtils.AreReferenceAssignable(type, ifFalse.Type)) {
- throw Error.ArgumentTypesMustMatch();
- }
- }
-
- return ConditionalExpression.Make(test, ifTrue, ifFalse, type);
- }
-
- /// <summary>
- /// Creates a <see cref="ConditionalExpression"/>.
- /// </summary>
- /// <param name="test">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.Test"/> property equal to.</param>
- /// <param name="ifTrue">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfTrue"/> property equal to.</param>
- /// <returns>A <see cref="ConditionalExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to
- /// <see cref="F:ExpressionType.Conditional"/> and the <see cref="P:ConditionalExpression.Test"/>, <see cref="P:ConditionalExpression.IfTrue"/>,
- /// properties set to the specified values. The <see cref="P:ConditionalExpression.IfFalse"/> property is set to default expression and
- /// the type of the resulting <see cref="ConditionalExpression"/> returned by this method is <see cref="System.Void"/>.</returns>
- public static ConditionalExpression IfThen(Expression test, Expression ifTrue) {
- return Condition(test, ifTrue, Expression.Empty(), typeof(void));
- }
-
- /// <summary>
- /// Creates a <see cref="ConditionalExpression"/>.
- /// </summary>
- /// <param name="test">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.Test"/> property equal to.</param>
- /// <param name="ifTrue">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfTrue"/> property equal to.</param>
- /// <param name="ifFalse">An <see cref="Expression"/> to set the <see cref="P:ConditionalExpression.IfFalse"/> property equal to.</param>
- /// <returns>A <see cref="ConditionalExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to
- /// <see cref="F:ExpressionType.Conditional"/> and the <see cref="P:ConditionalExpression.Test"/>, <see cref="P:ConditionalExpression.IfTrue"/>,
- /// and <see cref="P:ConditionalExpression.IfFalse"/> properties set to the specified values. The type of the resulting <see cref="ConditionalExpression"/>
- /// returned by this method is <see cref="System.Void"/>.</returns>
- public static ConditionalExpression IfThenElse(Expression test, Expression ifTrue, Expression ifFalse) {
- return Condition(test, ifTrue, ifFalse, typeof(void));
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ConstantExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ConstantExpression.cs
deleted file mode 100644
index b4c3c7b3ceb..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ConstantExpression.cs
+++ /dev/null
@@ -1,136 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if SILVERLIGHT
-using System.Core;
-#endif
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- /// <summary>
- /// Represents an expression that has a constant value.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.ConstantExpressionProxy))]
- public class ConstantExpression : Expression {
- // Possible optimization: we could have a Constant<T> subclass that
- // stores the unboxed value.
- private readonly object _value;
-
- internal ConstantExpression(object value) {
- _value = value;
- }
-
- internal static ConstantExpression Make(object value, Type type) {
- if ((value == null && type == typeof(object)) || (value != null && value.GetType() == type)) {
- return new ConstantExpression(value);
- } else {
- return new TypedConstantExpression(value, type);
- }
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents.
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public override Type Type {
- get {
- if (_value == null) {
- return typeof(object);
- }
- return _value.GetType();
- }
- }
-
- /// <summary>
- /// Returns the node type of this Expression. Extension nodes should return
- /// ExpressionType.Extension when overriding this method.
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Constant; }
- }
- /// <summary>
- /// Gets the value of the constant expression.
- /// </summary>
- public object Value {
- get { return _value; }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitConstant(this);
- }
- }
-
- internal class TypedConstantExpression : ConstantExpression {
- private readonly Type _type;
-
- internal TypedConstantExpression(object value, Type type)
- : base(value) {
- _type = type;
- }
-
- public sealed override Type Type {
- get { return _type; }
- }
- }
-
- public partial class Expression {
- /// <summary>
- /// Creates a <see cref="ConstantExpression"/> that has the <see cref="P:ConstantExpression.Value"/> property set to the specified value. .
- /// </summary>
- /// <param name="value">An <see cref="System.Object"/> to set the <see cref="P:ConstantExpression.Value"/> property equal to.</param>
- /// <returns>
- /// A <see cref="ConstantExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to
- /// <see cref="F:ExpressionType.Constant"/> and the <see cref="P:Expression.Value"/> property set to the specified value.
- /// </returns>
- public static ConstantExpression Constant(object value) {
- return ConstantExpression.Make(value, value == null ? typeof(object) : value.GetType());
- }
-
-
- /// <summary>
- /// Creates a <see cref="ConstantExpression"/> that has the <see cref="P:ConstantExpression.Value"/>
- /// and <see cref="P:ConstantExpression.Type"/> properties set to the specified values. .
- /// </summary>
- /// <param name="value">An <see cref="System.Object"/> to set the <see cref="P:ConstantExpression.Value"/> property equal to.</param>
- /// <param name="type">A <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
- /// <returns>
- /// A <see cref="ConstantExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to
- /// <see cref="F:ExpressionType.Constant"/> and the <see cref="P:ConstantExpression.Value"/> and
- /// <see cref="P:Expression.Type"/> properties set to the specified values.
- /// </returns>
- public static ConstantExpression Constant(object value, Type type) {
- ContractUtils.RequiresNotNull(type, "type");
- if (value == null && type.IsValueType && !TypeUtils.IsNullableType(type)) {
- throw Error.ArgumentTypesMustMatch();
- }
- if (value != null && !type.IsAssignableFrom(value.GetType())) {
- throw Error.ArgumentTypesMustMatch();
- }
- return ConstantExpression.Make(value, type);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DebugInfoExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DebugInfoExpression.cs
deleted file mode 100644
index dd5121a5246..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DebugInfoExpression.cs
+++ /dev/null
@@ -1,243 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Emits or clears a sequence point for debug information.
- ///
- /// This allows the debugger to highlight the correct source code when
- /// debugging.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.DebugInfoExpressionProxy))]
- public class DebugInfoExpression : Expression {
-
- private readonly SymbolDocumentInfo _document;
-
- internal DebugInfoExpression(SymbolDocumentInfo document) {
- _document = document;
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return typeof(void); }
- }
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.DebugInfo; }
- }
-
- /// <summary>
- /// Gets the start line of this <see cref="DebugInfoExpression" />.
- /// </summary>
- public virtual int StartLine {
- get { throw ContractUtils.Unreachable; }
- }
-
- /// <summary>
- /// Gets the start column of this <see cref="DebugInfoExpression" />.
- /// </summary>
- public virtual int StartColumn {
- get { throw ContractUtils.Unreachable; }
- }
-
- /// <summary>
- /// Gets the end line of this <see cref="DebugInfoExpression" />.
- /// </summary>
- public virtual int EndLine {
- get { throw ContractUtils.Unreachable; }
- }
-
- /// <summary>
- /// Gets the end column of this <see cref="DebugInfoExpression" />.
- /// </summary>
- public virtual int EndColumn {
- get { throw ContractUtils.Unreachable; }
- }
-
- /// <summary>
- /// Gets the <see cref="SymbolDocumentInfo"/> that represents the source file.
- /// </summary>
- public SymbolDocumentInfo Document {
- get { return _document; }
- }
-
- /// <summary>
- /// Gets the value to indicate if the <see cref="DebugInfoExpression"/> is for clearing a sequence point.
- /// </summary>
- public virtual bool IsClear {
- get { throw ContractUtils.Unreachable; }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitDebugInfo(this);
- }
- }
-
- #region Specialized subclasses
-
- internal sealed class SpanDebugInfoExpression : DebugInfoExpression {
- private readonly int _startLine, _startColumn, _endLine, _endColumn;
-
- internal SpanDebugInfoExpression(SymbolDocumentInfo document, int startLine, int startColumn, int endLine, int endColumn)
- : base(document) {
- _startLine = startLine;
- _startColumn = startColumn;
- _endLine = endLine;
- _endColumn = endColumn;
- }
-
- public override int StartLine {
- get {
- return _startLine;
- }
- }
-
- public override int StartColumn {
- get {
- return _startColumn;
- }
- }
-
- public override int EndLine {
- get {
- return _endLine;
- }
- }
-
- public override int EndColumn {
- get {
- return _endColumn;
- }
- }
-
- public override bool IsClear {
- get {
- return false;
- }
- }
-
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitDebugInfo(this);
- }
- }
-
- internal sealed class ClearDebugInfoExpression : DebugInfoExpression {
- internal ClearDebugInfoExpression(SymbolDocumentInfo document)
- : base(document) {
- }
-
- public override bool IsClear {
- get {
- return true;
- }
- }
-
- public override int StartLine {
- get {
- return 0xfeefee;
- }
- }
-
- public override int StartColumn {
- get {
- return 0;
- }
- }
-
- public override int EndLine {
- get {
- return 0xfeefee;
- }
- }
-
- public override int EndColumn {
- get {
- return 0;
- }
- }
- }
- #endregion
-
- public partial class Expression {
- /// <summary>
- /// Creates a <see cref="DebugInfoExpression"/> with the specified span.
- /// </summary>
- /// <param name="document">The <see cref="SymbolDocumentInfo"/> that represents the source file.</param>
- /// <param name="startLine">The start line of this <see cref="DebugInfoExpression" />. Must be greater than 0.</param>
- /// <param name="startColumn">The start column of this <see cref="DebugInfoExpression" />. Must be greater than 0.</param>
- /// <param name="endLine">The end line of this <see cref="DebugInfoExpression" />. Must be greater or equal than the start line.</param>
- /// <param name="endColumn">The end column of this <see cref="DebugInfoExpression" />. If the end line is the same as the start line, it must be greater or equal than the start column. In any case, must be greater than 0.</param>
- /// <returns>An instance of <see cref="DebugInfoExpression"/>.</returns>
- public static DebugInfoExpression DebugInfo(SymbolDocumentInfo document, int startLine, int startColumn, int endLine, int endColumn) {
- ContractUtils.RequiresNotNull(document, "document");
- if (startLine == 0xfeefee && startColumn == 0 && endLine == 0xfeefee && endColumn == 0) {
- return new ClearDebugInfoExpression(document);
- }
-
- ValidateSpan(startLine, startColumn, endLine, endColumn);
- return new SpanDebugInfoExpression(document, startLine, startColumn, endLine, endColumn);
- }
-
- /// <summary>
- /// Creates a <see cref="DebugInfoExpression"/> for clearing a sequence point.
- /// </summary>
- /// <param name="document">The <see cref="SymbolDocumentInfo"/> that represents the source file.</param>
- /// <returns>An instance of <see cref="DebugInfoExpression"/> for clearning a sequence point.</returns>
- public static DebugInfoExpression ClearDebugInfo(SymbolDocumentInfo document) {
- ContractUtils.RequiresNotNull(document, "document");
-
- return new ClearDebugInfoExpression(document);
- }
-
- private static void ValidateSpan(int startLine, int startColumn, int endLine, int endColumn) {
- if (startLine < 1) {
- throw Error.OutOfRange("startLine", 1);
- }
- if (startColumn < 1) {
- throw Error.OutOfRange("startColumn", 1);
- }
- if (endLine < 1) {
- throw Error.OutOfRange("endLine", 1);
- }
- if (endColumn < 1) {
- throw Error.OutOfRange("endColumn", 1);
- }
- if (startLine > endLine) {
- throw Error.StartEndMustBeOrdered();
- }
- if (startLine == endLine && startColumn > endColumn) {
- throw Error.StartEndMustBeOrdered();
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DebugViewWriter.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DebugViewWriter.cs
deleted file mode 100644
index 098126a383b..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DebugViewWriter.cs
+++ /dev/null
@@ -1,1179 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Dynamic;
-using System.Dynamic.Utils;
-using System.Globalization;
-using System.IO;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Collections.ObjectModel;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
- internal sealed class DebugViewWriter : ExpressionVisitor {
- [Flags]
- private enum Flow {
- None,
- Space,
- NewLine,
-
- Break = 0x8000 // newline if column > MaxColumn
- };
-
- private const int Tab = 4;
- private const int MaxColumn = 120;
-
- private TextWriter _out;
- private int _column;
-
- private Stack<int> _stack = new Stack<int>();
- private int _delta;
- private Flow _flow;
-
- // All the unique lambda expressions in the ET, will be used for displaying all
- // the lambda definitions.
- private Queue<LambdaExpression> _lambdas;
-
- // Associate every unique anonymous LambdaExpression in the tree with an integer.
- // The id is used to create a name for the anonymous lambda.
- //
- private Dictionary<LambdaExpression, int> _lambdaIds;
-
- // Associate every unique anonymous parameter or variable in the tree with an integer.
- // The id is used to create a name for the anonymous parameter or variable.
- //
- private Dictionary<ParameterExpression, int> _paramIds;
-
- // Associate every unique anonymous LabelTarget in the tree with an integer.
- // The id is used to create a name for the anonymous LabelTarget.
- //
- private Dictionary<LabelTarget, int> _labelIds;
-
- private DebugViewWriter(TextWriter file) {
- _out = file;
- }
-
- private int Base {
- get {
- return _stack.Count > 0 ? _stack.Peek() : 0;
- }
- }
-
- private int Delta {
- get { return _delta; }
- }
-
- private int Depth {
- get { return Base + Delta; }
- }
-
- private void Indent() {
- _delta += Tab;
- }
- private void Dedent() {
- _delta -= Tab;
- }
-
- private void NewLine() {
- _flow = Flow.NewLine;
- }
-
- private static int GetId<T>(T e, ref Dictionary<T, int> ids) {
- if (ids == null) {
- ids = new Dictionary<T, int>();
- ids.Add(e, 1);
- return 1;
- } else {
- int id;
- if (!ids.TryGetValue(e, out id)) {
- // e is met the first time
- id = ids.Count + 1;
- ids.Add(e, id);
- }
- return id;
- }
- }
-
- private int GetLambdaId(LambdaExpression le) {
- Debug.Assert(String.IsNullOrEmpty(le.Name));
- return GetId(le, ref _lambdaIds);
- }
-
- private int GetParamId(ParameterExpression p) {
- Debug.Assert(String.IsNullOrEmpty(p.Name));
- return GetId(p, ref _paramIds);
- }
-
- private int GetLabelTargetId(LabelTarget target) {
- Debug.Assert(String.IsNullOrEmpty(target.Name));
- return GetId(target, ref _labelIds);
- }
-
- /// <summary>
- /// Write out the given AST
- /// </summary>
- internal static void WriteTo(Expression node, TextWriter writer) {
- Debug.Assert(node != null);
- Debug.Assert(writer != null);
-
- new DebugViewWriter(writer).WriteTo(node);
- }
-
- private void WriteTo(Expression node) {
- var lambda = node as LambdaExpression;
- if (lambda != null) {
- WriteLambda(lambda);
- } else {
- Visit(node);
- Debug.Assert(_stack.Count == 0);
- }
-
- //
- // Output all lambda expression definitions.
- // in the order of their appearances in the tree.
- //
- while (_lambdas != null && _lambdas.Count > 0) {
- WriteLine();
- WriteLine();
- WriteLambda(_lambdas.Dequeue());
- }
- }
-
- #region The printing code
-
- private void Out(string s) {
- Out(Flow.None, s, Flow.None);
- }
-
- private void Out(Flow before, string s) {
- Out(before, s, Flow.None);
- }
-
- private void Out(string s, Flow after) {
- Out(Flow.None, s, after);
- }
-
- private void Out(Flow before, string s, Flow after) {
- switch (GetFlow(before)) {
- case Flow.None:
- break;
- case Flow.Space:
- Write(" ");
- break;
- case Flow.NewLine:
- WriteLine();
- Write(new String(' ', Depth));
- break;
- }
- Write(s);
- _flow = after;
- }
-
- private void WriteLine() {
- _out.WriteLine();
- _column = 0;
- }
- private void Write(string s) {
- _out.Write(s);
- _column += s.Length;
- }
-
- private Flow GetFlow(Flow flow) {
- Flow last;
-
- last = CheckBreak(_flow);
- flow = CheckBreak(flow);
-
- // Get the biggest flow that is requested None < Space < NewLine
- return (Flow)System.Math.Max((int)last, (int)flow);
- }
-
- private Flow CheckBreak(Flow flow) {
- if ((flow & Flow.Break) != 0) {
- if (_column > (MaxColumn + Depth)) {
- flow = Flow.NewLine;
- } else {
- flow &= ~Flow.Break;
- }
- }
- return flow;
- }
-
- #endregion
-
- #region The AST Output
-
- // More proper would be to make this a virtual method on Action
- private static string FormatBinder(CallSiteBinder binder) {
- ConvertBinder convert;
- GetMemberBinder getMember;
- SetMemberBinder setMember;
- DeleteMemberBinder deleteMember;
- InvokeMemberBinder call;
- UnaryOperationBinder unary;
- BinaryOperationBinder binary;
-
- if ((convert = binder as ConvertBinder) != null) {
- return "Convert " + convert.Type.ToString();
- } else if ((getMember = binder as GetMemberBinder) != null) {
- return "GetMember " + getMember.Name;
- } else if ((setMember = binder as SetMemberBinder) != null) {
- return "SetMember " + setMember.Name;
- } else if ((deleteMember = binder as DeleteMemberBinder) != null) {
- return "DeleteMember " + deleteMember.Name;
- } else if (binder is GetIndexBinder) {
- return "GetIndex";
- } else if (binder is SetIndexBinder) {
- return "SetIndex";
- } else if (binder is DeleteIndexBinder) {
- return "DeleteIndex";
- } else if ((call = binder as InvokeMemberBinder) != null) {
- return "Call " + call.Name;
- } else if (binder is InvokeBinder) {
- return "Invoke";
- } else if (binder is CreateInstanceBinder) {
- return "Create";
- } else if ((unary = binder as UnaryOperationBinder) != null) {
- return "UnaryOperation " + unary.Operation;
- } else if ((binary = binder as BinaryOperationBinder) != null) {
- return "BinaryOperation " + binary.Operation;
- } else {
- return binder.ToString();
- }
- }
-
- private void VisitExpressions<T>(char open, IList<T> expressions) where T : Expression {
- VisitExpressions<T>(open, ',', expressions);
- }
-
- private void VisitExpressions<T>(char open, char separator, IList<T> expressions) where T : Expression {
- VisitExpressions(open, separator, expressions, e => Visit(e));
- }
-
- private void VisitDeclarations(IList<ParameterExpression> expressions) {
- VisitExpressions('(', ',', expressions, variable =>
- {
- Out(variable.Type.ToString());
- if (variable.IsByRef) {
- Out("&");
- }
- Out(" ");
- VisitParameter(variable);
- });
- }
-
- private void VisitExpressions<T>(char open, char separator, IList<T> expressions, Action<T> visit) {
- Out(open.ToString());
-
- if (expressions != null) {
- Indent();
- bool isFirst = true;
- foreach (T e in expressions) {
- if (isFirst) {
- if (open == '{' || expressions.Count > 1) {
- NewLine();
- }
- isFirst = false;
- } else {
- Out(separator.ToString(), Flow.NewLine);
- }
- visit(e);
- }
- Dedent();
- }
-
- char close;
- switch (open) {
- case '(': close = ')'; break;
- case '{': close = '}'; break;
- case '[': close = ']'; break;
- case '<': close = '>'; break;
- default: throw ContractUtils.Unreachable;
- }
-
- if (open == '{') {
- NewLine();
- }
- Out(close.ToString(), Flow.Break);
- }
-
- protected internal override Expression VisitDynamic(DynamicExpression node) {
- Out(".Dynamic", Flow.Space);
- Out(FormatBinder(node.Binder));
- VisitExpressions('(', node.Arguments);
- return node;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- protected internal override Expression VisitBinary(BinaryExpression node) {
- if (node.NodeType == ExpressionType.ArrayIndex) {
- ParenthesizedVisit(node, node.Left);
- Out("[");
- Visit(node.Right);
- Out("]");
- } else {
- bool parenthesizeLeft = NeedsParentheses(node, node.Left);
- bool parenthesizeRight = NeedsParentheses(node, node.Right);
-
- string op;
- bool isChecked = false;
- Flow beforeOp = Flow.Space;
- switch (node.NodeType) {
- case ExpressionType.Assign: op = "="; break;
- case ExpressionType.Equal: op = "=="; break;
- case ExpressionType.NotEqual: op = "!="; break;
- case ExpressionType.AndAlso: op = "&&"; beforeOp = Flow.Break | Flow.Space; break;
- case ExpressionType.OrElse: op = "||"; beforeOp = Flow.Break | Flow.Space; break;
- case ExpressionType.GreaterThan: op = ">"; break;
- case ExpressionType.LessThan: op = "<"; break;
- case ExpressionType.GreaterThanOrEqual: op = ">="; break;
- case ExpressionType.LessThanOrEqual: op = "<="; break;
- case ExpressionType.Add: op = "+"; break;
- case ExpressionType.AddAssign: op = "+="; break;
- case ExpressionType.AddAssignChecked: op = "+="; isChecked = true; break;
- case ExpressionType.AddChecked: op = "+"; isChecked = true; break;
- case ExpressionType.Subtract: op = "-"; break;
- case ExpressionType.SubtractAssign: op = "-="; break;
- case ExpressionType.SubtractAssignChecked: op = "-="; isChecked = true; break;
- case ExpressionType.SubtractChecked: op = "-"; isChecked = true; break;
- case ExpressionType.Divide: op = "/"; break;
- case ExpressionType.DivideAssign: op = "/="; break;
- case ExpressionType.Modulo: op = "%"; break;
- case ExpressionType.ModuloAssign: op = "%="; break;
- case ExpressionType.Multiply: op = "*"; break;
- case ExpressionType.MultiplyAssign: op = "*="; break;
- case ExpressionType.MultiplyAssignChecked: op = "*="; isChecked = true; break;
- case ExpressionType.MultiplyChecked: op = "*"; isChecked = true; break;
- case ExpressionType.LeftShift: op = "<<"; break;
- case ExpressionType.LeftShiftAssign: op = "<<="; break;
- case ExpressionType.RightShift: op = ">>"; break;
- case ExpressionType.RightShiftAssign: op = ">>="; break;
- case ExpressionType.And: op = "&"; break;
- case ExpressionType.AndAssign: op = "&="; break;
- case ExpressionType.Or: op = "|"; break;
- case ExpressionType.OrAssign: op = "|="; break;
- case ExpressionType.ExclusiveOr: op = "^"; break;
- case ExpressionType.ExclusiveOrAssign: op = "^="; break;
- case ExpressionType.Power: op = "**"; break;
- case ExpressionType.PowerAssign: op = "**="; break;
- case ExpressionType.Coalesce: op = "??"; break;
-
- default:
- throw new InvalidOperationException();
- }
-
- if (parenthesizeLeft) {
- Out("(", Flow.None);
- }
-
- Visit(node.Left);
- if (parenthesizeLeft) {
- Out(Flow.None, ")", Flow.Break);
- }
-
- // prepend # to the operator to represent checked op
- if (isChecked) {
- op = String.Format(
- CultureInfo.CurrentCulture,
- "#{0}",
- op
- );
- }
- Out(beforeOp, op, Flow.Space | Flow.Break);
-
- if (parenthesizeRight) {
- Out("(", Flow.None);
- }
- Visit(node.Right);
- if (parenthesizeRight) {
- Out(Flow.None, ")", Flow.Break);
- }
- }
- return node;
- }
-
- protected internal override Expression VisitParameter(ParameterExpression node) {
- // Have '$' for the DebugView of ParameterExpressions
- Out("$");
- if (String.IsNullOrEmpty(node.Name)) {
- // If no name if provided, generate a name as $var1, $var2.
- // No guarantee for not having name conflicts with user provided variable names.
- //
- int id = GetParamId(node);
- Out("var" + id);
- } else {
- Out(GetDisplayName(node.Name));
- }
- return node;
- }
-
- protected internal override Expression VisitLambda<T>(Expression<T> node) {
- Out(
- String.Format(CultureInfo.CurrentCulture,
- "{0} {1}<{2}>",
- ".Lambda",
- GetLambdaName(node),
- node.Type.ToString()
- )
- );
-
- if (_lambdas == null) {
- _lambdas = new Queue<LambdaExpression>();
- }
-
- // N^2 performance, for keeping the order of the lambdas.
- if (!_lambdas.Contains(node)) {
- _lambdas.Enqueue(node);
- }
-
- return node;
- }
-
- private static bool IsSimpleExpression(Expression node) {
- var binary = node as BinaryExpression;
- if (binary != null) {
- return !(binary.Left is BinaryExpression || binary.Right is BinaryExpression);
- }
-
- return false;
- }
-
- protected internal override Expression VisitConditional(ConditionalExpression node) {
- if (IsSimpleExpression(node.Test)) {
- Out(".If (");
- Visit(node.Test);
- Out(") {", Flow.NewLine);
- } else {
- Out(".If (", Flow.NewLine);
- Indent();
- Visit(node.Test);
- Dedent();
- Out(Flow.NewLine, ") {", Flow.NewLine);
- }
- Indent();
- Visit(node.IfTrue);
- Dedent();
- Out(Flow.NewLine, "} .Else {", Flow.NewLine);
- Indent();
- Visit(node.IfFalse);
- Dedent();
- Out(Flow.NewLine, "}");
- return node;
- }
-
- protected internal override Expression VisitConstant(ConstantExpression node) {
- object value = node.Value;
-
- if (value == null) {
- Out("null");
- } else if ((value is string) && node.Type == typeof(string)) {
- Out(String.Format(
- CultureInfo.CurrentCulture,
- "\"{0}\"",
- value));
- } else if ((value is char) && node.Type == typeof(char)) {
- Out(String.Format(
- CultureInfo.CurrentCulture,
- "'{0}'",
- value));
- } else if ((value is int) && node.Type == typeof(int)
- || (value is bool) && node.Type == typeof(bool)) {
- Out(value.ToString());
- } else {
- string suffix = GetConstantValueSuffix(node.Type);
- if (suffix != null) {
- Out(value.ToString());
- Out(suffix);
- } else {
- Out(String.Format(
- CultureInfo.CurrentCulture,
- ".Constant<{0}>({1})",
- node.Type.ToString(),
- value));
- }
- }
- return node;
- }
-
- private static string GetConstantValueSuffix(Type type) {
- if (type == typeof(UInt32)) {
- return "U";
- }
- if (type == typeof(Int64)) {
- return "L";
- }
- if (type == typeof(UInt64)) {
- return "UL";
- }
- if (type == typeof(Double)) {
- return "D";
- }
- if (type == typeof(Single)) {
- return "F";
- }
- if (type == typeof(Decimal)) {
- return "M";
- }
- return null;
- }
-
- protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) {
- Out(".RuntimeVariables");
- VisitExpressions('(', node.Variables);
- return node;
- }
-
- // Prints ".instanceField" or "declaringType.staticField"
- private void OutMember(Expression node, Expression instance, MemberInfo member) {
- if (instance != null) {
- ParenthesizedVisit(node, instance);
- Out("." + member.Name);
- } else {
- // For static members, include the type name
- Out(member.DeclaringType.ToString() + "." + member.Name);
- }
- }
-
- protected internal override Expression VisitMember(MemberExpression node) {
- OutMember(node, node.Expression, node.Member);
- return node;
- }
-
- protected internal override Expression VisitInvocation(InvocationExpression node) {
- Out(".Invoke ");
- ParenthesizedVisit(node, node.Expression);
- VisitExpressions('(', node.Arguments);
- return node;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- private static bool NeedsParentheses(Expression parent, Expression child) {
- Debug.Assert(parent != null);
- if (child == null) {
- return false;
- }
-
- // Some nodes always have parentheses because of how they are
- // displayed, for example: ".Unbox(obj.Foo)"
- switch (parent.NodeType) {
- case ExpressionType.Increment:
- case ExpressionType.Decrement:
- case ExpressionType.IsTrue:
- case ExpressionType.IsFalse:
- case ExpressionType.Unbox:
- return true;
- }
-
- int childOpPrec = GetOperatorPrecedence(child);
- int parentOpPrec = GetOperatorPrecedence(parent);
-
- if (childOpPrec == parentOpPrec) {
- // When parent op and child op has the same precedence,
- // we want to be a little conservative to have more clarity.
- // Parentheses are not needed if
- // 1) Both ops are &&, ||, &, |, or ^, all of them are the only
- // op that has the precedence.
- // 2) Parent op is + or *, e.g. x + (y - z) can be simplified to
- // x + y - z.
- // 3) Parent op is -, / or %, and the child is the left operand.
- // In this case, if left and right operand are the same, we don't
- // remove parenthesis, e.g. (x + y) - (x + y)
- //
- switch (parent.NodeType) {
- case ExpressionType.AndAlso:
- case ExpressionType.OrElse:
- case ExpressionType.And:
- case ExpressionType.Or:
- case ExpressionType.ExclusiveOr:
- // Since these ops are the only ones on their precedence,
- // the child op must be the same.
- Debug.Assert(child.NodeType == parent.NodeType);
- // We remove the parenthesis, e.g. x && y && z
- return false;
- case ExpressionType.Add:
- case ExpressionType.AddChecked:
- case ExpressionType.Multiply:
- case ExpressionType.MultiplyChecked:
- return false;
- case ExpressionType.Subtract:
- case ExpressionType.SubtractChecked:
- case ExpressionType.Divide:
- case ExpressionType.Modulo:
- BinaryExpression binary = parent as BinaryExpression;
- Debug.Assert(binary != null);
- // Need to have parenthesis for the right operand.
- return child == binary.Right;
- }
- return true;
- }
-
- // Special case: negate of a constant needs parentheses, to
- // disambiguate it from a negative constant.
- if (child != null && child.NodeType == ExpressionType.Constant &&
- (parent.NodeType == ExpressionType.Negate || parent.NodeType == ExpressionType.NegateChecked)) {
- return true;
- }
-
- // If the parent op has higher precedence, need parentheses for the child.
- return childOpPrec < parentOpPrec;
- }
-
- // the greater the higher
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- private static int GetOperatorPrecedence(Expression node) {
-
- // Roughly matches C# operator precedence, with some additional
- // operators. Also things which are not binary/unary expressions,
- // such as conditional and type testing, don't use this mechanism.
- switch (node.NodeType) {
- // Assignment
- case ExpressionType.Assign:
- case ExpressionType.ExclusiveOrAssign:
- case ExpressionType.AddAssign:
- case ExpressionType.AddAssignChecked:
- case ExpressionType.SubtractAssign:
- case ExpressionType.SubtractAssignChecked:
- case ExpressionType.DivideAssign:
- case ExpressionType.ModuloAssign:
- case ExpressionType.MultiplyAssign:
- case ExpressionType.MultiplyAssignChecked:
- case ExpressionType.LeftShiftAssign:
- case ExpressionType.RightShiftAssign:
- case ExpressionType.AndAssign:
- case ExpressionType.OrAssign:
- case ExpressionType.PowerAssign:
- case ExpressionType.Coalesce:
- return 1;
-
- // Conditional (?:) would go here
-
- // Conditional OR
- case ExpressionType.OrElse:
- return 2;
-
- // Conditional AND
- case ExpressionType.AndAlso:
- return 3;
-
- // Logical OR
- case ExpressionType.Or:
- return 4;
-
- // Logical XOR
- case ExpressionType.ExclusiveOr:
- return 5;
-
- // Logical AND
- case ExpressionType.And:
- return 6;
-
- // Equality
- case ExpressionType.Equal:
- case ExpressionType.NotEqual:
- return 7;
-
- // Relational, type testing
- case ExpressionType.GreaterThan:
- case ExpressionType.LessThan:
- case ExpressionType.GreaterThanOrEqual:
- case ExpressionType.LessThanOrEqual:
- case ExpressionType.TypeAs:
- case ExpressionType.TypeIs:
- case ExpressionType.TypeEqual:
- return 8;
-
- // Shift
- case ExpressionType.LeftShift:
- case ExpressionType.RightShift:
- return 9;
-
- // Additive
- case ExpressionType.Add:
- case ExpressionType.AddChecked:
- case ExpressionType.Subtract:
- case ExpressionType.SubtractChecked:
- return 10;
-
- // Multiplicative
- case ExpressionType.Divide:
- case ExpressionType.Modulo:
- case ExpressionType.Multiply:
- case ExpressionType.MultiplyChecked:
- return 11;
-
- // Unary
- case ExpressionType.Negate:
- case ExpressionType.NegateChecked:
- case ExpressionType.UnaryPlus:
- case ExpressionType.Not:
- case ExpressionType.Convert:
- case ExpressionType.ConvertChecked:
- case ExpressionType.PreIncrementAssign:
- case ExpressionType.PreDecrementAssign:
- case ExpressionType.OnesComplement:
- case ExpressionType.Increment:
- case ExpressionType.Decrement:
- case ExpressionType.IsTrue:
- case ExpressionType.IsFalse:
- case ExpressionType.Unbox:
- case ExpressionType.Throw:
- return 12;
-
- // Power, which is not in C#
- // But VB/Python/Ruby put it here, above unary.
- case ExpressionType.Power:
- return 13;
-
- // Primary, which includes all other node types:
- // member access, calls, indexing, new.
- case ExpressionType.PostIncrementAssign:
- case ExpressionType.PostDecrementAssign:
- default:
- return 14;
-
- // These aren't expressions, so never need parentheses:
- // constants, variables
- case ExpressionType.Constant:
- case ExpressionType.Parameter:
- return 15;
- }
- }
-
- private void ParenthesizedVisit(Expression parent, Expression nodeToVisit) {
- if (NeedsParentheses(parent, nodeToVisit)) {
- Out("(");
- Visit(nodeToVisit);
- Out(")");
- } else {
- Visit(nodeToVisit);
- }
- }
-
- protected internal override Expression VisitMethodCall(MethodCallExpression node) {
- Out(".Call ");
- if (node.Object != null) {
- ParenthesizedVisit(node, node.Object);
- } else if (node.Method.DeclaringType != null) {
- Out(node.Method.DeclaringType.ToString());
- } else {
- Out("<UnknownType>");
- }
- Out(".");
- Out(node.Method.Name);
- VisitExpressions('(', node.Arguments);
- return node;
- }
-
- protected internal override Expression VisitNewArray(NewArrayExpression node) {
- if (node.NodeType == ExpressionType.NewArrayBounds) {
- // .NewArray MyType[expr1, expr2]
- Out(".NewArray " + node.Type.GetElementType().ToString());
- VisitExpressions('[', node.Expressions);
- } else {
- // .NewArray MyType {expr1, expr2}
- Out(".NewArray " + node.Type.ToString(), Flow.Space);
- VisitExpressions('{', node.Expressions);
- }
- return node;
- }
-
- protected internal override Expression VisitNew(NewExpression node) {
- Out(".New " + node.Type.ToString());
- VisitExpressions('(', node.Arguments);
- return node;
- }
-
- protected override ElementInit VisitElementInit(ElementInit node) {
- if (node.Arguments.Count == 1) {
- Visit(node.Arguments[0]);
- } else {
- VisitExpressions('{', node.Arguments);
- }
- return node;
- }
-
- protected internal override Expression VisitListInit(ListInitExpression node) {
- Visit(node.NewExpression);
- VisitExpressions('{', ',', node.Initializers, e => VisitElementInit(e));
- return node;
- }
-
- protected override MemberAssignment VisitMemberAssignment(MemberAssignment assignment) {
- Out(assignment.Member.Name);
- Out(Flow.Space, "=", Flow.Space);
- Visit(assignment.Expression);
- return assignment;
- }
-
- protected override MemberListBinding VisitMemberListBinding(MemberListBinding binding) {
- Out(binding.Member.Name);
- Out(Flow.Space, "=", Flow.Space);
- VisitExpressions('{', ',', binding.Initializers, e => VisitElementInit(e));
- return binding;
- }
-
- protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) {
- Out(binding.Member.Name);
- Out(Flow.Space, "=", Flow.Space);
- VisitExpressions('{', ',', binding.Bindings, e => VisitMemberBinding(e));
- return binding;
- }
-
- protected internal override Expression VisitMemberInit(MemberInitExpression node) {
- Visit(node.NewExpression);
- VisitExpressions('{', ',', node.Bindings, e => VisitMemberBinding(e));
- return node;
- }
-
- protected internal override Expression VisitTypeBinary(TypeBinaryExpression node) {
- ParenthesizedVisit(node, node.Expression);
- switch (node.NodeType) {
- case ExpressionType.TypeIs:
- Out(Flow.Space, ".Is", Flow.Space);
- break;
- case ExpressionType.TypeEqual:
- Out(Flow.Space, ".TypeEqual", Flow.Space);
- break;
- }
- Out(node.TypeOperand.ToString());
- return node;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- protected internal override Expression VisitUnary(UnaryExpression node) {
- switch (node.NodeType) {
- case ExpressionType.Convert:
- Out("(" + node.Type.ToString() + ")");
- break;
- case ExpressionType.ConvertChecked:
- Out("#(" + node.Type.ToString() + ")");
- break;
- case ExpressionType.TypeAs:
- break;
- case ExpressionType.Not:
- Out(node.Type == typeof(bool) ? "!" : "~");
- break;
- case ExpressionType.OnesComplement:
- Out("~");
- break;
- case ExpressionType.Negate:
- Out("-");
- break;
- case ExpressionType.NegateChecked:
- Out("#-");
- break;
- case ExpressionType.UnaryPlus:
- Out("+");
- break;
- case ExpressionType.ArrayLength:
- break;
- case ExpressionType.Quote:
- Out("'");
- break;
- case ExpressionType.Throw:
- if (node.Operand == null) {
- Out(".Rethrow");
- } else {
- Out(".Throw", Flow.Space);
- }
- break;
- case ExpressionType.IsFalse:
- Out(".IsFalse");
- break;
- case ExpressionType.IsTrue:
- Out(".IsTrue");
- break;
- case ExpressionType.Decrement:
- Out(".Decrement");
- break;
- case ExpressionType.Increment:
- Out(".Increment");
- break;
- case ExpressionType.PreDecrementAssign:
- Out("--");
- break;
- case ExpressionType.PreIncrementAssign:
- Out("++");
- break;
- case ExpressionType.Unbox:
- Out(".Unbox");
- break;
- }
-
- ParenthesizedVisit(node, node.Operand);
-
- switch (node.NodeType) {
- case ExpressionType.TypeAs:
- Out(Flow.Space, ".As", Flow.Space | Flow.Break);
- Out(node.Type.ToString());
- break;
-
- case ExpressionType.ArrayLength:
- Out(".Length");
- break;
-
- case ExpressionType.PostDecrementAssign:
- Out("--");
- break;
-
- case ExpressionType.PostIncrementAssign:
- Out("++");
- break;
- }
- return node;
- }
-
- protected internal override Expression VisitBlock(BlockExpression node) {
- Out(".Block");
-
- // Display <type> if the type of the BlockExpression is different from the
- // last expression's type in the block.
- if (node.Type != node.GetExpression(node.ExpressionCount - 1).Type) {
- Out(String.Format(CultureInfo.CurrentCulture, "<{0}>", node.Type.ToString()));
- }
-
- VisitDeclarations(node.Variables);
- Out(" ");
- // Use ; to separate expressions in the block
- VisitExpressions('{', ';', node.Expressions);
-
- return node;
- }
-
- protected internal override Expression VisitDefault(DefaultExpression node) {
- Out(".Default(" + node.Type.ToString() + ")");
- return node;
- }
-
- protected internal override Expression VisitLabel(LabelExpression node) {
- Out(".Label", Flow.NewLine);
- Indent();
- Visit(node.DefaultValue);
- Dedent();
- NewLine();
- DumpLabel(node.Target);
- return node;
- }
-
- protected internal override Expression VisitGoto(GotoExpression node) {
- Out("." + node.Kind.ToString(), Flow.Space);
- Out(GetLabelTargetName(node.Target), Flow.Space);
- Out("{", Flow.Space);
- Visit(node.Value);
- Out(Flow.Space, "}");
- return node;
- }
-
- protected internal override Expression VisitLoop(LoopExpression node) {
- Out(".Loop", Flow.Space);
- if (node.ContinueLabel != null) {
- DumpLabel(node.ContinueLabel);
- }
- Out(" {", Flow.NewLine);
- Indent();
- Visit(node.Body);
- Dedent();
- Out(Flow.NewLine, "}");
- if (node.BreakLabel != null) {
- Out("", Flow.NewLine);
- DumpLabel(node.BreakLabel);
- }
- return node;
- }
-
- protected override SwitchCase VisitSwitchCase(SwitchCase node) {
- foreach (var test in node.TestValues) {
- Out(".Case (");
- Visit(test);
- Out("):", Flow.NewLine);
- }
- Indent(); Indent();
- Visit(node.Body);
- Dedent(); Dedent();
- NewLine();
- return node;
- }
-
- protected internal override Expression VisitSwitch(SwitchExpression node) {
- Out(".Switch ");
- Out("(");
- Visit(node.SwitchValue);
- Out(") {", Flow.NewLine);
- Visit(node.Cases, VisitSwitchCase);
- if (node.DefaultBody != null) {
- Out(".Default:", Flow.NewLine);
- Indent(); Indent();
- Visit(node.DefaultBody);
- Dedent(); Dedent();
- NewLine();
- }
- Out("}");
- return node;
- }
-
- protected override CatchBlock VisitCatchBlock(CatchBlock node) {
- Out(Flow.NewLine, "} .Catch (" + node.Test.ToString());
- if (node.Variable != null) {
- Out(Flow.Space, "");
- VisitParameter(node.Variable);
- }
- if (node.Filter != null) {
- Out(") .If (", Flow.Break);
- Visit(node.Filter);
- }
- Out(") {", Flow.NewLine);
- Indent();
- Visit(node.Body);
- Dedent();
- return node;
- }
-
- protected internal override Expression VisitTry(TryExpression node) {
- Out(".Try {", Flow.NewLine);
- Indent();
- Visit(node.Body);
- Dedent();
- Visit(node.Handlers, VisitCatchBlock);
- if (node.Finally != null) {
- Out(Flow.NewLine, "} .Finally {", Flow.NewLine);
- Indent();
- Visit(node.Finally);
- Dedent();
- } else if (node.Fault != null) {
- Out(Flow.NewLine, "} .Fault {", Flow.NewLine);
- Indent();
- Visit(node.Fault);
- Dedent();
- }
-
- Out(Flow.NewLine, "}");
- return node;
- }
-
- protected internal override Expression VisitIndex(IndexExpression node) {
- if (node.Indexer != null) {
- OutMember(node, node.Object, node.Indexer);
- } else {
- ParenthesizedVisit(node, node.Object);
- }
-
- VisitExpressions('[', node.Arguments);
- return node;
- }
-
- protected internal override Expression VisitExtension(Expression node) {
- Out(String.Format(CultureInfo.CurrentCulture, ".Extension<{0}>", node.GetType().ToString()));
-
- if (node.CanReduce) {
- Out(Flow.Space, "{", Flow.NewLine);
- Indent();
- Visit(node.Reduce());
- Dedent();
- Out(Flow.NewLine, "}");
- }
-
- return node;
- }
-
- protected internal override Expression VisitDebugInfo(DebugInfoExpression node) {
- Out(String.Format(
- CultureInfo.CurrentCulture,
- ".DebugInfo({0}: {1}, {2} - {3}, {4})",
- node.Document.FileName,
- node.StartLine,
- node.StartColumn,
- node.EndLine,
- node.EndColumn)
- );
- return node;
- }
-
-
- private void DumpLabel(LabelTarget target) {
- Out(String.Format(CultureInfo.CurrentCulture, ".LabelTarget {0}:", GetLabelTargetName(target)));
- }
-
- private string GetLabelTargetName(LabelTarget target) {
- if (string.IsNullOrEmpty(target.Name)) {
- // Create the label target name as #Label1, #Label2, etc.
- return String.Format(CultureInfo.CurrentCulture, "#Label{0}", GetLabelTargetId(target));
- } else {
- return GetDisplayName(target.Name);
- }
- }
-
- private void WriteLambda(LambdaExpression lambda) {
- Out(
- String.Format(
- CultureInfo.CurrentCulture,
- ".Lambda {0}<{1}>",
- GetLambdaName(lambda),
- lambda.Type.ToString())
- );
-
- VisitDeclarations(lambda.Parameters);
-
- Out(Flow.Space, "{", Flow.NewLine);
- Indent();
- Visit(lambda.Body);
- Dedent();
- Out(Flow.NewLine, "}");
- Debug.Assert(_stack.Count == 0);
- }
-
- private string GetLambdaName(LambdaExpression lambda) {
- if (String.IsNullOrEmpty(lambda.Name)) {
- return "#Lambda" + GetLambdaId(lambda);
- }
- return GetDisplayName(lambda.Name);
- }
-
- /// <summary>
- /// Return true if the input string contains any whitespace character.
- /// Otherwise false.
- /// </summary>
- private static bool ContainsWhiteSpace(string name) {
- foreach (char c in name) {
- if (Char.IsWhiteSpace(c)) {
- return true;
- }
- }
- return false;
- }
-
- private static string QuoteName(string name) {
- return String.Format(CultureInfo.CurrentCulture, "'{0}'", name);
- }
-
- private static string GetDisplayName(string name) {
- if (ContainsWhiteSpace(name)) {
- // if name has whitespaces in it, quote it
- return QuoteName(name);
- } else {
- return name;
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DefaultExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DefaultExpression.cs
deleted file mode 100644
index 5234bf84465..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DefaultExpression.cs
+++ /dev/null
@@ -1,87 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents the default value of a type or an empty expression.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.DefaultExpressionProxy))]
- public sealed class DefaultExpression : Expression {
- private readonly Type _type;
-
- internal DefaultExpression(Type type) {
- _type = type;
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents.
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return _type; }
- }
-
- /// <summary>
- /// Returns the node type of this Expression. Extension nodes should return
- /// ExpressionType.Extension when overriding this method.
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Default; }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitDefault(this);
- }
- }
-
- public partial class Expression {
- /// <summary>
- /// Creates an empty expression that has <see cref="System.Void"/> type.
- /// </summary>
- /// <returns>
- /// A <see cref="DefaultExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to
- /// <see cref="F:ExpressionType.Default"/> and the <see cref="P:Expression.Type"/> property set to <see cref="System.Void"/>.
- /// </returns>
- public static DefaultExpression Empty() {
- return new DefaultExpression(typeof(void));
- }
-
- /// <summary>
- /// Creates a <see cref="DefaultExpression"/> that has the <see cref="P:Expression.Type"/> property set to the specified type.
- /// </summary>
- /// <param name="type">A <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
- /// <returns>
- /// A <see cref="DefaultExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to
- /// <see cref="F:ExpressionType.Default"/> and the <see cref="P:Expression.Type"/> property set to the specified type.
- /// </returns>
- public static DefaultExpression Default(Type type) {
- if (type == typeof(void)) {
- return Empty();
- }
- return new DefaultExpression(type);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DynamicExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DynamicExpression.cs
deleted file mode 100644
index 14a8d8e5593..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/DynamicExpression.cs
+++ /dev/null
@@ -1,848 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- using Compiler;
-
- /// <summary>
- /// Represents a dynamic operation.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.DynamicExpressionProxy))]
- public class DynamicExpression : Expression, IArgumentProvider {
- private readonly CallSiteBinder _binder;
- private readonly Type _delegateType;
-
- internal DynamicExpression(Type delegateType, CallSiteBinder binder) {
- Debug.Assert(delegateType.GetMethod("Invoke").GetReturnType() == typeof(object) || GetType() != typeof(DynamicExpression));
- _delegateType = delegateType;
- _binder = binder;
- }
-
- internal static DynamicExpression Make(Type returnType, Type delegateType, CallSiteBinder binder, ReadOnlyCollection<Expression> arguments) {
- if (returnType == typeof(object)) {
- return new DynamicExpressionN(delegateType, binder, arguments);
- } else {
- return new TypedDynamicExpressionN(returnType, delegateType, binder, arguments);
- }
- }
-
- internal static DynamicExpression Make(Type returnType, Type delegateType, CallSiteBinder binder, Expression arg0) {
- if (returnType == typeof(object)) {
- return new DynamicExpression1(delegateType, binder, arg0);
- } else {
- return new TypedDynamicExpression1(returnType, delegateType, binder, arg0);
- }
- }
-
- internal static DynamicExpression Make(Type returnType, Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1) {
- if (returnType == typeof(object)) {
- return new DynamicExpression2(delegateType, binder, arg0, arg1);
- } else {
- return new TypedDynamicExpression2(returnType, delegateType, binder, arg0, arg1);
- }
- }
-
- internal static DynamicExpression Make(Type returnType, Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1, Expression arg2) {
- if (returnType == typeof(object)) {
- return new DynamicExpression3(delegateType, binder, arg0, arg1, arg2);
- } else {
- return new TypedDynamicExpression3(returnType, delegateType, binder, arg0, arg1, arg2);
- }
- }
-
- internal static DynamicExpression Make(Type returnType, Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1, Expression arg2, Expression arg3) {
- if (returnType == typeof(object)) {
- return new DynamicExpression4(delegateType, binder, arg0, arg1, arg2, arg3);
- } else {
- return new TypedDynamicExpression4(returnType, delegateType, binder, arg0, arg1, arg2, arg3);
- }
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents.
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public override Type Type {
- get { return typeof(object); }
- }
-
- /// <summary>
- /// Returns the node type of this Expression. Extension nodes should return
- /// ExpressionType.Extension when overriding this method.
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Dynamic; }
- }
-
- /// <summary>
- /// Gets the <see cref="CallSiteBinder" />, which determines the runtime behavior of the
- /// dynamic site.
- /// </summary>
- public CallSiteBinder Binder {
- get { return _binder; }
- }
-
- /// <summary>
- /// Gets the type of the delegate used by the <see cref="CallSite" />.
- /// </summary>
- public Type DelegateType {
- get { return _delegateType; }
- }
-
- /// <summary>
- /// Gets the arguments to the dynamic operation.
- /// </summary>
- public ReadOnlyCollection<Expression> Arguments {
- get { return GetOrMakeArguments(); }
- }
-
- internal virtual ReadOnlyCollection<Expression> GetOrMakeArguments() {
- throw ContractUtils.Unreachable;
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitDynamic(this);
- }
-
- /// <summary>
- /// Makes a copy of this node replacing the args with the provided values. The
- /// number of the args needs to match the number of the current block.
- ///
- /// This helper is provided to allow re-writing of nodes to not depend on the specific optimized
- /// subclass of DynamicExpression which is being used.
- /// </summary>
- internal virtual DynamicExpression Rewrite(Expression[] args) {
- throw ContractUtils.Unreachable;
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="arguments">The <see cref="Arguments" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public DynamicExpression Update(IEnumerable<Expression> arguments) {
- if (arguments == Arguments) {
- return this;
- }
-
- return Expression.MakeDynamic(DelegateType, Binder, arguments);
- }
-
- #region IArgumentProvider Members
-
- Expression IArgumentProvider.GetArgument(int index) {
- throw ContractUtils.Unreachable;
- }
-
- int IArgumentProvider.ArgumentCount {
- get { throw ContractUtils.Unreachable; }
- }
-
- #endregion
- }
-
- #region Specialized Subclasses
-
- internal class DynamicExpressionN : DynamicExpression, IArgumentProvider {
- private IList<Expression> _arguments; // storage for the original IList or readonly collection. See IArgumentProvider for more info.
-
- internal DynamicExpressionN(Type delegateType, CallSiteBinder binder, IList<Expression> arguments)
- : base(delegateType, binder) {
- _arguments = arguments;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- return _arguments[index];
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return _arguments.Count;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(ref _arguments);
- }
-
- internal override DynamicExpression Rewrite(Expression[] args) {
- Debug.Assert(args.Length == ((IArgumentProvider)this).ArgumentCount);
-
- return Expression.MakeDynamic(DelegateType, Binder, args);
- }
- }
-
- internal class TypedDynamicExpressionN : DynamicExpressionN {
- private readonly Type _returnType;
-
- internal TypedDynamicExpressionN(Type returnType, Type delegateType, CallSiteBinder binder, IList<Expression> arguments)
- : base(delegateType, binder, arguments) {
- Debug.Assert(delegateType.GetMethod("Invoke").GetReturnType() == returnType);
- _returnType = returnType;
- }
-
- public sealed override Type Type {
- get { return _returnType; }
- }
- }
-
- internal class DynamicExpression1 : DynamicExpression, IArgumentProvider {
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider for more info.
-
- internal DynamicExpression1(Type delegateType, CallSiteBinder binder, Expression arg0)
- : base(delegateType, binder) {
- _arg0 = arg0;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- default: throw new InvalidOperationException();
- }
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return 1;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(this, ref _arg0);
- }
-
- internal override DynamicExpression Rewrite(Expression[] args) {
- Debug.Assert(args.Length == 1);
-
- return Expression.MakeDynamic(DelegateType, Binder, args[0]);
- }
- }
-
- internal sealed class TypedDynamicExpression1 : DynamicExpression1 {
- private readonly Type _retType;
-
- internal TypedDynamicExpression1(Type retType, Type delegateType, CallSiteBinder binder, Expression arg0)
- : base(delegateType, binder, arg0) {
- _retType = retType;
- }
-
- public sealed override Type Type {
- get { return _retType; }
- }
- }
-
- internal class DynamicExpression2 : DynamicExpression, IArgumentProvider {
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider for more info.
- private readonly Expression _arg1; // storage for the 2nd argument
-
- internal DynamicExpression2(Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1)
- : base(delegateType, binder) {
- _arg0 = arg0;
- _arg1 = arg1;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- case 1: return _arg1;
- default: throw new InvalidOperationException();
- }
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return 2;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(this, ref _arg0);
- }
-
- internal override DynamicExpression Rewrite(Expression[] args) {
- Debug.Assert(args.Length == 2);
-
- return Expression.MakeDynamic(DelegateType, Binder, args[0], args[1]);
- }
- }
-
- internal sealed class TypedDynamicExpression2 : DynamicExpression2 {
- private readonly Type _retType;
-
- internal TypedDynamicExpression2(Type retType, Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1)
- : base(delegateType, binder, arg0, arg1) {
- _retType = retType;
- }
-
- public sealed override Type Type {
- get { return _retType; }
- }
- }
-
- internal class DynamicExpression3 : DynamicExpression, IArgumentProvider {
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider for more info.
- private readonly Expression _arg1, _arg2; // storage for the 2nd & 3rd arguments
-
- internal DynamicExpression3(Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1, Expression arg2)
- : base(delegateType, binder) {
- _arg0 = arg0;
- _arg1 = arg1;
- _arg2 = arg2;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- case 1: return _arg1;
- case 2: return _arg2;
- default: throw new InvalidOperationException();
- }
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return 3;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(this, ref _arg0);
- }
-
- internal override DynamicExpression Rewrite(Expression[] args) {
- Debug.Assert(args.Length == 3);
-
- return Expression.MakeDynamic(DelegateType, Binder, args[0], args[1], args[2]);
- }
- }
-
- internal sealed class TypedDynamicExpression3 : DynamicExpression3 {
- private readonly Type _retType;
-
- internal TypedDynamicExpression3(Type retType, Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1, Expression arg2)
- : base(delegateType, binder, arg0, arg1, arg2) {
- _retType = retType;
- }
-
- public sealed override Type Type {
- get { return _retType; }
- }
- }
-
- internal class DynamicExpression4 : DynamicExpression, IArgumentProvider {
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider for more info.
- private readonly Expression _arg1, _arg2, _arg3; // storage for the 2nd - 4th arguments
-
- internal DynamicExpression4(Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1, Expression arg2, Expression arg3)
- : base(delegateType, binder) {
- _arg0 = arg0;
- _arg1 = arg1;
- _arg2 = arg2;
- _arg3 = arg3;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- case 1: return _arg1;
- case 2: return _arg2;
- case 3: return _arg3;
- default: throw new InvalidOperationException();
- }
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return 4;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(this, ref _arg0);
- }
-
- internal override DynamicExpression Rewrite(Expression[] args) {
- Debug.Assert(args.Length == 4);
-
- return Expression.MakeDynamic(DelegateType, Binder, args[0], args[1], args[2], args[3]);
- }
- }
-
- internal sealed class TypedDynamicExpression4 : DynamicExpression4 {
- private readonly Type _retType;
-
- internal TypedDynamicExpression4(Type retType, Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1, Expression arg2, Expression arg3)
- : base(delegateType, binder, arg0, arg1, arg2, arg3) {
- _retType = retType;
- }
-
- public sealed override Type Type {
- get { return _retType; }
- }
- }
-
- #endregion
-
- public partial class Expression {
-
- /// <summary>
- /// Creates a <see cref="DynamicExpression" /> that represents a dynamic operation bound by the provided <see cref="CallSiteBinder" />.
- /// </summary>
- /// <param name="delegateType">The type of the delegate used by the <see cref="CallSite" />.</param>
- /// <param name="binder">The runtime binder for the dynamic operation.</param>
- /// <param name="arguments">The arguments to the dynamic operation.</param>
- /// <returns>
- /// A <see cref="DynamicExpression" /> that has <see cref="NodeType" /> equal to
- /// <see cref="ExpressionType.Dynamic">Dynamic</see> and has the
- /// <see cref="DynamicExpression.DelegateType">DelegateType</see>,
- /// <see cref="DynamicExpression.Binder">Binder</see>, and
- /// <see cref="DynamicExpression.Arguments">Arguments</see> set to the specified values.
- /// </returns>
- public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder binder, params Expression[] arguments) {
- return MakeDynamic(delegateType, binder, (IEnumerable<Expression>)arguments);
- }
-
- /// <summary>
- /// Creates a <see cref="DynamicExpression" /> that represents a dynamic operation bound by the provided <see cref="CallSiteBinder" />.
- /// </summary>
- /// <param name="delegateType">The type of the delegate used by the <see cref="CallSite" />.</param>
- /// <param name="binder">The runtime binder for the dynamic operation.</param>
- /// <param name="arguments">The arguments to the dynamic operation.</param>
- /// <returns>
- /// A <see cref="DynamicExpression" /> that has <see cref="NodeType" /> equal to
- /// <see cref="ExpressionType.Dynamic">Dynamic</see> and has the
- /// <see cref="DynamicExpression.DelegateType">DelegateType</see>,
- /// <see cref="DynamicExpression.Binder">Binder</see>, and
- /// <see cref="DynamicExpression.Arguments">Arguments</see> set to the specified values.
- /// </returns>
- public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder binder, IEnumerable<Expression> arguments) {
- ContractUtils.RequiresNotNull(delegateType, "delegateType");
- ContractUtils.RequiresNotNull(binder, "binder");
- if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate();
-
- var method = GetValidMethodForDynamic(delegateType);
-
- var args = arguments.ToReadOnly();
- ValidateArgumentTypes(method, ExpressionType.Dynamic, ref args);
-
- return DynamicExpression.Make(method.GetReturnType(), delegateType, binder, args);
- }
-
- /// <summary>
- /// Creates a <see cref="DynamicExpression" /> that represents a dynamic operation bound by the provided <see cref="CallSiteBinder" /> and one argument.
- /// </summary>
- /// <param name="delegateType">The type of the delegate used by the <see cref="CallSite" />.</param>
- /// <param name="binder">The runtime binder for the dynamic operation.</param>
- /// <param name="arg0">The argument to the dynamic operation.</param>
- /// <returns>
- /// A <see cref="DynamicExpression" /> that has <see cref="NodeType" /> equal to
- /// <see cref="ExpressionType.Dynamic">Dynamic</see> and has the
- /// <see cref="DynamicExpression.DelegateType">DelegateType</see>,
- /// <see cref="DynamicExpression.Binder">Binder</see>, and
- /// <see cref="DynamicExpression.Arguments">Arguments</see> set to the specified values.
- /// </returns>
- public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder binder, Expression arg0) {
- ContractUtils.RequiresNotNull(delegateType, "delegateType");
- ContractUtils.RequiresNotNull(binder, "binder");
- if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate();
-
- var method = GetValidMethodForDynamic(delegateType);
- var parameters = method.GetParametersCached();
-
- ValidateArgumentCount(method, ExpressionType.Dynamic, 2, parameters);
- ValidateDynamicArgument(arg0);
- ValidateOneArgument(method, ExpressionType.Dynamic, arg0, parameters[1]);
-
- return DynamicExpression.Make(method.GetReturnType(), delegateType, binder, arg0);
- }
-
- /// <summary>
- /// Creates a <see cref="DynamicExpression" /> that represents a dynamic operation bound by the provided <see cref="CallSiteBinder" /> and two arguments.
- /// </summary>
- /// <param name="delegateType">The type of the delegate used by the <see cref="CallSite" />.</param>
- /// <param name="binder">The runtime binder for the dynamic operation.</param>
- /// <param name="arg0">The first argument to the dynamic operation.</param>
- /// <param name="arg1">The second argument to the dynamic operation.</param>
- /// <returns>
- /// A <see cref="DynamicExpression" /> that has <see cref="NodeType" /> equal to
- /// <see cref="ExpressionType.Dynamic">Dynamic</see> and has the
- /// <see cref="DynamicExpression.DelegateType">DelegateType</see>,
- /// <see cref="DynamicExpression.Binder">Binder</see>, and
- /// <see cref="DynamicExpression.Arguments">Arguments</see> set to the specified values.
- /// </returns>
- public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1) {
- ContractUtils.RequiresNotNull(delegateType, "delegateType");
- ContractUtils.RequiresNotNull(binder, "binder");
- if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate();
-
- var method = GetValidMethodForDynamic(delegateType);
- var parameters = method.GetParametersCached();
-
- ValidateArgumentCount(method, ExpressionType.Dynamic, 3, parameters);
- ValidateDynamicArgument(arg0);
- ValidateOneArgument(method, ExpressionType.Dynamic, arg0, parameters[1]);
- ValidateDynamicArgument(arg1);
- ValidateOneArgument(method, ExpressionType.Dynamic, arg1, parameters[2]);
-
- return DynamicExpression.Make(method.GetReturnType(), delegateType, binder, arg0, arg1);
- }
-
- /// <summary>
- /// Creates a <see cref="DynamicExpression" /> that represents a dynamic operation bound by the provided <see cref="CallSiteBinder" /> and three arguments.
- /// </summary>
- /// <param name="delegateType">The type of the delegate used by the <see cref="CallSite" />.</param>
- /// <param name="binder">The runtime binder for the dynamic operation.</param>
- /// <param name="arg0">The first argument to the dynamic operation.</param>
- /// <param name="arg1">The second argument to the dynamic operation.</param>
- /// <param name="arg2">The third argument to the dynamic operation.</param>
- /// <returns>
- /// A <see cref="DynamicExpression" /> that has <see cref="NodeType" /> equal to
- /// <see cref="ExpressionType.Dynamic">Dynamic</see> and has the
- /// <see cref="DynamicExpression.DelegateType">DelegateType</see>,
- /// <see cref="DynamicExpression.Binder">Binder</see>, and
- /// <see cref="DynamicExpression.Arguments">Arguments</see> set to the specified values.
- /// </returns>
- public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1, Expression arg2) {
- ContractUtils.RequiresNotNull(delegateType, "delegateType");
- ContractUtils.RequiresNotNull(binder, "binder");
- if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate();
-
- var method = GetValidMethodForDynamic(delegateType);
- var parameters = method.GetParametersCached();
-
- ValidateArgumentCount(method, ExpressionType.Dynamic, 4, parameters);
- ValidateDynamicArgument(arg0);
- ValidateOneArgument(method, ExpressionType.Dynamic, arg0, parameters[1]);
- ValidateDynamicArgument(arg1);
- ValidateOneArgument(method, ExpressionType.Dynamic, arg1, parameters[2]);
- ValidateDynamicArgument(arg2);
- ValidateOneArgument(method, ExpressionType.Dynamic, arg2, parameters[3]);
-
- return DynamicExpression.Make(method.GetReturnType(), delegateType, binder, arg0, arg1, arg2);
- }
-
- /// <summary>
- /// Creates a <see cref="DynamicExpression" /> that represents a dynamic operation bound by the provided <see cref="CallSiteBinder" /> and four arguments.
- /// </summary>
- /// <param name="delegateType">The type of the delegate used by the <see cref="CallSite" />.</param>
- /// <param name="binder">The runtime binder for the dynamic operation.</param>
- /// <param name="arg0">The first argument to the dynamic operation.</param>
- /// <param name="arg1">The second argument to the dynamic operation.</param>
- /// <param name="arg2">The third argument to the dynamic operation.</param>
- /// <param name="arg3">The fourth argument to the dynamic operation.</param>
- /// <returns>
- /// A <see cref="DynamicExpression" /> that has <see cref="NodeType" /> equal to
- /// <see cref="ExpressionType.Dynamic">Dynamic</see> and has the
- /// <see cref="DynamicExpression.DelegateType">DelegateType</see>,
- /// <see cref="DynamicExpression.Binder">Binder</see>, and
- /// <see cref="DynamicExpression.Arguments">Arguments</see> set to the specified values.
- /// </returns>
- public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1, Expression arg2, Expression arg3) {
- ContractUtils.RequiresNotNull(delegateType, "delegateType");
- ContractUtils.RequiresNotNull(binder, "binder");
- if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate();
-
- var method = GetValidMethodForDynamic(delegateType);
- var parameters = method.GetParametersCached();
-
- ValidateArgumentCount(method, ExpressionType.Dynamic, 5, parameters);
- ValidateDynamicArgument(arg0);
- ValidateOneArgument(method, ExpressionType.Dynamic, arg0, parameters[1]);
- ValidateDynamicArgument(arg1);
- ValidateOneArgument(method, ExpressionType.Dynamic, arg1, parameters[2]);
- ValidateDynamicArgument(arg2);
- ValidateOneArgument(method, ExpressionType.Dynamic, arg2, parameters[3]);
- ValidateDynamicArgument(arg3);
- ValidateOneArgument(method, ExpressionType.Dynamic, arg3, parameters[4]);
-
- return DynamicExpression.Make(method.GetReturnType(), delegateType, binder, arg0, arg1, arg2, arg3);
- }
-
- private static MethodInfo GetValidMethodForDynamic(Type delegateType) {
- var method = delegateType.GetMethod("Invoke");
- var pi = method.GetParametersCached();
- if (pi.Length == 0 || pi[0].ParameterType != typeof(CallSite)) throw Error.FirstArgumentMustBeCallSite();
- return method;
- }
-
- /// <summary>
- /// Creates a <see cref="DynamicExpression" /> that represents a dynamic operation bound by the provided <see cref="CallSiteBinder" />.
- /// </summary>
- /// <param name="binder">The runtime binder for the dynamic operation.</param>
- /// <param name="returnType">The result type of the dynamic expression.</param>
- /// <param name="arguments">The arguments to the dynamic operation.</param>
- /// <returns>
- /// A <see cref="DynamicExpression" /> that has <see cref="NodeType" /> equal to
- /// <see cref="ExpressionType.Dynamic">Dynamic</see> and has the
- /// <see cref="DynamicExpression.Binder">Binder</see> and
- /// <see cref="DynamicExpression.Arguments">Arguments</see> set to the specified values.
- /// </returns>
- /// <remarks>
- /// The <see cref="DynamicExpression.DelegateType">DelegateType</see> property of the
- /// result will be inferred from the types of the arguments and the specified return type.
- /// </remarks>
- public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, params Expression[] arguments) {
- return Dynamic(binder, returnType, (IEnumerable<Expression>)arguments);
- }
-
- /// <summary>
- /// Creates a <see cref="DynamicExpression" /> that represents a dynamic operation bound by the provided <see cref="CallSiteBinder" />.
- /// </summary>
- /// <param name="binder">The runtime binder for the dynamic operation.</param>
- /// <param name="returnType">The result type of the dynamic expression.</param>
- /// <param name="arg0">The first argument to the dynamic operation.</param>
- /// <returns>
- /// A <see cref="DynamicExpression" /> that has <see cref="NodeType" /> equal to
- /// <see cref="ExpressionType.Dynamic">Dynamic</see> and has the
- /// <see cref="DynamicExpression.Binder">Binder</see> and
- /// <see cref="DynamicExpression.Arguments">Arguments</see> set to the specified values.
- /// </returns>
- /// <remarks>
- /// The <see cref="DynamicExpression.DelegateType">DelegateType</see> property of the
- /// result will be inferred from the types of the arguments and the specified return type.
- /// </remarks>
- public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, Expression arg0) {
- ContractUtils.RequiresNotNull(binder, "binder");
- ValidateDynamicArgument(arg0);
-
- DelegateHelpers.TypeInfo info = DelegateHelpers.GetNextTypeInfo(
- returnType,
- DelegateHelpers.GetNextTypeInfo(
- arg0.Type,
- DelegateHelpers.NextTypeInfo(typeof(CallSite))
- )
- );
-
- Type delegateType = info.DelegateType;
- if (delegateType == null) {
- delegateType = info.MakeDelegateType(returnType, arg0);
- }
-
- return DynamicExpression.Make(returnType, delegateType, binder, arg0);
- }
-
- /// <summary>
- /// Creates a <see cref="DynamicExpression" /> that represents a dynamic operation bound by the provided <see cref="CallSiteBinder" />.
- /// </summary>
- /// <param name="binder">The runtime binder for the dynamic operation.</param>
- /// <param name="returnType">The result type of the dynamic expression.</param>
- /// <param name="arg0">The first argument to the dynamic operation.</param>
- /// <param name="arg1">The second argument to the dynamic operation.</param>
- /// <returns>
- /// A <see cref="DynamicExpression" /> that has <see cref="NodeType" /> equal to
- /// <see cref="ExpressionType.Dynamic">Dynamic</see> and has the
- /// <see cref="DynamicExpression.Binder">Binder</see> and
- /// <see cref="DynamicExpression.Arguments">Arguments</see> set to the specified values.
- /// </returns>
- /// <remarks>
- /// The <see cref="DynamicExpression.DelegateType">DelegateType</see> property of the
- /// result will be inferred from the types of the arguments and the specified return type.
- /// </remarks>
- public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, Expression arg0, Expression arg1) {
- ContractUtils.RequiresNotNull(binder, "binder");
- ValidateDynamicArgument(arg0);
- ValidateDynamicArgument(arg1);
-
- DelegateHelpers.TypeInfo info = DelegateHelpers.GetNextTypeInfo(
- returnType,
- DelegateHelpers.GetNextTypeInfo(
- arg1.Type,
- DelegateHelpers.GetNextTypeInfo(
- arg0.Type,
- DelegateHelpers.NextTypeInfo(typeof(CallSite))
- )
- )
- );
-
- Type delegateType = info.DelegateType;
- if (delegateType == null) {
- delegateType = info.MakeDelegateType(returnType, arg0, arg1);
- }
-
- return DynamicExpression.Make(returnType, delegateType, binder, arg0, arg1);
- }
-
- /// <summary>
- /// Creates a <see cref="DynamicExpression" /> that represents a dynamic operation bound by the provided <see cref="CallSiteBinder" />.
- /// </summary>
- /// <param name="binder">The runtime binder for the dynamic operation.</param>
- /// <param name="returnType">The result type of the dynamic expression.</param>
- /// <param name="arg0">The first argument to the dynamic operation.</param>
- /// <param name="arg1">The second argument to the dynamic operation.</param>
- /// <param name="arg2">The third argument to the dynamic operation.</param>
- /// <returns>
- /// A <see cref="DynamicExpression" /> that has <see cref="NodeType" /> equal to
- /// <see cref="ExpressionType.Dynamic">Dynamic</see> and has the
- /// <see cref="DynamicExpression.Binder">Binder</see> and
- /// <see cref="DynamicExpression.Arguments">Arguments</see> set to the specified values.
- /// </returns>
- /// <remarks>
- /// The <see cref="DynamicExpression.DelegateType">DelegateType</see> property of the
- /// result will be inferred from the types of the arguments and the specified return type.
- /// </remarks>
- public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, Expression arg0, Expression arg1, Expression arg2) {
- ContractUtils.RequiresNotNull(binder, "binder");
- ValidateDynamicArgument(arg0);
- ValidateDynamicArgument(arg1);
- ValidateDynamicArgument(arg2);
-
- DelegateHelpers.TypeInfo info = DelegateHelpers.GetNextTypeInfo(
- returnType,
- DelegateHelpers.GetNextTypeInfo(
- arg2.Type,
- DelegateHelpers.GetNextTypeInfo(
- arg1.Type,
- DelegateHelpers.GetNextTypeInfo(
- arg0.Type,
- DelegateHelpers.NextTypeInfo(typeof(CallSite))
- )
- )
- )
- );
-
- Type delegateType = info.DelegateType;
- if (delegateType == null) {
- delegateType = info.MakeDelegateType(returnType, arg0, arg1, arg2);
- }
-
- return DynamicExpression.Make(returnType, delegateType, binder, arg0, arg1, arg2);
- }
-
- /// <summary>
- /// Creates a <see cref="DynamicExpression" /> that represents a dynamic operation bound by the provided <see cref="CallSiteBinder" />.
- /// </summary>
- /// <param name="binder">The runtime binder for the dynamic operation.</param>
- /// <param name="returnType">The result type of the dynamic expression.</param>
- /// <param name="arg0">The first argument to the dynamic operation.</param>
- /// <param name="arg1">The second argument to the dynamic operation.</param>
- /// <param name="arg2">The third argument to the dynamic operation.</param>
- /// <param name="arg3">The fourth argument to the dynamic operation.</param>
- /// <returns>
- /// A <see cref="DynamicExpression" /> that has <see cref="NodeType" /> equal to
- /// <see cref="ExpressionType.Dynamic">Dynamic</see> and has the
- /// <see cref="DynamicExpression.Binder">Binder</see> and
- /// <see cref="DynamicExpression.Arguments">Arguments</see> set to the specified values.
- /// </returns>
- /// <remarks>
- /// The <see cref="DynamicExpression.DelegateType">DelegateType</see> property of the
- /// result will be inferred from the types of the arguments and the specified return type.
- /// </remarks>
- public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, Expression arg0, Expression arg1, Expression arg2, Expression arg3) {
- ContractUtils.RequiresNotNull(binder, "binder");
- ValidateDynamicArgument(arg0);
- ValidateDynamicArgument(arg1);
- ValidateDynamicArgument(arg2);
- ValidateDynamicArgument(arg3);
-
- DelegateHelpers.TypeInfo info = DelegateHelpers.GetNextTypeInfo(
- returnType,
- DelegateHelpers.GetNextTypeInfo(
- arg3.Type,
- DelegateHelpers.GetNextTypeInfo(
- arg2.Type,
- DelegateHelpers.GetNextTypeInfo(
- arg1.Type,
- DelegateHelpers.GetNextTypeInfo(
- arg0.Type,
- DelegateHelpers.NextTypeInfo(typeof(CallSite))
- )
- )
- )
- )
- );
-
- Type delegateType = info.DelegateType;
- if (delegateType == null) {
- delegateType = info.MakeDelegateType(returnType, arg0, arg1, arg2, arg3);
- }
-
- return DynamicExpression.Make(returnType, delegateType, binder, arg0, arg1, arg2, arg3);
- }
-
- /// <summary>
- /// Creates a <see cref="DynamicExpression" /> that represents a dynamic operation bound by the provided <see cref="CallSiteBinder" />.
- /// </summary>
- /// <param name="binder">The runtime binder for the dynamic operation.</param>
- /// <param name="returnType">The result type of the dynamic expression.</param>
- /// <param name="arguments">The arguments to the dynamic operation.</param>
- /// <returns>
- /// A <see cref="DynamicExpression" /> that has <see cref="NodeType" /> equal to
- /// <see cref="ExpressionType.Dynamic">Dynamic</see> and has the
- /// <see cref="DynamicExpression.Binder">Binder</see> and
- /// <see cref="DynamicExpression.Arguments">Arguments</see> set to the specified values.
- /// </returns>
- /// <remarks>
- /// The <see cref="DynamicExpression.DelegateType">DelegateType</see> property of the
- /// result will be inferred from the types of the arguments and the specified return type.
- /// </remarks>
- public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, IEnumerable<Expression> arguments) {
- ContractUtils.RequiresNotNull(arguments, "arguments");
- ContractUtils.RequiresNotNull(returnType, "returnType");
-
- var args = arguments.ToReadOnly();
- ContractUtils.RequiresNotEmpty(args, "args");
- return MakeDynamic(binder, returnType, args);
- }
-
- private static DynamicExpression MakeDynamic(CallSiteBinder binder, Type returnType, ReadOnlyCollection<Expression> args) {
- ContractUtils.RequiresNotNull(binder, "binder");
-
- for (int i = 0; i < args.Count; i++) {
- Expression arg = args[i];
-
- ValidateDynamicArgument(arg);
- }
-
- Type delegateType = DelegateHelpers.MakeCallSiteDelegate(args, returnType);
-
- // Since we made a delegate with argument types that exactly match,
- // we can skip delegate and argument validation
-
- switch (args.Count) {
- case 1: return DynamicExpression.Make(returnType, delegateType, binder, args[0]);
- case 2: return DynamicExpression.Make(returnType, delegateType, binder, args[0], args[1]);
- case 3: return DynamicExpression.Make(returnType, delegateType, binder, args[0], args[1], args[2]);
- case 4: return DynamicExpression.Make(returnType, delegateType, binder, args[0], args[1], args[2], args[3]);
- default: return DynamicExpression.Make(returnType, delegateType, binder, args);
- }
- }
-
- private static void ValidateDynamicArgument(Expression arg) {
- RequiresCanRead(arg, "arguments");
- var type = arg.Type;
- ContractUtils.RequiresNotNull(type, "type");
- TypeUtils.ValidateType(type);
- if (type == typeof(void)) throw Error.ArgumentTypeCannotBeVoid();
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ElementInit.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ElementInit.cs
deleted file mode 100644
index 21f87689d6a..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ElementInit.cs
+++ /dev/null
@@ -1,135 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Reflection;
-using System.Text;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents the initialization of a list.
- /// </summary>
- public sealed class ElementInit : IArgumentProvider {
- private MethodInfo _addMethod;
- private ReadOnlyCollection<Expression> _arguments;
-
- internal ElementInit(MethodInfo addMethod, ReadOnlyCollection<Expression> arguments) {
- _addMethod = addMethod;
- _arguments = arguments;
- }
- /// <summary>
- /// Gets the <see cref="MethodInfo"/> used to add elements to the object.
- /// </summary>
- public MethodInfo AddMethod {
- get { return _addMethod; }
- }
-
- /// <summary>
- /// Gets the list of elements to be added to the object.
- /// </summary>
- public ReadOnlyCollection<Expression> Arguments {
- get { return _arguments; }
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- return _arguments[index];
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return _arguments.Count;
- }
- }
-
- /// <summary>
- /// Creates a <see cref="String"/> representation of the node.
- /// </summary>
- /// <returns>A <see cref="String"/> representation of the node.</returns>
- public override string ToString() {
- return ExpressionStringBuilder.ElementInitBindingToString(this);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="arguments">The <see cref="Arguments" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public ElementInit Update(IEnumerable<Expression> arguments) {
- if (arguments == Arguments) {
- return this;
- }
- return Expression.ElementInit(AddMethod, arguments);
- }
- }
-
-
- public partial class Expression {
- /// <summary>
- /// Creates an <see cref="T:ElementInit">ElementInit</see> expression that represents the initialization of a list.
- /// </summary>
- /// <param name="addMethod">The <see cref="MethodInfo"/> for the list's Add method.</param>
- /// <param name="arguments">An array containing the Expressions to be used to initialize the list.</param>
- /// <returns>The created <see cref="T:ElementInit">ElementInit</see> expression.</returns>
- public static ElementInit ElementInit(MethodInfo addMethod, params Expression[] arguments) {
- return ElementInit(addMethod, arguments as IEnumerable<Expression>);
- }
-
- /// <summary>
- /// Creates an <see cref="T:ElementInit">ElementInit</see> expression that represents the initialization of a list.
- /// </summary>
- /// <param name="addMethod">The <see cref="MethodInfo"/> for the list's Add method.</param>
- /// <param name="arguments">An <see cref="IEnumerable{T}"/> containing <see cref="Expression"/> elements to initialize the list.</param>
- /// <returns>The created <see cref="T:ElementInit">ElementInit</see> expression.</returns>
- public static ElementInit ElementInit(MethodInfo addMethod, IEnumerable<Expression> arguments) {
- ContractUtils.RequiresNotNull(addMethod, "addMethod");
- ContractUtils.RequiresNotNull(arguments, "arguments");
-
- var argumentsRO = arguments.ToReadOnly();
-
- RequiresCanRead(argumentsRO, "arguments");
- ValidateElementInitAddMethodInfo(addMethod);
- ValidateArgumentTypes(addMethod, ExpressionType.Call, ref argumentsRO);
- return new ElementInit(addMethod, argumentsRO);
- }
-
- private static void ValidateElementInitAddMethodInfo(MethodInfo addMethod) {
- ValidateMethodInfo(addMethod);
- ParameterInfo[] pis = addMethod.GetParametersCached();
- if (pis.Length == 0) {
- throw Error.ElementInitializerMethodWithZeroArgs();
- }
- if (!addMethod.Name.Equals("Add", StringComparison.OrdinalIgnoreCase)) {
- throw Error.ElementInitializerMethodNotAdd();
- }
- if (addMethod.IsStatic) {
- throw Error.ElementInitializerMethodStatic();
- }
- foreach (ParameterInfo pi in pis) {
- if (pi.ParameterType.IsByRef) {
- throw Error.ElementInitializerMethodNoRefOutParam(pi.Name, addMethod.Name);
- }
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/Expression.DebuggerProxy.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/Expression.DebuggerProxy.cs
deleted file mode 100644
index 3d1d6c9e352..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/Expression.DebuggerProxy.cs
+++ /dev/null
@@ -1,455 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.ObjectModel;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- public partial class Expression {
- #region Generated Expression Debugger Proxies
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_debug_proxies from: generate_tree.py
-
- internal class BinaryExpressionProxy {
- private readonly BinaryExpression _node;
-
- public BinaryExpressionProxy(BinaryExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public LambdaExpression Conversion { get { return _node.Conversion; } }
- public String DebugView { get { return _node.DebugView; } }
- public Boolean IsLifted { get { return _node.IsLifted; } }
- public Boolean IsLiftedToNull { get { return _node.IsLiftedToNull; } }
- public Expression Left { get { return _node.Left; } }
- public MethodInfo Method { get { return _node.Method; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Expression Right { get { return _node.Right; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class BlockExpressionProxy {
- private readonly BlockExpression _node;
-
- public BlockExpressionProxy(BlockExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public ReadOnlyCollection<Expression> Expressions { get { return _node.Expressions; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Expression Result { get { return _node.Result; } }
- public Type Type { get { return _node.Type; } }
- public ReadOnlyCollection<ParameterExpression> Variables { get { return _node.Variables; } }
- }
-
- internal class CatchBlockProxy {
- private readonly CatchBlock _node;
-
- public CatchBlockProxy(CatchBlock node) {
- _node = node;
- }
-
- public Expression Body { get { return _node.Body; } }
- public Expression Filter { get { return _node.Filter; } }
- public Type Test { get { return _node.Test; } }
- public ParameterExpression Variable { get { return _node.Variable; } }
- }
-
- internal class ConditionalExpressionProxy {
- private readonly ConditionalExpression _node;
-
- public ConditionalExpressionProxy(ConditionalExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public Expression IfFalse { get { return _node.IfFalse; } }
- public Expression IfTrue { get { return _node.IfTrue; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Expression Test { get { return _node.Test; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class ConstantExpressionProxy {
- private readonly ConstantExpression _node;
-
- public ConstantExpressionProxy(ConstantExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- public Object Value { get { return _node.Value; } }
- }
-
- internal class DebugInfoExpressionProxy {
- private readonly DebugInfoExpression _node;
-
- public DebugInfoExpressionProxy(DebugInfoExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public SymbolDocumentInfo Document { get { return _node.Document; } }
- public Int32 EndColumn { get { return _node.EndColumn; } }
- public Int32 EndLine { get { return _node.EndLine; } }
- public Boolean IsClear { get { return _node.IsClear; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Int32 StartColumn { get { return _node.StartColumn; } }
- public Int32 StartLine { get { return _node.StartLine; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class DefaultExpressionProxy {
- private readonly DefaultExpression _node;
-
- public DefaultExpressionProxy(DefaultExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class DynamicExpressionProxy {
- private readonly DynamicExpression _node;
-
- public DynamicExpressionProxy(DynamicExpression node) {
- _node = node;
- }
-
- public ReadOnlyCollection<Expression> Arguments { get { return _node.Arguments; } }
- public CallSiteBinder Binder { get { return _node.Binder; } }
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public Type DelegateType { get { return _node.DelegateType; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class GotoExpressionProxy {
- private readonly GotoExpression _node;
-
- public GotoExpressionProxy(GotoExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public GotoExpressionKind Kind { get { return _node.Kind; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public LabelTarget Target { get { return _node.Target; } }
- public Type Type { get { return _node.Type; } }
- public Expression Value { get { return _node.Value; } }
- }
-
- internal class IndexExpressionProxy {
- private readonly IndexExpression _node;
-
- public IndexExpressionProxy(IndexExpression node) {
- _node = node;
- }
-
- public ReadOnlyCollection<Expression> Arguments { get { return _node.Arguments; } }
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public PropertyInfo Indexer { get { return _node.Indexer; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Expression Object { get { return _node.Object; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class InvocationExpressionProxy {
- private readonly InvocationExpression _node;
-
- public InvocationExpressionProxy(InvocationExpression node) {
- _node = node;
- }
-
- public ReadOnlyCollection<Expression> Arguments { get { return _node.Arguments; } }
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public Expression Expression { get { return _node.Expression; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class LabelExpressionProxy {
- private readonly LabelExpression _node;
-
- public LabelExpressionProxy(LabelExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public Expression DefaultValue { get { return _node.DefaultValue; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public LabelTarget Target { get { return _node.Target; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class LambdaExpressionProxy {
- private readonly LambdaExpression _node;
-
- public LambdaExpressionProxy(LambdaExpression node) {
- _node = node;
- }
-
- public Expression Body { get { return _node.Body; } }
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public String Name { get { return _node.Name; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public ReadOnlyCollection<ParameterExpression> Parameters { get { return _node.Parameters; } }
- public Type ReturnType { get { return _node.ReturnType; } }
- public Boolean TailCall { get { return _node.TailCall; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class ListInitExpressionProxy {
- private readonly ListInitExpression _node;
-
- public ListInitExpressionProxy(ListInitExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public ReadOnlyCollection<ElementInit> Initializers { get { return _node.Initializers; } }
- public NewExpression NewExpression { get { return _node.NewExpression; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class LoopExpressionProxy {
- private readonly LoopExpression _node;
-
- public LoopExpressionProxy(LoopExpression node) {
- _node = node;
- }
-
- public Expression Body { get { return _node.Body; } }
- public LabelTarget BreakLabel { get { return _node.BreakLabel; } }
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public LabelTarget ContinueLabel { get { return _node.ContinueLabel; } }
- public String DebugView { get { return _node.DebugView; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class MemberExpressionProxy {
- private readonly MemberExpression _node;
-
- public MemberExpressionProxy(MemberExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public Expression Expression { get { return _node.Expression; } }
- public MemberInfo Member { get { return _node.Member; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class MemberInitExpressionProxy {
- private readonly MemberInitExpression _node;
-
- public MemberInitExpressionProxy(MemberInitExpression node) {
- _node = node;
- }
-
- public ReadOnlyCollection<MemberBinding> Bindings { get { return _node.Bindings; } }
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public NewExpression NewExpression { get { return _node.NewExpression; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class MethodCallExpressionProxy {
- private readonly MethodCallExpression _node;
-
- public MethodCallExpressionProxy(MethodCallExpression node) {
- _node = node;
- }
-
- public ReadOnlyCollection<Expression> Arguments { get { return _node.Arguments; } }
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public MethodInfo Method { get { return _node.Method; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Expression Object { get { return _node.Object; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class NewArrayExpressionProxy {
- private readonly NewArrayExpression _node;
-
- public NewArrayExpressionProxy(NewArrayExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public ReadOnlyCollection<Expression> Expressions { get { return _node.Expressions; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class NewExpressionProxy {
- private readonly NewExpression _node;
-
- public NewExpressionProxy(NewExpression node) {
- _node = node;
- }
-
- public ReadOnlyCollection<Expression> Arguments { get { return _node.Arguments; } }
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public ConstructorInfo Constructor { get { return _node.Constructor; } }
- public String DebugView { get { return _node.DebugView; } }
- public ReadOnlyCollection<MemberInfo> Members { get { return _node.Members; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class ParameterExpressionProxy {
- private readonly ParameterExpression _node;
-
- public ParameterExpressionProxy(ParameterExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public Boolean IsByRef { get { return _node.IsByRef; } }
- public String Name { get { return _node.Name; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class RuntimeVariablesExpressionProxy {
- private readonly RuntimeVariablesExpression _node;
-
- public RuntimeVariablesExpressionProxy(RuntimeVariablesExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- public ReadOnlyCollection<ParameterExpression> Variables { get { return _node.Variables; } }
- }
-
- internal class SwitchCaseProxy {
- private readonly SwitchCase _node;
-
- public SwitchCaseProxy(SwitchCase node) {
- _node = node;
- }
-
- public Expression Body { get { return _node.Body; } }
- public ReadOnlyCollection<Expression> TestValues { get { return _node.TestValues; } }
- }
-
- internal class SwitchExpressionProxy {
- private readonly SwitchExpression _node;
-
- public SwitchExpressionProxy(SwitchExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public ReadOnlyCollection<SwitchCase> Cases { get { return _node.Cases; } }
- public MethodInfo Comparison { get { return _node.Comparison; } }
- public String DebugView { get { return _node.DebugView; } }
- public Expression DefaultBody { get { return _node.DefaultBody; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Expression SwitchValue { get { return _node.SwitchValue; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class TryExpressionProxy {
- private readonly TryExpression _node;
-
- public TryExpressionProxy(TryExpression node) {
- _node = node;
- }
-
- public Expression Body { get { return _node.Body; } }
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public Expression Fault { get { return _node.Fault; } }
- public Expression Finally { get { return _node.Finally; } }
- public ReadOnlyCollection<CatchBlock> Handlers { get { return _node.Handlers; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- }
-
- internal class TypeBinaryExpressionProxy {
- private readonly TypeBinaryExpression _node;
-
- public TypeBinaryExpressionProxy(TypeBinaryExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public Expression Expression { get { return _node.Expression; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Type Type { get { return _node.Type; } }
- public Type TypeOperand { get { return _node.TypeOperand; } }
- }
-
- internal class UnaryExpressionProxy {
- private readonly UnaryExpression _node;
-
- public UnaryExpressionProxy(UnaryExpression node) {
- _node = node;
- }
-
- public Boolean CanReduce { get { return _node.CanReduce; } }
- public String DebugView { get { return _node.DebugView; } }
- public Boolean IsLifted { get { return _node.IsLifted; } }
- public Boolean IsLiftedToNull { get { return _node.IsLiftedToNull; } }
- public MethodInfo Method { get { return _node.Method; } }
- public ExpressionType NodeType { get { return _node.NodeType; } }
- public Expression Operand { get { return _node.Operand; } }
- public Type Type { get { return _node.Type; } }
- }
-
- // *** END GENERATED CODE ***
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/Expression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/Expression.cs
deleted file mode 100644
index 21005b217c7..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/Expression.cs
+++ /dev/null
@@ -1,402 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Dynamic.Utils;
-using System.Globalization;
-using System.IO;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Threading;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
- using Microsoft.Scripting.Utils;
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// The base type for all nodes in Expression Trees.
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
- public abstract partial class Expression {
- private delegate LambdaExpression LambdaFactory(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters);
-
- private static readonly CacheDict<Type, MethodInfo> _LambdaDelegateCache = new CacheDict<Type, MethodInfo>(40);
- private static CacheDict<Type, LambdaFactory> _LambdaFactories;
-
- // LINQ protected ctor from 3.5
-
- // needs ConditionWeakTable in 4.0
-
- // For 4.0, many frequently used Expression nodes have had their memory
- // footprint reduced by removing the Type and NodeType fields. This has
- // large performance benefits to all users of Expression Trees.
- //
- // To support the 3.5 protected constructor, we store the fields that
- // used to be here in a ConditionalWeakTable.
-
- private class ExtensionInfo {
- public ExtensionInfo(ExpressionType nodeType, Type type) {
- NodeType = nodeType;
- Type = type;
- }
-
- internal readonly ExpressionType NodeType;
- internal readonly Type Type;
- }
-
- private static ConditionalWeakTable<Expression, ExtensionInfo> _legacyCtorSupportTable;
-
- /// <summary>
- /// Constructs a new instance of <see cref="Expression"/>.
- /// </summary>
- /// <param name="nodeType">The <see ctype="ExpressionType"/> of the <see cref="Expression"/>.</param>
- /// <param name="type">The <see cref="Type"/> of the <see cref="Expression"/>.</param>
- [Obsolete("use a different constructor that does not take ExpressionType. Then override NodeType and Type properties to provide the values that would be specified to this constructor.")]
- protected Expression(ExpressionType nodeType, Type type) {
- // Can't enforce anything that V1 didn't
- if (_legacyCtorSupportTable == null) {
- Interlocked.CompareExchange(
- ref _legacyCtorSupportTable,
- new ConditionalWeakTable<Expression, ExtensionInfo>(),
- null
- );
- }
-
- _legacyCtorSupportTable.Add(this, new ExtensionInfo(nodeType, type));
- }
-
- /// <summary>
- /// Constructs a new instance of <see cref="Expression"/>.
- /// </summary>
- protected Expression() {
- }
-
- /// <summary>
- /// The <see cref="ExpressionType"/> of the <see cref="Expression"/>.
- /// </summary>
- public virtual ExpressionType NodeType {
- get {
- ExtensionInfo extInfo;
- if (_legacyCtorSupportTable != null && _legacyCtorSupportTable.TryGetValue(this, out extInfo)) {
- return extInfo.NodeType;
- }
-
- // the extension expression failed to override NodeType
- throw Error.ExtensionNodeMustOverrideProperty("Expression.NodeType");
- }
- }
-
-
- /// <summary>
- /// The <see cref="Type"/> of the value represented by this <see cref="Expression"/>.
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
- public virtual Type Type {
- get {
- ExtensionInfo extInfo;
- if (_legacyCtorSupportTable != null && _legacyCtorSupportTable.TryGetValue(this, out extInfo)) {
- return extInfo.Type;
- }
-
- // the extension expression failed to override Type
- throw Error.ExtensionNodeMustOverrideProperty("Expression.Type");
- }
- }
-
- /// <summary>
- /// Indicates that the node can be reduced to a simpler node. If this
- /// returns true, Reduce() can be called to produce the reduced form.
- /// </summary>
- public virtual bool CanReduce {
- get { return false; }
- }
-
- /// <summary>
- /// Reduces this node to a simpler expression. If CanReduce returns
- /// true, this should return a valid expression. This method is
- /// allowed to return another node which itself must be reduced.
- /// </summary>
- /// <returns>The reduced expression.</returns>
- public virtual Expression Reduce() {
- if (CanReduce) throw Error.ReducibleMustOverrideReduce();
- return this;
- }
-
- /// <summary>
- /// Reduces the node and then calls the visitor delegate on the reduced expression.
- /// Throws an exception if the node isn't reducible.
- /// </summary>
- /// <param name="visitor">An instance of <see cref="Func{Expression, Expression}"/>.</param>
- /// <returns>The expression being visited, or an expression which should replace it in the tree.</returns>
- /// <remarks>
- /// Override this method to provide logic to walk the node's children.
- /// A typical implementation will call visitor.Visit on each of its
- /// children, and if any of them change, should return a new copy of
- /// itself with the modified children.
- /// </remarks>
- protected internal virtual Expression VisitChildren(ExpressionVisitor visitor) {
- if (!CanReduce) throw Error.MustBeReducible();
- return visitor.Visit(ReduceAndCheck());
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type. For
- /// example, <see cref="MethodCallExpression" /> will call into
- /// <see cref="ExpressionVisitor.VisitMethodCall" />.
- /// </summary>
- /// <param name="visitor">The visitor to visit this node with.</param>
- /// <returns>The result of visiting this node.</returns>
- /// <remarks>
- /// This default implementation for <see cref="ExpressionType.Extension" />
- /// nodes will call <see cref="ExpressionVisitor.VisitExtension" />.
- /// Override this method to call into a more specific method on a derived
- /// visitor class of ExprressionVisitor. However, it should still
- /// support unknown visitors by calling VisitExtension.
- /// </remarks>
- protected internal virtual Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitExtension(this);
- }
-
- /// <summary>
- /// Reduces this node to a simpler expression. If CanReduce returns
- /// true, this should return a valid expression. This method is
- /// allowed to return another node which itself must be reduced.
- /// </summary>
- /// <returns>The reduced expression.</returns>
- /// <remarks >
- /// Unlike Reduce, this method checks that the reduced node satisfies
- /// certain invariants.
- /// </remarks>
- public Expression ReduceAndCheck() {
- if (!CanReduce) throw Error.MustBeReducible();
-
- var newNode = Reduce();
-
- // 1. Reduction must return a new, non-null node
- // 2. Reduction must return a new node whose result type can be assigned to the type of the original node
- if (newNode == null || newNode == this) throw Error.MustReduceToDifferent();
- if (!TypeUtils.AreReferenceAssignable(Type, newNode.Type)) throw Error.ReducedNotCompatible();
- return newNode;
- }
-
- /// <summary>
- /// Reduces the expression to a known node type (i.e. not an Extension node)
- /// or simply returns the expression if it is already a known type.
- /// </summary>
- /// <returns>The reduced expression.</returns>
- public Expression ReduceExtensions() {
- var node = this;
- while (node.NodeType == ExpressionType.Extension) {
- node = node.ReduceAndCheck();
- }
- return node;
- }
-
-
- /// <summary>
- /// Creates a <see cref="String"/> representation of the Expression.
- /// </summary>
- /// <returns>A <see cref="String"/> representation of the Expression.</returns>
- public override string ToString() {
- return ExpressionStringBuilder.ExpressionToString(this);
- }
-
-#if !FEATURE_CORE_DLR
- /// <summary>
- /// Writes a <see cref="String"/> representation of the <see cref="Expression"/> to a <see cref="TextWriter"/>.
- /// </summary>
- /// <param name="writer">A <see cref="TextWriter"/> that will be used to build the string representation.</param>
- public void DumpExpression(TextWriter writer) {
- DebugViewWriter.WriteTo(this, writer);
- }
-
- /// <summary>
- /// Creates a <see cref="String"/> representation of the Expression.
- /// </summary>
- /// <returns>A <see cref="String"/> representation of the Expression.</returns>
- public string DebugView {
-#else
- private string DebugView {
-#endif
- get {
- using (System.IO.StringWriter writer = new System.IO.StringWriter(CultureInfo.CurrentCulture)) {
- DebugViewWriter.WriteTo(this, writer);
- return writer.ToString();
- }
- }
- }
-
- /// <summary>
- /// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T.
- ///
- /// This is called from various methods where we internally hold onto an IList of T
- /// or a readonly collection of T. We check to see if we've already returned a
- /// readonly collection of T and if so simply return the other one. Otherwise we do
- /// a thread-safe replacement of the list w/ a readonly collection which wraps it.
- ///
- /// Ultimately this saves us from having to allocate a ReadOnlyCollection for our
- /// data types because the compiler is capable of going directly to the IList of T.
- /// </summary>
- internal static ReadOnlyCollection<T> ReturnReadOnly<T>(ref IList<T> collection) {
- IList<T> value = collection;
-
- // if it's already read-only just return it.
- ReadOnlyCollection<T> res = value as ReadOnlyCollection<T>;
- if (res != null) {
- return res;
- }
-
- // otherwise make sure only readonly collection every gets exposed
- Interlocked.CompareExchange<IList<T>>(
- ref collection,
- value.ToReadOnly(),
- value
- );
-
- // and return it
- return (ReadOnlyCollection<T>)collection;
- }
-
- /// <summary>
- /// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T.
- ///
- /// This is similar to the ReturnReadOnly of T. This version supports nodes which hold
- /// onto multiple Expressions where one is typed to object. That object field holds either
- /// an expression or a ReadOnlyCollection of Expressions. When it holds a ReadOnlyCollection
- /// the IList which backs it is a ListArgumentProvider which uses the Expression which
- /// implements IArgumentProvider to get 2nd and additional values. The ListArgumentProvider
- /// continues to hold onto the 1st expression.
- ///
- /// This enables users to get the ReadOnlyCollection w/o it consuming more memory than if
- /// it was just an array. Meanwhile The DLR internally avoids accessing which would force
- /// the readonly collection to be created resulting in a typical memory savings.
- /// </summary>
- internal static ReadOnlyCollection<Expression> ReturnReadOnly(IArgumentProvider provider, ref object collection) {
- Expression tObj = collection as Expression;
- if (tObj != null) {
- // otherwise make sure only one readonly collection ever gets exposed
- Interlocked.CompareExchange(
- ref collection,
- new ReadOnlyCollection<Expression>(new ListArgumentProvider(provider, tObj)),
- tObj
- );
- }
-
- // and return what is not guaranteed to be a readonly collection
- return (ReadOnlyCollection<Expression>)collection;
- }
-
- /// <summary>
- /// Helper which is used for specialized subtypes which use ReturnReadOnly(ref object, ...).
- /// This is the reverse version of ReturnReadOnly which takes an IArgumentProvider.
- ///
- /// This is used to return the 1st argument. The 1st argument is typed as object and either
- /// contains a ReadOnlyCollection or the Expression. We check for the Expression and if it's
- /// present we return that, otherwise we return the 1st element of the ReadOnlyCollection.
- /// </summary>
- internal static T ReturnObject<T>(object collectionOrT) where T : class {
- T t = collectionOrT as T;
- if (t != null) {
- return t;
- }
-
- return ((ReadOnlyCollection<T>)collectionOrT)[0];
- }
-
- private static void RequiresCanRead(Expression expression, string paramName) {
- if (expression == null) {
- throw new ArgumentNullException(paramName);
- }
-
- // validate that we can read the node
- switch (expression.NodeType) {
- case ExpressionType.Index:
- IndexExpression index = (IndexExpression)expression;
- if (index.Indexer != null && !index.Indexer.CanRead) {
- throw new ArgumentException(Strings.ExpressionMustBeReadable, paramName);
- }
- break;
- case ExpressionType.MemberAccess:
- MemberExpression member = (MemberExpression)expression;
- MemberInfo memberInfo = member.Member;
- if (memberInfo.MemberType == MemberTypes.Property) {
- PropertyInfo prop = (PropertyInfo)memberInfo;
- if (!prop.CanRead) {
- throw new ArgumentException(Strings.ExpressionMustBeReadable, paramName);
- }
- }
- break;
- }
- }
-
- private static void RequiresCanRead(IEnumerable<Expression> items, string paramName) {
- if (items != null) {
- // this is called a lot, avoid allocating an enumerator if we can...
- IList<Expression> listItems = items as IList<Expression>;
- if (listItems != null) {
- for (int i = 0; i < listItems.Count; i++) {
- RequiresCanRead(listItems[i], paramName);
- }
- return;
- }
-
- foreach (var i in items) {
- RequiresCanRead(i, paramName);
- }
- }
- }
- private static void RequiresCanWrite(Expression expression, string paramName) {
- if (expression == null) {
- throw new ArgumentNullException(paramName);
- }
-
- bool canWrite = false;
- switch (expression.NodeType) {
- case ExpressionType.Index:
- IndexExpression index = (IndexExpression)expression;
- if (index.Indexer != null) {
- canWrite = index.Indexer.CanWrite;
- } else {
- canWrite = true;
- }
- break;
- case ExpressionType.MemberAccess:
- MemberExpression member = (MemberExpression)expression;
- switch (member.Member.MemberType) {
- case MemberTypes.Property:
- PropertyInfo prop = (PropertyInfo)member.Member;
- canWrite = prop.CanWrite;
- break;
- case MemberTypes.Field:
- FieldInfo field = (FieldInfo)member.Member;
- canWrite = !(field.IsInitOnly || field.IsLiteral);
- break;
- }
- break;
- case ExpressionType.Parameter:
- canWrite = true;
- break;
- }
-
- if (!canWrite) {
- throw new ArgumentException(Strings.ExpressionMustBeWriteable, paramName);
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionStringBuilder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionStringBuilder.cs
deleted file mode 100644
index abfd257c385..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionStringBuilder.cs
+++ /dev/null
@@ -1,759 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Dynamic;
-using System.Dynamic.Utils;
-using System.Globalization;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Text;
-using Microsoft.Scripting.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
- internal sealed class ExpressionStringBuilder : ExpressionVisitor {
- private StringBuilder _out;
-
- // Associate every unique label or anonymous parameter in the tree with an integer.
- // The label is displayed as Label_#.
- private Dictionary<object, int> _ids;
-
- private ExpressionStringBuilder() {
- _out = new StringBuilder();
- }
-
- public override string ToString() {
- return _out.ToString();
- }
-
- private void AddLabel(LabelTarget label) {
- if (_ids == null) {
- _ids = new Dictionary<object, int>();
- _ids.Add(label, 0);
- } else {
- if (!_ids.ContainsKey(label)) {
- _ids.Add(label, _ids.Count);
- }
- }
- }
-
- private int GetLabelId(LabelTarget label) {
- if (_ids == null) {
- _ids = new Dictionary<object, int>();
- AddLabel(label);
- return 0;
- } else {
- int id;
- if (!_ids.TryGetValue(label, out id)) {
- //label is met the first time
- id = _ids.Count;
- AddLabel(label);
- }
- return id;
- }
- }
-
- private void AddParam(ParameterExpression p) {
- if (_ids == null) {
- _ids = new Dictionary<object, int>();
- _ids.Add(_ids, 0);
- } else {
- if (!_ids.ContainsKey(p)) {
- _ids.Add(p, _ids.Count);
- }
- }
- }
-
- private int GetParamId(ParameterExpression p) {
- if (_ids == null) {
- _ids = new Dictionary<object, int>();
- AddParam(p);
- return 0;
- } else {
- int id;
- if (!_ids.TryGetValue(p, out id)) {
- // p is met the first time
- id = _ids.Count;
- AddParam(p);
- }
- return id;
- }
- }
-
- #region The printing code
-
- private void Out(string s) {
- _out.Append(s);
- }
-
- private void Out(char c) {
- _out.Append(c);
- }
-
- #endregion
-
- #region Output an expresstion tree to a string
-
- /// <summary>
- /// Output a given expression tree to a string.
- /// </summary>
- internal static string ExpressionToString(Expression node) {
- Debug.Assert(node != null);
- ExpressionStringBuilder esb = new ExpressionStringBuilder();
- esb.Visit(node);
- return esb.ToString();
- }
-
- internal static string CatchBlockToString(CatchBlock node) {
- Debug.Assert(node != null);
- ExpressionStringBuilder esb = new ExpressionStringBuilder();
- esb.VisitCatchBlock(node);
- return esb.ToString();
- }
-
- internal static string SwitchCaseToString(SwitchCase node) {
- Debug.Assert(node != null);
- ExpressionStringBuilder esb = new ExpressionStringBuilder();
- esb.VisitSwitchCase(node);
- return esb.ToString();
- }
-
- /// <summary>
- /// Output a given member binding to a string.
- /// </summary>
- internal static string MemberBindingToString(MemberBinding node) {
- Debug.Assert(node != null);
- ExpressionStringBuilder esb = new ExpressionStringBuilder();
- esb.VisitMemberBinding(node);
- return esb.ToString();
- }
-
- /// <summary>
- /// Output a given ElementInit to a string.
- /// </summary>
- internal static string ElementInitBindingToString(ElementInit node) {
- Debug.Assert(node != null);
- ExpressionStringBuilder esb = new ExpressionStringBuilder();
- esb.VisitElementInit(node);
- return esb.ToString();
- }
-
- // More proper would be to make this a virtual method on Action
- private static string FormatBinder(CallSiteBinder binder) {
- ConvertBinder convert;
- GetMemberBinder getMember;
- SetMemberBinder setMember;
- DeleteMemberBinder deleteMember;
- InvokeMemberBinder call;
- UnaryOperationBinder unary;
- BinaryOperationBinder binary;
-
- if ((convert = binder as ConvertBinder) != null) {
- return "Convert " + convert.Type;
- } else if ((getMember = binder as GetMemberBinder) != null) {
- return "GetMember " + getMember.Name;
- } else if ((setMember = binder as SetMemberBinder) != null) {
- return "SetMember " + setMember.Name;
- } else if ((deleteMember = binder as DeleteMemberBinder) != null) {
- return "DeleteMember " + deleteMember.Name;
- } else if (binder is GetIndexBinder) {
- return "GetIndex";
- } else if (binder is SetIndexBinder) {
- return "SetIndex";
- } else if (binder is DeleteIndexBinder) {
- return "DeleteIndex";
- } else if ((call = binder as InvokeMemberBinder) != null) {
- return "Call " + call.Name;
- } else if (binder is InvokeBinder) {
- return "Invoke";
- } else if (binder is CreateInstanceBinder) {
- return "Create";
- } else if ((unary = binder as UnaryOperationBinder) != null) {
- return unary.Operation.ToString();
- } else if ((binary = binder as BinaryOperationBinder) != null) {
- return binary.Operation.ToString();
- } else {
- return "CallSiteBinder";
- }
- }
-
- private void VisitExpressions<T>(char open, IList<T> expressions, char close) where T : Expression {
- VisitExpressions(open, expressions, close, ", ");
- }
-
- private void VisitExpressions<T>(char open, IList<T> expressions, char close, string seperator) where T : Expression {
- Out(open);
- if (expressions != null) {
- bool isFirst = true;
- foreach (T e in expressions) {
- if (isFirst) {
- isFirst = false;
- } else {
- Out(seperator);
- }
- Visit(e);
- }
- }
- Out(close);
- }
-
- protected internal override Expression VisitDynamic(DynamicExpression node) {
- Out(FormatBinder(node.Binder));
- VisitExpressions('(', node.Arguments, ')');
- return node;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- protected internal override Expression VisitBinary(BinaryExpression node) {
- if (node.NodeType == ExpressionType.ArrayIndex) {
- Visit(node.Left);
- Out("[");
- Visit(node.Right);
- Out("]");
- } else {
- string op;
- switch (node.NodeType) {
- // AndAlso and OrElse were unintentionally changed in
- // CLR 4. We changed them to "AndAlso" and "OrElse" to
- // be 3.5 compatible, but it turns out 3.5 shipped with
- // "&&" and "||". Oops.
- case ExpressionType.AndAlso:
- op = "AndAlso";
- break;
- case ExpressionType.OrElse:
- op = "OrElse";
- break;
- case ExpressionType.Assign: op = "="; break;
- case ExpressionType.Equal:
- op = "==";
- break;
- case ExpressionType.NotEqual: op = "!="; break;
- case ExpressionType.GreaterThan: op = ">"; break;
- case ExpressionType.LessThan: op = "<"; break;
- case ExpressionType.GreaterThanOrEqual: op = ">="; break;
- case ExpressionType.LessThanOrEqual: op = "<="; break;
- case ExpressionType.Add: op = "+"; break;
- case ExpressionType.AddAssign: op = "+="; break;
- case ExpressionType.AddAssignChecked: op = "+="; break;
- case ExpressionType.AddChecked: op = "+"; break;
- case ExpressionType.Subtract: op = "-"; break;
- case ExpressionType.SubtractAssign: op = "-="; break;
- case ExpressionType.SubtractAssignChecked: op = "-="; break;
- case ExpressionType.SubtractChecked: op = "-"; break;
- case ExpressionType.Divide: op = "/"; break;
- case ExpressionType.DivideAssign: op = "/="; break;
- case ExpressionType.Modulo: op = "%"; break;
- case ExpressionType.ModuloAssign: op = "%="; break;
- case ExpressionType.Multiply: op = "*"; break;
- case ExpressionType.MultiplyAssign: op = "*="; break;
- case ExpressionType.MultiplyAssignChecked: op = "*="; break;
- case ExpressionType.MultiplyChecked: op = "*"; break;
- case ExpressionType.LeftShift: op = "<<"; break;
- case ExpressionType.LeftShiftAssign: op = "<<="; break;
- case ExpressionType.RightShift: op = ">>"; break;
- case ExpressionType.RightShiftAssign: op = ">>="; break;
- case ExpressionType.And:
- if (node.Type == typeof(bool) || node.Type == typeof(bool?)) {
- op = "And";
- } else {
- op = "&";
- }
- break;
- case ExpressionType.AndAssign:
- if (node.Type == typeof(bool) || node.Type == typeof(bool?)) {
- op = "&&=";
- } else {
- op = "&=";
- }
- break;
- case ExpressionType.Or:
- if (node.Type == typeof(bool) || node.Type == typeof(bool?)) {
- op = "Or";
- } else {
- op = "|";
- }
- break;
- case ExpressionType.OrAssign:
- if (node.Type == typeof(bool) || node.Type == typeof(bool?)) {
- op = "||=";
- } else { op = "|="; }
- break;
- case ExpressionType.ExclusiveOr: op = "^"; break;
- case ExpressionType.ExclusiveOrAssign: op = "^="; break;
- case ExpressionType.Power: op = "^"; break;
- case ExpressionType.PowerAssign: op = "**="; break;
- case ExpressionType.Coalesce: op = "??"; break;
-
- default:
- throw new InvalidOperationException();
- }
- Out("(");
- Visit(node.Left);
- Out(' ');
- Out(op);
- Out(' ');
- Visit(node.Right);
- Out(")");
- }
- return node;
- }
-
- protected internal override Expression VisitParameter(ParameterExpression node) {
- if (node.IsByRef) {
- Out("ref ");
- }
- string name = node.Name;
- if (String.IsNullOrEmpty(name)) {
- Out("Param_" + GetParamId(node));
- } else {
- Out(name);
- }
- return node;
- }
-
- protected internal override Expression VisitLambda<T>(Expression<T> node) {
- if (node.Parameters.Count == 1) {
- // p => body
- Visit(node.Parameters[0]);
- } else {
- // (p1, p2, ..., pn) => body
- VisitExpressions('(', node.Parameters, ')');
- }
- Out(" => ");
- Visit(node.Body);
- return node;
- }
-
- protected internal override Expression VisitListInit(ListInitExpression node) {
- Visit(node.NewExpression);
- Out(" {");
- for (int i = 0, n = node.Initializers.Count; i < n; i++) {
- if (i > 0) {
- Out(", ");
- }
- Out(node.Initializers[i].ToString());
- }
- Out("}");
- return node;
- }
-
- protected internal override Expression VisitConditional(ConditionalExpression node) {
- Out("IIF(");
- Visit(node.Test);
- Out(", ");
- Visit(node.IfTrue);
- Out(", ");
- Visit(node.IfFalse);
- Out(")");
- return node;
- }
-
- protected internal override Expression VisitConstant(ConstantExpression node) {
- if (node.Value != null) {
- string sValue = node.Value.ToString();
- if (node.Value is string) {
- Out("\"");
- Out(sValue);
- Out("\"");
- } else if (sValue == node.Value.GetType().ToString()) {
- Out("value(");
- Out(sValue);
- Out(")");
- } else {
- Out(sValue);
- }
- } else {
- Out("null");
- }
- return node;
- }
-
- protected internal override Expression VisitDebugInfo(DebugInfoExpression node) {
- string s = String.Format(
- CultureInfo.CurrentCulture,
- "<DebugInfo({0}: {1}, {2}, {3}, {4})>",
- node.Document.FileName,
- node.StartLine,
- node.StartColumn,
- node.EndLine,
- node.EndColumn
- );
- Out(s);
- return node;
- }
-
- protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) {
- VisitExpressions('(', node.Variables, ')');
- return node;
- }
-
- // Prints ".instanceField" or "declaringType.staticField"
- private void OutMember(Expression instance, MemberInfo member) {
- if (instance != null) {
- Visit(instance);
- Out("." + member.Name);
- } else {
- // For static members, include the type name
- Out(member.DeclaringType.Name + "." + member.Name);
- }
- }
-
- protected internal override Expression VisitMember(MemberExpression node) {
- OutMember(node.Expression, node.Member);
- return node;
- }
-
- protected internal override Expression VisitMemberInit(MemberInitExpression node) {
- if (node.NewExpression.Arguments.Count == 0 &&
- node.NewExpression.Type.Name.Contains("<")) {
- // anonymous type constructor
- Out("new");
- } else {
- Visit(node.NewExpression);
- }
- Out(" {");
- for (int i = 0, n = node.Bindings.Count; i < n; i++) {
- MemberBinding b = node.Bindings[i];
- if (i > 0) {
- Out(", ");
- }
- VisitMemberBinding(b);
- }
- Out("}");
- return node;
- }
-
- protected override MemberAssignment VisitMemberAssignment(MemberAssignment assignment) {
- Out(assignment.Member.Name);
- Out(" = ");
- Visit(assignment.Expression);
- return assignment;
- }
-
- protected override MemberListBinding VisitMemberListBinding(MemberListBinding binding) {
- Out(binding.Member.Name);
- Out(" = {");
- for (int i = 0, n = binding.Initializers.Count; i < n; i++) {
- if (i > 0) {
- Out(", ");
- }
- VisitElementInit(binding.Initializers[i]);
- }
- Out("}");
- return binding;
- }
-
- protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) {
- Out(binding.Member.Name);
- Out(" = {");
- for (int i = 0, n = binding.Bindings.Count; i < n; i++) {
- if (i > 0) {
- Out(", ");
- }
- VisitMemberBinding(binding.Bindings[i]);
- }
- Out("}");
- return binding;
- }
-
- protected override ElementInit VisitElementInit(ElementInit initializer) {
- Out(initializer.AddMethod.ToString());
- string sep = ", ";
- VisitExpressions('(', initializer.Arguments, ')', sep);
- return initializer;
- }
-
- protected internal override Expression VisitInvocation(InvocationExpression node) {
- Out("Invoke(");
- Visit(node.Expression);
- string sep = ", ";
- for (int i = 0, n = node.Arguments.Count; i < n; i++) {
- Out(sep);
- Visit(node.Arguments[i]);
- }
- Out(")");
- return node;
- }
-
- protected internal override Expression VisitMethodCall(MethodCallExpression node) {
- int start = 0;
- Expression ob = node.Object;
-
- if (Attribute.GetCustomAttribute(node.Method, typeof(ExtensionAttribute)) != null) {
- start = 1;
- ob = node.Arguments[0];
- }
-
- if (ob != null) {
- Visit(ob);
- Out(".");
- }
- Out(node.Method.Name);
- Out("(");
- for (int i = start, n = node.Arguments.Count; i < n; i++) {
- if (i > start)
- Out(", ");
- Visit(node.Arguments[i]);
- }
- Out(")");
- return node;
- }
-
- protected internal override Expression VisitNewArray(NewArrayExpression node) {
- switch (node.NodeType) {
- case ExpressionType.NewArrayBounds:
- // new MyType[](expr1, expr2)
- Out("new " + node.Type.ToString());
- VisitExpressions('(', node.Expressions, ')');
- break;
- case ExpressionType.NewArrayInit:
- // new [] {expr1, expr2}
- Out("new [] ");
- VisitExpressions('{', node.Expressions, '}');
- break;
- }
- return node;
- }
-
- protected internal override Expression VisitNew(NewExpression node) {
- Out("new " + node.Type.Name);
- Out("(");
- var members = node.Members;
- for (int i = 0; i < node.Arguments.Count; i++) {
- if (i > 0) {
- Out(", ");
- }
- if (members != null) {
- string name = members[i].Name;
- Out(name);
- Out(" = ");
- }
- Visit(node.Arguments[i]);
- }
- Out(")");
- return node;
- }
-
- protected internal override Expression VisitTypeBinary(TypeBinaryExpression node) {
- Out("(");
- Visit(node.Expression);
- switch (node.NodeType) {
- case ExpressionType.TypeIs:
- Out(" Is ");
- break;
- case ExpressionType.TypeEqual:
- Out(" TypeEqual ");
- break;
- }
- Out(node.TypeOperand.Name);
- Out(")");
- return node;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- protected internal override Expression VisitUnary(UnaryExpression node) {
- switch (node.NodeType) {
- case ExpressionType.TypeAs:
- Out("(");
- break;
- case ExpressionType.Not:
- Out("Not(");
- break;
- case ExpressionType.Negate:
- case ExpressionType.NegateChecked:
- Out("-");
- break;
- case ExpressionType.UnaryPlus:
- Out("+");
- break;
- case ExpressionType.Quote:
- break;
- case ExpressionType.Throw:
- Out("throw(");
- break;
- case ExpressionType.Increment:
- Out("Increment(");
- break;
- case ExpressionType.Decrement:
- Out("Decrement(");
- break;
- case ExpressionType.PreIncrementAssign:
- Out("++");
- break;
- case ExpressionType.PreDecrementAssign:
- Out("--");
- break;
- case ExpressionType.OnesComplement:
- Out("~(");
- break;
- default:
- Out(node.NodeType.ToString());
- Out("(");
- break;
- }
-
- Visit(node.Operand);
-
- switch (node.NodeType) {
- case ExpressionType.Negate:
- case ExpressionType.NegateChecked:
- case ExpressionType.UnaryPlus:
- case ExpressionType.PreDecrementAssign:
- case ExpressionType.PreIncrementAssign:
- case ExpressionType.Quote:
- break;
- case ExpressionType.TypeAs:
- Out(" As ");
- Out(node.Type.Name);
- Out(")");
- break;
- case ExpressionType.PostIncrementAssign:
- Out("++");
- break;
- case ExpressionType.PostDecrementAssign:
- Out("--");
- break;
- default:
- Out(")");
- break;
- }
- return node;
- }
-
- protected internal override Expression VisitBlock(BlockExpression node) {
- Out("{");
- foreach (var v in node.Variables) {
- Out("var ");
- Visit(v);
- Out(";");
- }
- Out(" ... }");
- return node;
- }
-
- protected internal override Expression VisitDefault(DefaultExpression node) {
- Out("default(");
- Out(node.Type.Name);
- Out(")");
- return node;
- }
-
- protected internal override Expression VisitLabel(LabelExpression node) {
- Out("{ ... } ");
- DumpLabel(node.Target);
- Out(":");
- return node;
- }
-
- protected internal override Expression VisitGoto(GotoExpression node) {
- Out(node.Kind.ToString().ToLower(CultureInfo.CurrentCulture));
- DumpLabel(node.Target);
- if (node.Value != null) {
- Out(" (");
- Visit(node.Value);
- Out(") ");
- }
- return node;
- }
-
- protected internal override Expression VisitLoop(LoopExpression node) {
- Out("loop { ... }");
- return node;
- }
-
- protected override SwitchCase VisitSwitchCase(SwitchCase node) {
- Out("case ");
- VisitExpressions('(', node.TestValues, ')');
- Out(": ...");
- return node;
- }
-
- protected internal override Expression VisitSwitch(SwitchExpression node) {
- Out("switch ");
- Out("(");
- Visit(node.SwitchValue);
- Out(") { ... }");
- return node;
- }
-
- protected override CatchBlock VisitCatchBlock(CatchBlock node) {
- Out("catch (" + node.Test.Name);
- if (node.Variable != null) {
- Out(node.Variable.Name ?? "");
- }
- Out(") { ... }");
- return node;
- }
-
- protected internal override Expression VisitTry(TryExpression node) {
- Out("try { ... }");
- return node;
- }
-
- protected internal override Expression VisitIndex(IndexExpression node) {
- if (node.Object != null) {
- Visit(node.Object);
- } else {
- Debug.Assert(node.Indexer != null);
- Out(node.Indexer.DeclaringType.Name);
- }
- if (node.Indexer != null) {
- Out(".");
- Out(node.Indexer.Name);
- }
-
- VisitExpressions('[', node.Arguments, ']');
- return node;
- }
-
- protected internal override Expression VisitExtension(Expression node) {
- // Prefer an overriden ToString, if available.
- var flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.ExactBinding;
- var toString = node.GetType().GetMethod("ToString", flags, null, ReflectionUtils.EmptyTypes, null);
- if (toString.DeclaringType != typeof(Expression)) {
- Out(node.ToString());
- return node;
- }
-
- Out("[");
- // For 3.5 subclasses, print the NodeType.
- // For Extension nodes, print the class name.
- if (node.NodeType == ExpressionType.Extension) {
- Out(node.GetType().FullName);
- } else {
- Out(node.NodeType.ToString());
- }
- Out("]");
- return node;
- }
-
- private void DumpLabel(LabelTarget target) {
- if (!String.IsNullOrEmpty(target.Name)) {
- Out(target.Name);
- } else {
- int labelId = GetLabelId(target);
- Out("UnamedLabel_" + labelId);
- }
- }
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionType.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionType.cs
deleted file mode 100644
index 1e3e64cbaa5..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionType.cs
+++ /dev/null
@@ -1,377 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- /// <summary>
- /// Describes the node types for the nodes of an expression tree.
- /// </summary>
- public enum ExpressionType {
-
- #region Generated Expression Tree Node Types
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_tree_nodes from: generate_tree.py
-
- /// <summary>
- /// A node that represents arithmetic addition without overflow checking.
- /// </summary>
- Add,
- /// <summary>
- /// A node that represents arithmetic addition with overflow checking.
- /// </summary>
- AddChecked,
- /// <summary>
- /// A node that represents a bitwise AND operation.
- /// </summary>
- And,
- /// <summary>
- /// A node that represents a short-circuiting conditional AND operation.
- /// </summary>
- AndAlso,
- /// <summary>
- /// A node that represents getting the length of a one-dimensional array.
- /// </summary>
- ArrayLength,
- /// <summary>
- /// A node that represents indexing into a one-dimensional array.
- /// </summary>
- ArrayIndex,
- /// <summary>
- /// A node that represents represents a method call.
- /// </summary>
- Call,
- /// <summary>
- /// A node that represents a null coalescing operation.
- /// </summary>
- Coalesce,
- /// <summary>
- /// A node that represents a conditional operation.
- /// </summary>
- Conditional,
- /// <summary>
- /// A node that represents an expression that has a constant value.
- /// </summary>
- Constant,
- /// <summary>
- /// A node that represents a cast or conversion operation. If the operation is a numeric conversion, it overflows silently if the converted value does not fit the target type.
- /// </summary>
- Convert,
- /// <summary>
- /// A node that represents a cast or conversion operation. If the operation is a numeric conversion, an exception is thrown if the converted value does not fit the target type.
- /// </summary>
- ConvertChecked,
- /// <summary>
- /// A node that represents arithmetic division.
- /// </summary>
- Divide,
- /// <summary>
- /// A node that represents an equality comparison.
- /// </summary>
- Equal,
- /// <summary>
- /// A node that represents a bitwise XOR operation.
- /// </summary>
- ExclusiveOr,
- /// <summary>
- /// A node that represents a "greater than" numeric comparison.
- /// </summary>
- GreaterThan,
- /// <summary>
- /// A node that represents a "greater than or equal" numeric comparison.
- /// </summary>
- GreaterThanOrEqual,
- /// <summary>
- /// A node that represents applying a delegate or lambda expression to a list of argument expressions.
- /// </summary>
- Invoke,
- /// <summary>
- /// A node that represents a lambda expression.
- /// </summary>
- Lambda,
- /// <summary>
- /// A node that represents a bitwise left-shift operation.
- /// </summary>
- LeftShift,
- /// <summary>
- /// A node that represents a "less than" numeric comparison.
- /// </summary>
- LessThan,
- /// <summary>
- /// A node that represents a "less than or equal" numeric comparison.
- /// </summary>
- LessThanOrEqual,
- /// <summary>
- /// A node that represents creating a new IEnumerable object and initializing it from a list of elements.
- /// </summary>
- ListInit,
- /// <summary>
- /// A node that represents reading from a field or property.
- /// </summary>
- MemberAccess,
- /// <summary>
- /// A node that represents creating a new object and initializing one or more of its members.
- /// </summary>
- MemberInit,
- /// <summary>
- /// A node that represents an arithmetic remainder operation.
- /// </summary>
- Modulo,
- /// <summary>
- /// A node that represents arithmetic multiplication without overflow checking.
- /// </summary>
- Multiply,
- /// <summary>
- /// A node that represents arithmetic multiplication with overflow checking.
- /// </summary>
- MultiplyChecked,
- /// <summary>
- /// A node that represents an arithmetic negation operation.
- /// </summary>
- Negate,
- /// <summary>
- /// A node that represents a unary plus operation. The result of a predefined unary plus operation is simply the value of the operand, but user-defined implementations may have non-trivial results.
- /// </summary>
- UnaryPlus,
- /// <summary>
- /// A node that represents an arithmetic negation operation that has overflow checking.
- /// </summary>
- NegateChecked,
- /// <summary>
- /// A node that represents calling a constructor to create a new object.
- /// </summary>
- New,
- /// <summary>
- /// A node that represents creating a new one-dimensional array and initializing it from a list of elements.
- /// </summary>
- NewArrayInit,
- /// <summary>
- /// A node that represents creating a new array where the bounds for each dimension are specified.
- /// </summary>
- NewArrayBounds,
- /// <summary>
- /// A node that represents a bitwise complement operation.
- /// </summary>
- Not,
- /// <summary>
- /// A node that represents an inequality comparison.
- /// </summary>
- NotEqual,
- /// <summary>
- /// A node that represents a bitwise OR operation.
- /// </summary>
- Or,
- /// <summary>
- /// A node that represents a short-circuiting conditional OR operation.
- /// </summary>
- OrElse,
- /// <summary>
- /// A node that represents a reference to a parameter or variable defined in the context of the expression.
- /// </summary>
- Parameter,
- /// <summary>
- /// A node that represents raising a number to a power.
- /// </summary>
- Power,
- /// <summary>
- /// A node that represents an expression that has a constant value of type Expression. A Quote node can contain references to parameters defined in the context of the expression it represents.
- /// </summary>
- Quote,
- /// <summary>
- /// A node that represents a bitwise right-shift operation.
- /// </summary>
- RightShift,
- /// <summary>
- /// A node that represents arithmetic subtraction without overflow checking.
- /// </summary>
- Subtract,
- /// <summary>
- /// A node that represents arithmetic subtraction with overflow checking.
- /// </summary>
- SubtractChecked,
- /// <summary>
- /// A node that represents an explicit reference or boxing conversion where null reference (Nothing in Visual Basic) is supplied if the conversion fails.
- /// </summary>
- TypeAs,
- /// <summary>
- /// A node that represents a type test.
- /// </summary>
- TypeIs,
- /// <summary>
- /// A node that represents an assignment.
- /// </summary>
- Assign,
- /// <summary>
- /// A node that represents a block of expressions.
- /// </summary>
- Block,
- /// <summary>
- /// A node that represents a debugging information.
- /// </summary>
- DebugInfo,
- /// <summary>
- /// A node that represents a unary decrement.
- /// </summary>
- Decrement,
- /// <summary>
- /// A node that represents a dynamic operation.
- /// </summary>
- Dynamic,
- /// <summary>
- /// A node that represents a default value.
- /// </summary>
- Default,
- /// <summary>
- /// A node that represents an extension expression.
- /// </summary>
- Extension,
- /// <summary>
- /// A node that represents a goto.
- /// </summary>
- Goto,
- /// <summary>
- /// A node that represents a unary increment.
- /// </summary>
- Increment,
- /// <summary>
- /// A node that represents an index operation.
- /// </summary>
- Index,
- /// <summary>
- /// A node that represents a label.
- /// </summary>
- Label,
- /// <summary>
- /// A node that represents a list of runtime variables.
- /// </summary>
- RuntimeVariables,
- /// <summary>
- /// A node that represents a loop.
- /// </summary>
- Loop,
- /// <summary>
- /// A node that represents a switch operation.
- /// </summary>
- Switch,
- /// <summary>
- /// A node that represents a throwing of an exception.
- /// </summary>
- Throw,
- /// <summary>
- /// A node that represents a try-catch expression.
- /// </summary>
- Try,
- /// <summary>
- /// A node that represents an unbox value type operation.
- /// </summary>
- Unbox,
- /// <summary>
- /// A node that represents an arithmetic addition compound assignment without overflow checking.
- /// </summary>
- AddAssign,
- /// <summary>
- /// A node that represents a bitwise AND compound assignment.
- /// </summary>
- AndAssign,
- /// <summary>
- /// A node that represents an arithmetic division compound assignment .
- /// </summary>
- DivideAssign,
- /// <summary>
- /// A node that represents a bitwise XOR compound assignment.
- /// </summary>
- ExclusiveOrAssign,
- /// <summary>
- /// A node that represents a bitwise left-shift compound assignment.
- /// </summary>
- LeftShiftAssign,
- /// <summary>
- /// A node that represents an arithmetic remainder compound assignment.
- /// </summary>
- ModuloAssign,
- /// <summary>
- /// A node that represents arithmetic multiplication compound assignment without overflow checking.
- /// </summary>
- MultiplyAssign,
- /// <summary>
- /// A node that represents a bitwise OR compound assignment.
- /// </summary>
- OrAssign,
- /// <summary>
- /// A node that represents raising a number to a power compound assignment.
- /// </summary>
- PowerAssign,
- /// <summary>
- /// A node that represents a bitwise right-shift compound assignment.
- /// </summary>
- RightShiftAssign,
- /// <summary>
- /// A node that represents arithmetic subtraction compound assignment without overflow checking.
- /// </summary>
- SubtractAssign,
- /// <summary>
- /// A node that represents an arithmetic addition compound assignment with overflow checking.
- /// </summary>
- AddAssignChecked,
- /// <summary>
- /// A node that represents arithmetic multiplication compound assignment with overflow checking.
- /// </summary>
- MultiplyAssignChecked,
- /// <summary>
- /// A node that represents arithmetic subtraction compound assignment with overflow checking.
- /// </summary>
- SubtractAssignChecked,
- /// <summary>
- /// A node that represents an unary prefix increment.
- /// </summary>
- PreIncrementAssign,
- /// <summary>
- /// A node that represents an unary prefix decrement.
- /// </summary>
- PreDecrementAssign,
- /// <summary>
- /// A node that represents an unary postfix increment.
- /// </summary>
- PostIncrementAssign,
- /// <summary>
- /// A node that represents an unary postfix decrement.
- /// </summary>
- PostDecrementAssign,
- /// <summary>
- /// A node that represents a exact type test.
- /// </summary>
- TypeEqual,
- /// <summary>
- /// A node that represents a ones complement.
- /// </summary>
- OnesComplement,
- /// <summary>
- /// A node that represents a true condition value.
- /// </summary>
- IsTrue,
- /// <summary>
- /// A node that represents a false condition value.
- /// </summary>
- IsFalse,
-
- // *** END GENERATED CODE ***
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionVisitor.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionVisitor.cs
deleted file mode 100644
index 07c1201ddeb..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionVisitor.cs
+++ /dev/null
@@ -1,679 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
- using Microsoft.Scripting.Utils;
-#else
-namespace System.Linq.Expressions {
-#endif
-
- /// <summary>
- /// Represents a visitor or rewriter for expression trees.
- /// </summary>
- /// <remarks>
- /// This class is designed to be inherited to create more specialized
- /// classes whose functionality requires traversing, examining or copying
- /// an expression tree.
- /// </remarks>
- public abstract class ExpressionVisitor {
-
- /// <summary>
- /// Initializes a new instance of <see cref="ExpressionVisitor"/>.
- /// </summary>
- protected ExpressionVisitor() {
- }
-
- /// <summary>
- /// Dispatches the expression to one of the more specialized visit methods in this class.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- public virtual Expression Visit(Expression node) {
- if (node != null) {
- return node.Accept(this);
- }
- return null;
- }
-
- /// <summary>
- /// Dispatches the list of expressions to one of the more specialized visit methods in this class.
- /// </summary>
- /// <param name="nodes">The expressions to visit.</param>
- /// <returns>The modified expression list, if any of the elements were modified;
- /// otherwise, returns the original expression list.</returns>
- public ReadOnlyCollection<Expression> Visit(ReadOnlyCollection<Expression> nodes) {
- Expression[] newNodes = null;
- for (int i = 0, n = nodes.Count; i < n; i++) {
- Expression node = Visit(nodes[i]);
-
- if (newNodes != null) {
- newNodes[i] = node;
- } else if (!object.ReferenceEquals(node, nodes[i])) {
- newNodes = new Expression[n];
- for (int j = 0; j < i; j++) {
- newNodes[j] = nodes[j];
- }
- newNodes[i] = node;
- }
- }
- if (newNodes == null) {
- return nodes;
- }
- return new TrueReadOnlyCollection<Expression>(newNodes);
- }
-
- internal Expression[] VisitArguments(IArgumentProvider nodes) {
- Expression[] newNodes = null;
- for (int i = 0, n = nodes.ArgumentCount; i < n; i++) {
- Expression curNode = nodes.GetArgument(i);
- Expression node = Visit(curNode);
-
- if (newNodes != null) {
- newNodes[i] = node;
- } else if (!object.ReferenceEquals(node, curNode)) {
- newNodes = new Expression[n];
- for (int j = 0; j < i; j++) {
- newNodes[j] = nodes.GetArgument(j);
- }
- newNodes[i] = node;
- }
- }
- return newNodes;
- }
-
- /// <summary>
- /// Visits all nodes in the collection using a specified element visitor.
- /// </summary>
- /// <typeparam name="T">The type of the nodes.</typeparam>
- /// <param name="nodes">The nodes to visit.</param>
- /// <param name="elementVisitor">A delegate that visits a single element,
- /// optionally replacing it with a new element.</param>
- /// <returns>The modified node list, if any of the elements were modified;
- /// otherwise, returns the original node list.</returns>
- public static ReadOnlyCollection<T> Visit<T>(ReadOnlyCollection<T> nodes, Func<T, T> elementVisitor) {
- T[] newNodes = null;
- for (int i = 0, n = nodes.Count; i < n; i++) {
- T node = elementVisitor(nodes[i]);
- if (newNodes != null) {
- newNodes[i] = node;
- } else if (!object.ReferenceEquals(node, nodes[i])) {
- newNodes = new T[n];
- for (int j = 0; j < i; j++) {
- newNodes[j] = nodes[j];
- }
- newNodes[i] = node;
- }
- }
- if (newNodes == null) {
- return nodes;
- }
- return new TrueReadOnlyCollection<T>(newNodes);
- }
-
- /// <summary>
- /// Visits an expression, casting the result back to the original expression type.
- /// </summary>
- /// <typeparam name="T">The type of the expression.</typeparam>
- /// <param name="node">The expression to visit.</param>
- /// <param name="callerName">The name of the calling method; used to report to report a better error message.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- /// <exception cref="InvalidOperationException">The visit method for this node returned a different type.</exception>
- public T VisitAndConvert<T>(T node, string callerName) where T : Expression {
- if (node == null) {
- return null;
- }
- node = Visit(node) as T;
- if (node == null) {
- throw Error.MustRewriteToSameNode(callerName, typeof(T), callerName);
- }
- return node;
- }
-
- /// <summary>
- /// Visits an expression, casting the result back to the original expression type.
- /// </summary>
- /// <typeparam name="T">The type of the expression.</typeparam>
- /// <param name="nodes">The expression to visit.</param>
- /// <param name="callerName">The name of the calling method; used to report to report a better error message.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- /// <exception cref="InvalidOperationException">The visit method for this node returned a different type.</exception>
- public ReadOnlyCollection<T> VisitAndConvert<T>(ReadOnlyCollection<T> nodes, string callerName) where T : Expression {
- T[] newNodes = null;
- for (int i = 0, n = nodes.Count; i < n; i++) {
- T node = Visit(nodes[i]) as T;
- if (node == null) {
- throw Error.MustRewriteToSameNode(callerName, typeof(T), callerName);
- }
-
- if (newNodes != null) {
- newNodes[i] = node;
- } else if (!object.ReferenceEquals(node, nodes[i])) {
- newNodes = new T[n];
- for (int j = 0; j < i; j++) {
- newNodes[j] = nodes[j];
- }
- newNodes[i] = node;
- }
- }
- if (newNodes == null) {
- return nodes;
- }
- return new TrueReadOnlyCollection<T>(newNodes);
- }
-
- /// <summary>
- /// Visits the children of the <see cref="BinaryExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitBinary(BinaryExpression node) {
- // Walk children in evaluation order: left, conversion, right
- return ValidateBinary(
- node,
- node.Update(
- Visit(node.Left),
- VisitAndConvert(node.Conversion, "VisitBinary"),
- Visit(node.Right)
- )
- );
- }
-
- /// <summary>
- /// Visits the children of the <see cref="BlockExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitBlock(BlockExpression node) {
- int count = node.ExpressionCount;
- Expression[] nodes = null;
- for (int i = 0; i < count; i++) {
- Expression oldNode = node.GetExpression(i);
- Expression newNode = Visit(oldNode);
-
- if (oldNode != newNode) {
- if (nodes == null) {
- nodes = new Expression[count];
- }
- nodes[i] = newNode;
- }
- }
- var v = VisitAndConvert(node.Variables, "VisitBlock");
-
- if (v == node.Variables && nodes == null) {
- return node;
- } else {
- for (int i = 0; i < count; i++) {
- if (nodes[i] == null) {
- nodes[i] = node.GetExpression(i);
- }
- }
- }
-
- return node.Rewrite(v, nodes);
- }
-
- /// <summary>
- /// Visits the children of the <see cref="ConditionalExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitConditional(ConditionalExpression node) {
- return node.Update(Visit(node.Test), Visit(node.IfTrue), Visit(node.IfFalse));
- }
-
- /// <summary>
- /// Visits the <see cref="ConstantExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitConstant(ConstantExpression node) {
- return node;
- }
-
- /// <summary>
- /// Visits the <see cref="DebugInfoExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitDebugInfo(DebugInfoExpression node) {
- return node;
- }
-
- /// <summary>
- /// Visits the children of the <see cref="DynamicExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitDynamic(DynamicExpression node) {
- Expression[] a = VisitArguments((IArgumentProvider)node);
- if (a == null) {
- return node;
- }
-
- return node.Rewrite(a);
- }
-
- /// <summary>
- /// Visits the <see cref="DefaultExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitDefault(DefaultExpression node) {
- return node;
- }
-
- /// <summary>
- /// Visits the children of the extension expression.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- /// <remarks>
- /// This can be overridden to visit or rewrite specific extension nodes.
- /// If it is not overridden, this method will call <see cref="Expression.VisitChildren" />,
- /// which gives the node a chance to walk its children. By default,
- /// <see cref="Expression.VisitChildren" /> will try to reduce the node.
- /// </remarks>
- protected internal virtual Expression VisitExtension(Expression node) {
- return node.VisitChildren(this);
- }
-
- /// <summary>
- /// Visits the children of the <see cref="GotoExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitGoto(GotoExpression node) {
- return node.Update(VisitLabelTarget(node.Target), Visit(node.Value));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="InvocationExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitInvocation(InvocationExpression node) {
- Expression e = Visit(node.Expression);
- Expression[] a = VisitArguments(node);
- if (e == node.Expression && a == null) {
- return node;
- }
-
- return node.Rewrite(e, a);
- }
-
- /// <summary>
- /// Visits the <see cref="LabelTarget" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected virtual LabelTarget VisitLabelTarget(LabelTarget node) {
- return node;
- }
-
- /// <summary>
- /// Visits the children of the <see cref="LabelExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitLabel(LabelExpression node) {
- return node.Update(VisitLabelTarget(node.Target), Visit(node.DefaultValue));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="Expression&lt;T&gt;" />.
- /// </summary>
- /// <typeparam name="T">The type of the delegate.</typeparam>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitLambda<T>(Expression<T> node) {
- return node.Update(Visit(node.Body), VisitAndConvert(node.Parameters, "VisitLambda"));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="LoopExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitLoop(LoopExpression node) {
- return node.Update(VisitLabelTarget(node.BreakLabel), VisitLabelTarget(node.ContinueLabel), Visit(node.Body));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="MemberExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitMember(MemberExpression node) {
- return node.Update(Visit(node.Expression));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="IndexExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitIndex(IndexExpression node) {
- Expression o = Visit(node.Object);
- Expression[] a = VisitArguments(node);
- if (o == node.Object && a == null) {
- return node;
- }
-
- return node.Rewrite(o, a);
- }
-
- /// <summary>
- /// Visits the children of the <see cref="MethodCallExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitMethodCall(MethodCallExpression node) {
- Expression o = Visit(node.Object);
- Expression[] a = VisitArguments((IArgumentProvider)node);
- if (o == node.Object && a == null) {
- return node;
- }
-
- return node.Rewrite(o, a);
- }
-
- /// <summary>
- /// Visits the children of the <see cref="NewArrayExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitNewArray(NewArrayExpression node) {
- return node.Update(Visit(node.Expressions));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="NewExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
- protected internal virtual Expression VisitNew(NewExpression node) {
- return node.Update(Visit(node.Arguments));
- }
-
- /// <summary>
- /// Visits the <see cref="ParameterExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitParameter(ParameterExpression node) {
- return node;
- }
-
- /// <summary>
- /// Visits the children of the <see cref="RuntimeVariablesExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitRuntimeVariables(RuntimeVariablesExpression node) {
- return node.Update(VisitAndConvert(node.Variables, "VisitRuntimeVariables"));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="SwitchCase" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected virtual SwitchCase VisitSwitchCase(SwitchCase node) {
- return node.Update(Visit(node.TestValues), Visit(node.Body));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="SwitchExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitSwitch(SwitchExpression node) {
- return ValidateSwitch(
- node,
- node.Update(
- Visit(node.SwitchValue),
- Visit(node.Cases, VisitSwitchCase),
- Visit(node.DefaultBody)
- )
- );
- }
-
- /// <summary>
- /// Visits the children of the <see cref="CatchBlock" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected virtual CatchBlock VisitCatchBlock(CatchBlock node) {
- return node.Update(VisitAndConvert(node.Variable, "VisitCatchBlock"), Visit(node.Filter), Visit(node.Body));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="TryExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitTry(TryExpression node) {
- return node.Update(
- Visit(node.Body),
- Visit(node.Handlers, VisitCatchBlock),
- Visit(node.Finally),
- Visit(node.Fault)
- );
- }
-
- /// <summary>
- /// Visits the children of the <see cref="TypeBinaryExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitTypeBinary(TypeBinaryExpression node) {
- return node.Update(Visit(node.Expression));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="UnaryExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitUnary(UnaryExpression node) {
- return ValidateUnary(node, node.Update(Visit(node.Operand)));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="MemberInitExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitMemberInit(MemberInitExpression node) {
- return node.Update(
- VisitAndConvert(node.NewExpression, "VisitMemberInit"),
- Visit(node.Bindings, VisitMemberBinding)
- );
- }
-
- /// <summary>
- /// Visits the children of the <see cref="ListInitExpression" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected internal virtual Expression VisitListInit(ListInitExpression node) {
- return node.Update(
- VisitAndConvert(node.NewExpression, "VisitListInit"),
- Visit(node.Initializers, VisitElementInit)
- );
- }
-
- /// <summary>
- /// Visits the children of the <see cref="ElementInit" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected virtual ElementInit VisitElementInit(ElementInit node) {
- return node.Update(Visit(node.Arguments));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="MemberBinding" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected virtual MemberBinding VisitMemberBinding(MemberBinding node) {
- switch (node.BindingType) {
- case MemberBindingType.Assignment:
- return VisitMemberAssignment((MemberAssignment)node);
- case MemberBindingType.MemberBinding:
- return VisitMemberMemberBinding((MemberMemberBinding)node);
- case MemberBindingType.ListBinding:
- return VisitMemberListBinding((MemberListBinding)node);
- default:
- throw Error.UnhandledBindingType(node.BindingType);
- }
- }
-
- /// <summary>
- /// Visits the children of the <see cref="MemberAssignment" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment node) {
- return node.Update(Visit(node.Expression));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="MemberMemberBinding" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node) {
- return node.Update(Visit(node.Bindings, VisitMemberBinding));
- }
-
- /// <summary>
- /// Visits the children of the <see cref="MemberListBinding" />.
- /// </summary>
- /// <param name="node">The expression to visit.</param>
- /// <returns>The modified expression, if it or any subexpression was modified;
- /// otherwise, returns the original expression.</returns>
- protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding node) {
- return node.Update(Visit(node.Initializers, VisitElementInit));
- }
-
-
- //
- // Prevent some common cases of invalid rewrites.
- //
- // Essentially, we don't want the rewritten node to be semantically
- // bound by the factory, which may do the wrong thing. Instead we
- // require derived classes to be explicit about what they want to do if
- // types change.
- //
- private static UnaryExpression ValidateUnary(UnaryExpression before, UnaryExpression after) {
- if (before != after && before.Method == null) {
- if (after.Method != null) {
- throw Error.MustRewriteWithoutMethod(after.Method, "VisitUnary");
- }
-
- // rethrow has null operand
- if (before.Operand != null && after.Operand != null) {
- ValidateChildType(before.Operand.Type, after.Operand.Type, "VisitUnary");
- }
- }
- return after;
- }
-
- private static BinaryExpression ValidateBinary(BinaryExpression before, BinaryExpression after) {
- if (before != after && before.Method == null) {
- if (after.Method != null) {
- throw Error.MustRewriteWithoutMethod(after.Method, "VisitBinary");
- }
-
- ValidateChildType(before.Left.Type, after.Left.Type, "VisitBinary");
- ValidateChildType(before.Right.Type, after.Right.Type, "VisitBinary");
- }
- return after;
- }
-
- // We wouldn't need this if switch didn't infer the method.
- private static SwitchExpression ValidateSwitch(SwitchExpression before, SwitchExpression after) {
- // If we did not have a method, we don't want to bind to one,
- // it might not be the right thing.
- if (before.Comparison == null && after.Comparison != null) {
- throw Error.MustRewriteWithoutMethod(after.Comparison, "VisitSwitch");
- }
- return after;
- }
-
- // Value types must stay as the same type, otherwise it's now a
- // different operation, e.g. adding two doubles vs adding two ints.
- private static void ValidateChildType(Type before, Type after, string methodName) {
- if (before.IsValueType) {
- if (TypeUtils.AreEquivalent(before, after)) {
- // types are the same value type
- return;
- }
- } else if (!after.IsValueType) {
- // both are reference types
- return;
- }
-
- // Otherwise, it's an invalid type change.
- throw Error.MustRewriteChildToSameType(before, after, methodName);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/GotoExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/GotoExpression.cs
deleted file mode 100644
index 7fa8c9a61b7..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/GotoExpression.cs
+++ /dev/null
@@ -1,371 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Specifies what kind of jump this <see cref="GotoExpression"/> represents.
- /// </summary>
- public enum GotoExpressionKind {
- /// <summary>
- /// A <see cref="GotoExpression"/> that represents a jump to some location.
- /// </summary>
- Goto,
- /// <summary>
- /// A <see cref="GotoExpression"/> that represents a return statement.
- /// </summary>
- Return,
- /// <summary>
- /// A <see cref="GotoExpression"/> that represents a break statement.
- /// </summary>
- Break,
- /// <summary>
- /// A <see cref="GotoExpression"/> that represents a continue statement.
- /// </summary>
- Continue,
- }
-
- /// <summary>
- /// Represents an unconditional jump. This includes return statements, break and continue statements, and other jumps.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.GotoExpressionProxy))]
- public sealed class GotoExpression : Expression {
- private readonly GotoExpressionKind _kind;
- private readonly Expression _value;
- private readonly LabelTarget _target;
- private readonly Type _type;
-
- internal GotoExpression(GotoExpressionKind kind, LabelTarget target, Expression value, Type type) {
- _kind = kind;
- _value = value;
- _target = target;
- _type = type;
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return _type; }
- }
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Goto; }
- }
-
- /// <summary>
- /// The value passed to the target, or null if the target is of type
- /// System.Void.
- /// </summary>
- public Expression Value {
- get { return _value; }
- }
-
- /// <summary>
- /// The target label where this node jumps to.
- /// </summary>
- public LabelTarget Target {
- get { return _target; }
- }
-
- /// <summary>
- /// The kind of the goto. For information purposes only.
- /// </summary>
- public GotoExpressionKind Kind {
- get { return _kind; }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitGoto(this);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="target">The <see cref="Target" /> property of the result.</param>
- /// <param name="value">The <see cref="Value" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public GotoExpression Update(LabelTarget target, Expression value) {
- if (target == Target && value == Value) {
- return this;
- }
- return Expression.MakeGoto(Kind, target, value, Type);
- }
- }
-
- public partial class Expression {
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a break statement.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break,
- /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, and a null value to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression Break(LabelTarget target) {
- return MakeGoto(GotoExpressionKind.Break, target, null, typeof(void));
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a break statement. The value passed to the label upon jumping can be specified.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <param name="value">The value that will be passed to the associated label upon jumping.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break,
- /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
- /// and <paramref name="value"/> to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression Break(LabelTarget target, Expression value) {
- return MakeGoto(GotoExpressionKind.Break, target, value, typeof(void));
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a break statement with the specified type.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break,
- /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
- /// and the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>.
- /// </returns>
- public static GotoExpression Break(LabelTarget target, Type type) {
- return MakeGoto(GotoExpressionKind.Break, target, null, type);
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a break statement with the specified type.
- /// The value passed to the label upon jumping can be specified.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <param name="value">The value that will be passed to the associated label upon jumping.</param>
- /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break,
- /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
- /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
- /// and <paramref name="value"/> to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression Break(LabelTarget target, Expression value, Type type) {
- return MakeGoto(GotoExpressionKind.Break, target, value, type);
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a continue statement.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue,
- /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
- /// and a null value to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression Continue(LabelTarget target) {
- return MakeGoto(GotoExpressionKind.Continue, target, null, typeof(void));
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a continue statement with the specified type.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue,
- /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
- /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
- /// and a null value to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression Continue(LabelTarget target, Type type) {
- return MakeGoto(GotoExpressionKind.Continue, target, null, type);
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a return statement.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Return,
- /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
- /// and a null value to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression Return(LabelTarget target) {
- return MakeGoto(GotoExpressionKind.Return, target, null, typeof(void));
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a return statement with the specified type.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Return,
- /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
- /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
- /// and a null value to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression Return(LabelTarget target, Type type) {
- return MakeGoto(GotoExpressionKind.Return, target, null, type);
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a return statement. The value passed to the label upon jumping can be specified.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <param name="value">The value that will be passed to the associated label upon jumping.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue,
- /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
- /// and <paramref name="value"/> to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression Return(LabelTarget target, Expression value) {
- return MakeGoto(GotoExpressionKind.Return, target, value, typeof(void));
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a return statement with the specified type.
- /// The value passed to the label upon jumping can be specified.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <param name="value">The value that will be passed to the associated label upon jumping.</param>
- /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue,
- /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
- /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
- /// and <paramref name="value"/> to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression Return(LabelTarget target, Expression value, Type type) {
- return MakeGoto(GotoExpressionKind.Return, target, value, type);
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a goto.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto,
- /// the <see cref="P:GotoExpression.Target"/> property set to the specified value,
- /// and a null value to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression Goto(LabelTarget target) {
- return MakeGoto(GotoExpressionKind.Goto, target, null, typeof(void));
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a goto with the specified type.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto,
- /// the <see cref="P:GotoExpression.Target"/> property set to the specified value,
- /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
- /// and a null value to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression Goto(LabelTarget target, Type type) {
- return MakeGoto(GotoExpressionKind.Goto, target, null, type);
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a goto. The value passed to the label upon jumping can be specified.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <param name="value">The value that will be passed to the associated label upon jumping.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto,
- /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
- /// and <paramref name="value"/> to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression Goto(LabelTarget target, Expression value) {
- return MakeGoto(GotoExpressionKind.Goto, target, value, typeof(void));
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a goto with the specified type.
- /// The value passed to the label upon jumping can be specified.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <param name="value">The value that will be passed to the associated label upon jumping.</param>
- /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto,
- /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
- /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
- /// and <paramref name="value"/> to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression Goto(LabelTarget target, Expression value, Type type) {
- return MakeGoto(GotoExpressionKind.Goto, target, value, type);
- }
-
- /// <summary>
- /// Creates a <see cref="GotoExpression"/> representing a jump of the specified <see cref="GotoExpressionKind"/>.
- /// The value passed to the label upon jumping can also be specified.
- /// </summary>
- /// <param name="kind">The <see cref="GotoExpressionKind"/> of the <see cref="GotoExpression"/>.</param>
- /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
- /// <param name="value">The value that will be passed to the associated label upon jumping.</param>
- /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
- /// <returns>
- /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to <paramref name="kind"/>,
- /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
- /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
- /// and <paramref name="value"/> to be passed to the target label upon jumping.
- /// </returns>
- public static GotoExpression MakeGoto(GotoExpressionKind kind, LabelTarget target, Expression value, Type type) {
- ValidateGoto(target, ref value, "target", "value");
- return new GotoExpression(kind, target, value, type);
- }
-
- private static void ValidateGoto(LabelTarget target, ref Expression value, string targetParameter, string valueParameter) {
- ContractUtils.RequiresNotNull(target, targetParameter);
- if (value == null) {
- if (target.Type != typeof(void)) throw Error.LabelMustBeVoidOrHaveExpression();
- } else {
- ValidateGotoType(target.Type, ref value, valueParameter);
- }
- }
-
- // Standard argument validation, taken from ValidateArgumentTypes
- private static void ValidateGotoType(Type expectedType, ref Expression value, string paramName) {
- RequiresCanRead(value, paramName);
- if (expectedType != typeof(void)) {
- if (!TypeUtils.AreReferenceAssignable(expectedType, value.Type)) {
- // C# autoquotes return values, so we'll do that here
- if (!TryQuote(expectedType, ref value)) {
- throw Error.ExpressionTypeDoesNotMatchLabel(value.Type, expectedType);
- }
- }
- }
- }
-
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/IArgumentProvider.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/IArgumentProvider.cs
deleted file mode 100644
index af67d2bebb6..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/IArgumentProvider.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
- using Microsoft.Scripting.Utils;
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Provides an internal interface for accessing the arguments that multiple tree
- /// nodes (DynamicExpression, ElementInit, MethodCallExpression, InvocationExpression, NewExpression,
- /// and InexExpression).
- ///
- /// This enables two optimizations which reduce the size of the trees. The first is it enables
- /// the nodes to hold onto an IList of T instead of a ReadOnlyCollection. This saves the cost
- /// of allocating the ReadOnlyCollection for each node. The second is that it enables specialized
- /// subclasses to be created which hold onto a specific number of arguments. For example Block2,
- /// Block3, Block4. These nodes can therefore avoid allocating both a ReadOnlyCollection and an
- /// array for storing their elements saving 32 bytes per node.
- ///
- /// Meanwhile the nodes can continue to expose the original LINQ properties of ReadOnlyCollections. They
- /// do this by re-using 1 field for storing both the array or an element that would normally be stored
- /// in the array.
- ///
- /// For the array case the collection is typed to IList of T instead of ReadOnlyCollection of T.
- /// When the node is initially constructed it is an array. When the compiler accesses the members it
- /// uses this interface. If a user accesses the members the array is promoted to a ReadOnlyCollection.
- ///
- /// For the object case we store the 1st argument in a field typed to object and when the node is initially
- /// constructed this holds directly onto the Expression. When the compiler accesses the members
- /// it again uses this interface and the accessor for the 1st argument uses Expression.ReturnObject to
- /// return the object which handles the Expression or ReadOnlyCollection case. When the user accesses
- /// the ReadOnlyCollection then the object field is updated to hold directly onto the ReadOnlyCollection.
- ///
- /// It is important that the Expressions consistently return the same ReadOnlyCollection otherwise the
- /// re-writer will be broken and it would be a breaking change from LINQ v1. The problem is that currently
- /// users can rely on object identity to tell if the node has changed. Storing the readonly collection in
- /// an overloaded field enables us to both reduce memory usage as well as maintain compatibility and an
- /// easy to use external API.
- /// </summary>
- internal interface IArgumentProvider {
- Expression GetArgument(int index);
- int ArgumentCount {
- get;
- }
- }
-
- static class ArgumentProviderOps {
- internal static T[] Map<T>(this IArgumentProvider collection, Func<Expression, T> select) {
- int count = collection.ArgumentCount;
- T[] result = new T[count];
- count = 0;
- for (int i = 0; i < count; i++) {
- result[i] = select(collection.GetArgument(i));
- }
- return result;
- }
-
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/IndexExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/IndexExpression.cs
deleted file mode 100644
index b0498c9ebd0..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/IndexExpression.cs
+++ /dev/null
@@ -1,451 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Text;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents indexing a property or array.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.IndexExpressionProxy))]
- public sealed class IndexExpression : Expression, IArgumentProvider {
- private readonly Expression _instance;
- private readonly PropertyInfo _indexer;
- private IList<Expression> _arguments;
-
- internal IndexExpression(
- Expression instance,
- PropertyInfo indexer,
- IList<Expression> arguments) {
-
- if (indexer == null) {
- Debug.Assert(instance != null && instance.Type.IsArray);
- Debug.Assert(instance.Type.GetArrayRank() == arguments.Count);
- }
-
- _instance = instance;
- _indexer = indexer;
- _arguments = arguments;
- }
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Index; }
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get {
- if (_indexer != null) {
- return _indexer.PropertyType;
- }
- return _instance.Type.GetElementType();
- }
- }
-
- /// <summary>
- /// An object to index.
- /// </summary>
- public Expression Object {
- get { return _instance; }
- }
-
- /// <summary>
- /// Gets the <see cref="PropertyInfo"/> for the property if the expression represents an indexed property, returns null otherwise.
- /// </summary>
- public PropertyInfo Indexer {
- get { return _indexer; }
- }
-
- /// <summary>
- /// Gets the arguments to be used to index the property or array.
- /// </summary>
- public ReadOnlyCollection<Expression> Arguments {
- get { return ReturnReadOnly(ref _arguments); }
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="object">The <see cref="Object" /> property of the result.</param>
- /// <param name="arguments">The <see cref="Arguments" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public IndexExpression Update(Expression @object, IEnumerable<Expression> arguments) {
- if (@object == Object && arguments == Arguments) {
- return this;
- }
- return Expression.MakeIndex(@object, Indexer, arguments);
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- return _arguments[index];
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return _arguments.Count;
- }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitIndex(this);
- }
-
- internal Expression Rewrite(Expression instance, Expression[] arguments) {
- Debug.Assert(instance != null);
- Debug.Assert(arguments == null || arguments.Length == _arguments.Count);
-
- return Expression.MakeIndex(instance, _indexer, arguments ?? _arguments);
- }
- }
-
- public partial class Expression {
-
- /// <summary>
- /// Creates an <see cref="IndexExpression"/> that represents accessing an indexed property in an object.
- /// </summary>
- /// <param name="instance">The object to which the property belongs. Should be null if the property is static(shared).</param>
- /// <param name="indexer">An <see cref="Expression"/> representing the property to index.</param>
- /// <param name="arguments">An IEnumerable{Expression} contaning the arguments to be used to index the property.</param>
- /// <returns>The created <see cref="IndexExpression"/>.</returns>
- public static IndexExpression MakeIndex(Expression instance, PropertyInfo indexer, IEnumerable<Expression> arguments) {
- if (indexer != null) {
- return Property(instance, indexer, arguments);
- } else {
- return ArrayAccess(instance, arguments);
- }
- }
-
- #region ArrayAccess
-
- /// <summary>
- /// Creates an <see cref="IndexExpression"></see> to access an array.
- /// </summary>
- /// <param name="array">An expression representing the array to index.</param>
- /// <param name="indexes">An array containing expressions used to index the array.</param>
- /// <remarks>The expression representing the array can be obtained by using the MakeMemberAccess method,
- /// or through NewArrayBounds or NewArrayInit.</remarks>
- /// <returns>The created <see cref="IndexExpression"/>.</returns>
- public static IndexExpression ArrayAccess(Expression array, params Expression[] indexes) {
- return ArrayAccess(array, (IEnumerable<Expression>)indexes);
- }
-
- /// <summary>
- /// Creates an <see cref="IndexExpression"></see> to access an array.
- /// </summary>
- /// <param name="array">An expression representing the array to index.</param>
- /// <param name="indexes">An <see cref="IEnumerable{Expression}"/> containing expressions used to index the array.</param>
- /// <remarks>The expression representing the array can be obtained by using the MakeMemberAccess method,
- /// or through NewArrayBounds or NewArrayInit.</remarks>
- /// <returns>The created <see cref="IndexExpression"/>.</returns>
- public static IndexExpression ArrayAccess(Expression array, IEnumerable<Expression> indexes) {
- RequiresCanRead(array, "array");
-
- Type arrayType = array.Type;
- if (!arrayType.IsArray) {
- throw Error.ArgumentMustBeArray();
- }
-
- var indexList = indexes.ToReadOnly();
- if (arrayType.GetArrayRank() != indexList.Count) {
- throw Error.IncorrectNumberOfIndexes();
- }
-
- foreach (Expression e in indexList) {
- RequiresCanRead(e, "indexes");
- if (e.Type != typeof(int)) {
- throw Error.ArgumentMustBeArrayIndexType();
- }
- }
-
- return new IndexExpression(array, null, indexList);
- }
-
- #endregion
-
- #region Property
- /// <summary>
- /// Creates an <see cref="IndexExpression"/> representing the access to an indexed property.
- /// </summary>
- /// <param name="instance">The object to which the property belongs. If the property is static/shared, it must be null.</param>
- /// <param name="propertyName">The name of the indexer.</param>
- /// <param name="arguments">An array of <see cref="Expression"/> objects that are used to index the property.</param>
- /// <returns>The created <see cref="IndexExpression"/>.</returns>
- public static IndexExpression Property(Expression instance, string propertyName, params Expression[] arguments) {
- RequiresCanRead(instance, "instance");
- ContractUtils.RequiresNotNull(propertyName, "indexerName");
- PropertyInfo pi = FindInstanceProperty(instance.Type, propertyName, arguments);
- return Property(instance, pi, arguments);
- }
-
- #region methods for finding a PropertyInfo by its name
- /// <summary>
- /// The method finds the instance property with the specified name in a type. The property's type signature needs to be compatible with
- /// the arguments if it is a indexer. If the arguments is null or empty, we get a normal property.
- /// </summary>
- private static PropertyInfo FindInstanceProperty(Type type, string propertyName, Expression[] arguments) {
- // bind to public names first
- BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy;
- PropertyInfo pi = FindProperty(type, propertyName, arguments, flags);
- if (pi == null) {
- flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy;
- pi = FindProperty(type, propertyName, arguments, flags);
- }
- if (pi == null) {
- if (arguments == null || arguments.Length == 0) {
- throw Error.InstancePropertyWithoutParameterNotDefinedForType(propertyName, type);
- } else {
- throw Error.InstancePropertyWithSpecifiedParametersNotDefinedForType(propertyName, GetArgTypesString(arguments), type);
- }
- }
- return pi;
- }
-
- private static string GetArgTypesString(Expression[] arguments) {
- StringBuilder argTypesStr = new StringBuilder();
- var isFirst = true;
- argTypesStr.Append("(");
- foreach (var t in arguments.Select(arg => arg.Type)) {
- if (!isFirst) {
- argTypesStr.Append(", ");
- }
- argTypesStr.Append(t.Name);
- isFirst = false;
- }
- argTypesStr.Append(")");
- return argTypesStr.ToString();
- }
-
- private static PropertyInfo FindProperty(Type type, string propertyName, Expression[] arguments, BindingFlags flags) {
- MemberInfo[] members = type.FindMembers(MemberTypes.Property, flags, Type.FilterNameIgnoreCase, propertyName);
- if (members == null || members.Length == 0)
- return null;
-
- PropertyInfo pi;
- var propertyInfos = members.Map(t => (PropertyInfo)t);
- int count = FindBestProperty(propertyInfos, arguments, out pi);
-
- if (count == 0)
- return null;
- if (count > 1)
- throw Error.PropertyWithMoreThanOneMatch(propertyName, type);
- return pi;
- }
-
- private static int FindBestProperty(IEnumerable<PropertyInfo> properties, Expression[] args, out PropertyInfo property) {
- int count = 0;
- property = null;
- foreach (PropertyInfo pi in properties) {
- if (pi != null && IsCompatible(pi, args)) {
- if (property == null) {
- property = pi;
- count = 1;
- }
- else {
- count++;
- }
- }
- }
- return count;
- }
-
- private static bool IsCompatible(PropertyInfo pi, Expression[] args) {
- MethodInfo mi;
-
- mi = pi.GetGetMethod(true);
- ParameterInfo[] parms;
- if (mi != null) {
- parms = mi.GetParametersCached();
- } else {
- mi = pi.GetSetMethod(true);
- //The setter has an additional parameter for the value to set,
- //need to remove the last type to match the arguments.
- parms = mi.GetParametersCached().RemoveLast();
- }
-
- if (mi == null) {
- return false;
- }
- if (args == null) {
- return parms.Length == 0;
- }
-
- if (parms.Length != args.Length)
- return false;
- for (int i = 0; i < args.Length; i++) {
- if (args[i] == null) return false;
- if (!TypeUtils.AreReferenceAssignable(parms[i].ParameterType, args[i].Type)) {
- return false;
- }
- }
- return true;
- }
- #endregion
-
- /// <summary>
- /// Creates an <see cref="IndexExpression"/> representing the access to an indexed property.
- /// </summary>
- /// <param name="instance">The object to which the property belongs. If the property is static/shared, it must be null.</param>
- /// <param name="indexer">The <see cref="PropertyInfo"/> that represents the property to index.</param>
- /// <param name="arguments">An array of <see cref="Expression"/> objects that are used to index the property.</param>
- /// <returns>The created <see cref="IndexExpression"/>.</returns>
- public static IndexExpression Property(Expression instance, PropertyInfo indexer, params Expression[] arguments) {
- return Property(instance, indexer, (IEnumerable<Expression>)arguments);
- }
-
- /// <summary>
- /// Creates an <see cref="IndexExpression"/> representing the access to an indexed property.
- /// </summary>
- /// <param name="instance">The object to which the property belongs. If the property is static/shared, it must be null.</param>
- /// <param name="indexer">The <see cref="PropertyInfo"/> that represents the property to index.</param>
- /// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects that are used to index the property.</param>
- /// <returns>The created <see cref="IndexExpression"/>.</returns>
- public static IndexExpression Property(Expression instance, PropertyInfo indexer, IEnumerable<Expression> arguments) {
- var argList = arguments.ToReadOnly();
- ValidateIndexedProperty(instance, indexer, ref argList);
- return new IndexExpression(instance, indexer, argList);
- }
-
- // CTS places no restrictions on properties (see ECMA-335 8.11.3),
- // so we validate that the property conforms to CLS rules here.
- //
- // Does reflection help us out at all? Expression.Property skips all of
- // these checks, so either it needs more checks or we need less here.
- private static void ValidateIndexedProperty(Expression instance, PropertyInfo property, ref ReadOnlyCollection<Expression> argList) {
-
- // If both getter and setter specified, all their parameter types
- // should match, with exception of the last setter parameter which
- // should match the type returned by the get method.
- // Accessor parameters cannot be ByRef.
-
- ContractUtils.RequiresNotNull(property, "property");
- if (property.PropertyType.IsByRef) throw Error.PropertyCannotHaveRefType();
- if (property.PropertyType == typeof(void)) throw Error.PropertyTypeCannotBeVoid();
-
- ParameterInfo[] getParameters = null;
- MethodInfo getter = property.GetGetMethod(true);
- if (getter != null) {
- getParameters = getter.GetParametersCached();
- ValidateAccessor(instance, getter, getParameters, ref argList);
- }
-
- MethodInfo setter = property.GetSetMethod(true);
- if (setter != null) {
- ParameterInfo[] setParameters = setter.GetParametersCached();
- if (setParameters.Length == 0) throw Error.SetterHasNoParams();
-
- // valueType is the type of the value passed to the setter (last parameter)
- Type valueType = setParameters[setParameters.Length - 1].ParameterType;
- if (valueType.IsByRef) throw Error.PropertyCannotHaveRefType();
- if (setter.ReturnType != typeof(void)) throw Error.SetterMustBeVoid();
- if (property.PropertyType != valueType) throw Error.PropertyTyepMustMatchSetter();
-
- if (getter != null) {
- if (getter.IsStatic ^ setter.IsStatic) throw Error.BothAccessorsMustBeStatic();
- if (getParameters.Length != setParameters.Length - 1) throw Error.IndexesOfSetGetMustMatch();
-
- for (int i = 0; i < getParameters.Length; i++) {
- if (getParameters[i].ParameterType != setParameters[i].ParameterType) throw Error.IndexesOfSetGetMustMatch();
- }
- } else {
- ValidateAccessor(instance, setter, setParameters.RemoveLast(), ref argList);
- }
- }
-
- if (getter == null && setter == null) {
- throw Error.PropertyDoesNotHaveAccessor(property);
- }
- }
-
- private static void ValidateAccessor(Expression instance, MethodInfo method, ParameterInfo[] indexes, ref ReadOnlyCollection<Expression> arguments) {
- ContractUtils.RequiresNotNull(arguments, "arguments");
-
- ValidateMethodInfo(method);
- if ((method.CallingConvention & CallingConventions.VarArgs) != 0) throw Error.AccessorsCannotHaveVarArgs();
- if (method.IsStatic) {
- if (instance != null) throw Error.OnlyStaticMethodsHaveNullInstance();
- } else {
- if (instance == null) throw Error.OnlyStaticMethodsHaveNullInstance();
- RequiresCanRead(instance, "instance");
- ValidateCallInstanceType(instance.Type, method);
- }
-
- ValidateAccessorArgumentTypes(method, indexes, ref arguments);
- }
-
- private static void ValidateAccessorArgumentTypes(MethodInfo method, ParameterInfo[] indexes, ref ReadOnlyCollection<Expression> arguments) {
- if (indexes.Length > 0) {
- if (indexes.Length != arguments.Count) {
- throw Error.IncorrectNumberOfMethodCallArguments(method);
- }
- Expression[] newArgs = null;
- for (int i = 0, n = indexes.Length; i < n; i++) {
- Expression arg = arguments[i];
- ParameterInfo pi = indexes[i];
- RequiresCanRead(arg, "arguments");
-
- Type pType = pi.ParameterType;
- if (pType.IsByRef) throw Error.AccessorsCannotHaveByRefArgs();
- TypeUtils.ValidateType(pType);
-
- if (!TypeUtils.AreReferenceAssignable(pType, arg.Type)) {
- if (!TryQuote(pType, ref arg)) {
- throw Error.ExpressionTypeDoesNotMatchMethodParameter(arg.Type, pType, method);
- }
- }
- if (newArgs == null && arg != arguments[i]) {
- newArgs = new Expression[arguments.Count];
- for (int j = 0; j < i; j++) {
- newArgs[j] = arguments[j];
- }
- }
- if (newArgs != null) {
- newArgs[i] = arg;
- }
- }
- if (newArgs != null) {
- arguments = new TrueReadOnlyCollection<Expression>(newArgs);
- }
-
- } else if (arguments.Count > 0) {
- throw Error.IncorrectNumberOfMethodCallArguments(method);
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/InvocationExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/InvocationExpression.cs
deleted file mode 100644
index 2dfdb3a6be7..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/InvocationExpression.cs
+++ /dev/null
@@ -1,199 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents an expression that applies a delegate or lambda expression to a list of argument expressions.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.InvocationExpressionProxy))]
- public sealed class InvocationExpression : Expression, IArgumentProvider {
- private IList<Expression> _arguments;
- private readonly Expression _lambda;
- private readonly Type _returnType;
-
- internal InvocationExpression(Expression lambda, IList<Expression> arguments, Type returnType) {
- _lambda = lambda;
- _arguments = arguments;
- _returnType = returnType;
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents.
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return _returnType; }
- }
-
- /// <summary>
- /// Returns the node type of this Expression. Extension nodes should return
- /// ExpressionType.Extension when overriding this method.
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Invoke; }
- }
-
- /// <summary>
- /// Gets the delegate or lambda expression to be applied.
- /// </summary>
- public Expression Expression {
- get { return _lambda; }
- }
-
- /// <summary>
- /// Gets the arguments that the delegate or lambda expression is applied to.
- /// </summary>
- public ReadOnlyCollection<Expression> Arguments {
- get { return ReturnReadOnly(ref _arguments); }
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="expression">The <see cref="Expression" /> property of the result.</param>
- /// <param name="arguments">The <see cref="Arguments" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public InvocationExpression Update(Expression expression, IEnumerable<Expression> arguments) {
- if (expression == Expression && arguments == Arguments) {
- return this;
- }
-
- return Expression.Invoke(expression, arguments);
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- return _arguments[index];
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return _arguments.Count;
- }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitInvocation(this);
- }
-
- internal InvocationExpression Rewrite(Expression lambda, Expression[] arguments) {
- Debug.Assert(lambda != null);
- Debug.Assert(arguments == null || arguments.Length == _arguments.Count);
-
- return Expression.Invoke(lambda, arguments ?? _arguments);
- }
-
- internal LambdaExpression LambdaOperand {
- get {
- return (_lambda.NodeType == ExpressionType.Quote)
- ? (LambdaExpression)((UnaryExpression)_lambda).Operand
- : (_lambda as LambdaExpression);
- }
- }
- }
-
- public partial class Expression {
-
- ///<summary>
- ///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
- ///applies a delegate or lambda expression to a list of argument expressions.
- ///</summary>
- ///<returns>
- ///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
- ///applies the specified delegate or lambda expression to the provided arguments.
- ///</returns>
- ///<param name="expression">
- ///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
- ///or lambda expression to be applied.
- ///</param>
- ///<param name="arguments">
- ///An array of <see cref="T:System.Linq.Expressions.Expression" /> objects
- ///that represent the arguments that the delegate or lambda expression is applied to.
- ///</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="expression" /> is null.</exception>
- ///<exception cref="T:System.ArgumentException">
- ///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an element of <paramref name="arguments" /> is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
- ///<exception cref="T:System.InvalidOperationException">
- ///<paramref name="arguments" /> does not contain the same number of elements as the list of parameters for the delegate represented by <paramref name="expression" />.</exception>
- public static InvocationExpression Invoke(Expression expression, params Expression[] arguments) {
- return Invoke(expression, (IEnumerable<Expression>)arguments);
- }
-
- ///<summary>
- ///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
- ///applies a delegate or lambda expression to a list of argument expressions.
- ///</summary>
- ///<returns>
- ///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
- ///applies the specified delegate or lambda expression to the provided arguments.
- ///</returns>
- ///<param name="expression">
- ///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
- ///or lambda expression to be applied.
- ///</param>
- ///<param name="arguments">
- ///An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Linq.Expressions.Expression" /> objects
- ///that represent the arguments that the delegate or lambda expression is applied to.
- ///</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="expression" /> is null.</exception>
- ///<exception cref="T:System.ArgumentException">
- ///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an element of <paramref name="arguments" /> is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
- ///<exception cref="T:System.InvalidOperationException">
- ///<paramref name="arguments" /> does not contain the same number of elements as the list of parameters for the delegate represented by <paramref name="expression" />.</exception>
- public static InvocationExpression Invoke(Expression expression, IEnumerable<Expression> arguments) {
- RequiresCanRead(expression, "expression");
-
- var args = arguments.ToReadOnly();
- var mi = GetInvokeMethod(expression);
- ValidateArgumentTypes(mi, ExpressionType.Invoke, ref args);
- return new InvocationExpression(expression, args, mi.ReturnType);
- }
-
- /// <summary>
- /// Gets the delegate's Invoke method; used by InvocationExpression.
- /// </summary>
- /// <param name="expression">The expression to be invoked.</param>
- internal static MethodInfo GetInvokeMethod(Expression expression) {
- Type delegateType = expression.Type;
- if (!expression.Type.IsSubclassOf(typeof(MulticastDelegate))) {
- Type exprType = TypeUtils.FindGenericType(typeof(Expression<>), expression.Type);
- if (exprType == null) {
- throw Error.ExpressionTypeNotInvocable(expression.Type);
- }
- delegateType = exprType.GetGenericArguments()[0];
- }
-
- return delegateType.GetMethod("Invoke");
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LabelExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LabelExpression.cs
deleted file mode 100644
index 513b0c4df55..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LabelExpression.cs
+++ /dev/null
@@ -1,115 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents a label, which can be placed in any <see cref="Expression"/> context. If
- /// it is jumped to, it will get the value provided by the corresponding
- /// <see cref="GotoExpression"/>. Otherwise, it gets the value in <see cref="LabelExpression.DefaultValue"/>. If the
- /// <see cref="Type"/> equals System.Void, no value should be provided.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.LabelExpressionProxy))]
- public sealed class LabelExpression : Expression {
- private readonly Expression _defaultValue;
- private readonly LabelTarget _target;
-
- internal LabelExpression(LabelTarget label, Expression defaultValue) {
- _target = label;
- _defaultValue = defaultValue;
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return _target.Type; }
- }
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Label; }
- }
-
- /// <summary>
- /// The <see cref="LabelTarget"/> which this label is associated with.
- /// </summary>
- public LabelTarget Target {
- get { return _target; }
- }
-
- /// <summary>
- /// The value of the <see cref="LabelExpression"/> when the label is reached through
- /// normal control flow (e.g. is not jumped to).
- /// </summary>
- public Expression DefaultValue {
- get { return _defaultValue; }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitLabel(this);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="target">The <see cref="Target" /> property of the result.</param>
- /// <param name="defaultValue">The <see cref="DefaultValue" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public LabelExpression Update(LabelTarget target, Expression defaultValue) {
- if (target == Target && defaultValue == DefaultValue) {
- return this;
- }
- return Expression.Label(target, defaultValue);
- }
- }
-
- public partial class Expression {
- /// <summary>
- /// Creates a <see cref="LabelExpression"/> representing a label with no default value.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> which this <see cref="LabelExpression"/> will be associated with.</param>
- /// <returns>A <see cref="LabelExpression"/> with no default value.</returns>
- public static LabelExpression Label(LabelTarget target) {
- return Label(target, null);
- }
-
- /// <summary>
- /// Creates a <see cref="LabelExpression"/> representing a label with the given default value.
- /// </summary>
- /// <param name="target">The <see cref="LabelTarget"/> which this <see cref="LabelExpression"/> will be associated with.</param>
- /// <param name="defaultValue">The value of this <see cref="LabelExpression"/> when the label is reached through normal control flow.</param>
- /// <returns>A <see cref="LabelExpression"/> with the given default value.</returns>
- public static LabelExpression Label(LabelTarget target, Expression defaultValue) {
- ValidateGoto(target, ref defaultValue, "label", "defaultValue");
- return new LabelExpression(target, defaultValue);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LabelTarget.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LabelTarget.cs
deleted file mode 100644
index 3385dbde64d..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LabelTarget.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- /// <summary>
- /// Used to denote the target of a <see cref="GotoExpression"/>.
- /// </summary>
- public sealed class LabelTarget {
- private readonly Type _type;
- private readonly string _name;
-
- internal LabelTarget(Type type, string name) {
- _type = type;
- _name = name;
- }
-
- /// <summary>
- /// Gets the name of the label.
- /// </summary>
- /// <remarks>The label's name is provided for information purposes only.</remarks>
- public string Name {
- get { return _name; }
- }
-
- /// <summary>
- /// The type of value that is passed when jumping to the label
- /// (or System.Void if no value should be passed).
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
- public Type Type {
- get { return _type; }
- }
-
- /// <summary>
- /// Returns a <see cref="String"/> that represents the current <see cref="Object"/>.
- /// </summary>
- /// <returns>A <see cref="String"/> that represents the current <see cref="Object"/>. </returns>
- public override string ToString() {
- return String.IsNullOrEmpty(this.Name) ? "UnamedLabel" : this.Name;
- }
- }
-
- public partial class Expression {
- /// <summary>
- /// Creates a <see cref="LabelTarget"/> representing a label with void type and no name.
- /// </summary>
- /// <returns>The new <see cref="LabelTarget"/>.</returns>
- public static LabelTarget Label() {
- return Label(typeof(void), null);
- }
-
- /// <summary>
- /// Creates a <see cref="LabelTarget"/> representing a label with void type and the given name.
- /// </summary>
- /// <param name="name">The name of the label.</param>
- /// <returns>The new <see cref="LabelTarget"/>.</returns>
- public static LabelTarget Label(string name) {
- return Label(typeof(void), name);
- }
-
- /// <summary>
- /// Creates a <see cref="LabelTarget"/> representing a label with the given type.
- /// </summary>
- /// <param name="type">The type of value that is passed when jumping to the label.</param>
- /// <returns>The new <see cref="LabelTarget"/>.</returns>
- public static LabelTarget Label(Type type) {
- return Label(type, null);
- }
-
- /// <summary>
- /// Creates a <see cref="LabelTarget"/> representing a label with the given type and name.
- /// </summary>
- /// <param name="type">The type of value that is passed when jumping to the label.</param>
- /// <param name="name">The name of the label.</param>
- /// <returns>The new <see cref="LabelTarget"/>.</returns>
- public static LabelTarget Label(Type type, string name) {
- ContractUtils.RequiresNotNull(type, "type");
- TypeUtils.ValidateType(type);
- return new LabelTarget(type, name);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LambdaExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LambdaExpression.cs
deleted file mode 100644
index 050330c0b4d..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LambdaExpression.cs
+++ /dev/null
@@ -1,666 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-#if FEATURE_REFEMIT
-using System.Reflection.Emit;
-#endif
-using System.Threading;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- using Compiler;
-
- /// <summary>
- /// Creates a <see cref="LambdaExpression"/> node.
- /// This captures a block of code that is similar to a .NET method body.
- /// </summary>
- /// <remarks>
- /// Lambda expressions take input through parameters and are expected to be fully bound.
- /// </remarks>
- [DebuggerTypeProxy(typeof(Expression.LambdaExpressionProxy))]
- public abstract class LambdaExpression : Expression {
- private readonly string _name;
- private readonly Expression _body;
- private readonly ReadOnlyCollection<ParameterExpression> _parameters;
- private readonly Type _delegateType;
- private readonly bool _tailCall;
-
- internal LambdaExpression(
- Type delegateType,
- string name,
- Expression body,
- bool tailCall,
- ReadOnlyCollection<ParameterExpression> parameters
- ) {
-
- Debug.Assert(delegateType != null);
-
- _name = name;
- _body = body;
- _parameters = parameters;
- _delegateType = delegateType;
- _tailCall = tailCall;
- }
-#if FEATURE_REFEMIT
- internal abstract LambdaExpression Accept(StackSpiller spiller);
-#endif
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return _delegateType; }
- }
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Lambda; }
- }
-
- /// <summary>
- /// Gets the parameters of the lambda expression.
- /// </summary>
- public ReadOnlyCollection<ParameterExpression> Parameters {
- get { return _parameters; }
- }
-
- /// <summary>
- /// Gets the name of the lambda expression.
- /// </summary>
- /// <remarks>Used for debugging purposes.</remarks>
- public string Name {
- get { return _name; }
- }
-
- /// <summary>
- /// Gets the body of the lambda expression.
- /// </summary>
- public Expression Body {
- get { return _body; }
- }
-
- /// <summary>
- /// Gets the return type of the lambda expression.
- /// </summary>
- public Type ReturnType {
- get { return Type.GetMethod("Invoke").ReturnType; }
- }
-
- /// <summary>
- /// Gets the value that indicates if the lambda expression will be compiled with
- /// tail call optimization.
- /// </summary>
- public bool TailCall {
- get { return _tailCall; }
- }
-
- /// <summary>
- /// Produces a delegate that represents the lambda expression.
- /// </summary>
- /// <returns>A delegate containing the compiled version of the lambda.</returns>
- public Delegate Compile() {
- return LambdaCompiler.Compile(this, null);
- }
-
- /// <summary>
- /// Produces a delegate that represents the lambda expression.
- /// </summary>
- /// <param name="debugInfoGenerator">Debugging information generator used by the compiler to mark sequence points and annotate local variables.</param>
- /// <returns>A delegate containing the compiled version of the lambda.</returns>
- public Delegate Compile(DebugInfoGenerator debugInfoGenerator) {
- ContractUtils.RequiresNotNull(debugInfoGenerator, "debugInfoGenerator");
- return LambdaCompiler.Compile(this, debugInfoGenerator);
- }
-
-#if NETSTANDARD
- public Delegate Compile(bool preferInterpretation) {
- // TODO: add logic for preferInterpretation
- return Compile();
- }
-#endif
-
-#if FEATURE_REFEMIT
- /// <summary>
- /// Compiles the lambda into a method definition.
- /// </summary>
- /// <param name="method">A <see cref="MethodBuilder"/> which will be used to hold the lambda's IL.</param>
- public void CompileToMethod(MethodBuilder method) {
- CompileToMethodInternal(method, null);
- }
-
- /// <summary>
- /// Compiles the lambda into a method definition and custom debug information.
- /// </summary>
- /// <param name="method">A <see cref="MethodBuilder"/> which will be used to hold the lambda's IL.</param>
- /// <param name="debugInfoGenerator">Debugging information generator used by the compiler to mark sequence points and annotate local variables.</param>
- public void CompileToMethod(MethodBuilder method, DebugInfoGenerator debugInfoGenerator) {
- ContractUtils.RequiresNotNull(debugInfoGenerator, "debugInfoGenerator");
- CompileToMethodInternal(method, debugInfoGenerator);
- }
-
- private void CompileToMethodInternal(MethodBuilder method, DebugInfoGenerator debugInfoGenerator) {
- ContractUtils.RequiresNotNull(method, "method");
- ContractUtils.Requires(method.IsStatic, "method");
- var type = method.DeclaringType as TypeBuilder;
- if (type == null) throw Error.MethodBuilderDoesNotHaveTypeBuilder();
-
- LambdaCompiler.Compile(this, method, debugInfoGenerator);
- }
-#endif
- }
-
- /// <summary>
- /// Defines a <see cref="Expression{TDelegate}"/> node.
- /// This captures a block of code that is similar to a .NET method body.
- /// </summary>
- /// <typeparam name="TDelegate">The type of the delegate.</typeparam>
- /// <remarks>
- /// Lambda expressions take input through parameters and are expected to be fully bound.
- /// </remarks>
- public sealed class Expression<TDelegate> : LambdaExpression {
- internal Expression(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters)
- : base(typeof(TDelegate), name, body, tailCall, parameters) {
- }
-
- /// <summary>
- /// Produces a delegate that represents the lambda expression.
- /// </summary>
- /// <returns>A delegate containing the compiled version of the lambda.</returns>
- public new TDelegate Compile() {
- return (TDelegate)(object)LambdaCompiler.Compile(this, null);
- }
-
- /// <summary>
- /// Produces a delegate that represents the lambda expression.
- /// </summary>
- /// <param name="debugInfoGenerator">Debugging information generator used by the compiler to mark sequence points and annotate local variables.</param>
- /// <returns>A delegate containing the compiled version of the lambda.</returns>
- public new TDelegate Compile(DebugInfoGenerator debugInfoGenerator) {
- ContractUtils.RequiresNotNull(debugInfoGenerator, "debugInfoGenerator");
- return (TDelegate)(object)LambdaCompiler.Compile(this, debugInfoGenerator);
- }
-
-#if NETSTANDARD
- public new TDelegate Compile(bool preferInterpretation) {
- // TODO: add logic for preferInterpretation
- return Compile();
- }
-#endif
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="body">The <see cref="LambdaExpression.Body">Body</see> property of the result.</param>
- /// <param name="parameters">The <see cref="LambdaExpression.Parameters">Parameters</see> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public Expression<TDelegate> Update(Expression body, IEnumerable<ParameterExpression> parameters) {
- if (body == Body && parameters == Parameters) {
- return this;
- }
- return Expression.Lambda<TDelegate>(body, Name, TailCall, parameters);
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitLambda(this);
- }
-#if FEATURE_REFEMIT
- internal override LambdaExpression Accept(StackSpiller spiller) {
- return spiller.Rewrite(this);
- }
-#endif
- internal static LambdaExpression Create(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) {
- return new Expression<TDelegate>(body, name, tailCall, parameters);
- }
- }
-
-
- public partial class Expression {
-
- /// <summary>
- /// Creates an Expression{T} given the delegate type. Caches the
- /// factory method to speed up repeated creations for the same T.
- /// </summary>
- internal static LambdaExpression CreateLambda(Type delegateType, Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) {
- // Get or create a delegate to the public Expression.Lambda<T>
- // method and call that will be used for creating instances of this
- // delegate type
- LambdaFactory fastPath;
- if (_LambdaFactories == null) {
- // NOTE: this must be Interlocked assigment since we use _LambdaFactories for locking.
- Interlocked.CompareExchange(ref _LambdaFactories, new CacheDict<Type, LambdaFactory>(50), null);
- }
-
- MethodInfo create = null;
- lock (_LambdaFactories) {
- if (!_LambdaFactories.TryGetValue(delegateType, out fastPath)) {
- create = typeof(Expression<>).MakeGenericType(delegateType).GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic);
- if (TypeUtils.CanCache(delegateType)) {
- _LambdaFactories[delegateType] = fastPath = (LambdaFactory)Delegate.CreateDelegate(typeof(LambdaFactory), create);
- }
- }
- }
-
- if (fastPath != null) {
- return fastPath(body, name, tailCall, parameters);
- }
-
- Debug.Assert(create != null);
- return (LambdaExpression)create.Invoke(null, new object[] { body, name, tailCall, parameters });
- }
-
- /// <summary>
- /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
- /// </summary>
- /// <typeparam name="TDelegate">The delegate type. </typeparam>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters) {
- return Lambda<TDelegate>(body, false, (IEnumerable<ParameterExpression>)parameters);
- }
-
- /// <summary>
- /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
- /// </summary>
- /// <typeparam name="TDelegate">The delegate type. </typeparam>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
- /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, params ParameterExpression[] parameters) {
- return Lambda<TDelegate>(body, tailCall, (IEnumerable<ParameterExpression>)parameters);
- }
-
- /// <summary>
- /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
- /// </summary>
- /// <typeparam name="TDelegate">The delegate type. </typeparam>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static Expression<TDelegate> Lambda<TDelegate>(Expression body, IEnumerable<ParameterExpression> parameters) {
- return Lambda<TDelegate>(body, null, false, parameters);
- }
-
- /// <summary>
- /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
- /// </summary>
- /// <typeparam name="TDelegate">The delegate type. </typeparam>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
- /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) {
- return Lambda<TDelegate>(body, null, tailCall, parameters);
- }
-
- /// <summary>
- /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
- /// </summary>
- /// <typeparam name="TDelegate">The delegate type. </typeparam>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <param name="name">The name of the lambda. Used for generating debugging info.</param>
- /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static Expression<TDelegate> Lambda<TDelegate>(Expression body, String name, IEnumerable<ParameterExpression> parameters) {
- return Lambda<TDelegate>(body, name, false, parameters);
- }
-
- /// <summary>
- /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
- /// </summary>
- /// <typeparam name="TDelegate">The delegate type. </typeparam>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="name">The name of the lambda. Used for generating debugging info.</param>
- /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
- /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static Expression<TDelegate> Lambda<TDelegate>(Expression body, String name, bool tailCall, IEnumerable<ParameterExpression> parameters) {
- var parameterList = parameters.ToReadOnly();
- ValidateLambdaArgs(typeof(TDelegate), ref body, parameterList);
- return new Expression<TDelegate>(body, name, tailCall, parameterList);
- }
-
-
- /// <summary>
- /// Creates a LambdaExpression by first constructing a delegate type.
- /// </summary>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static LambdaExpression Lambda(Expression body, params ParameterExpression[] parameters) {
- return Lambda(body, false, (IEnumerable<ParameterExpression>)parameters);
- }
-
- /// <summary>
- /// Creates a LambdaExpression by first constructing a delegate type.
- /// </summary>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
- /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static LambdaExpression Lambda(Expression body, bool tailCall, params ParameterExpression[] parameters) {
- return Lambda(body, tailCall, (IEnumerable<ParameterExpression>)parameters);
- }
-
- /// <summary>
- /// Creates a LambdaExpression by first constructing a delegate type.
- /// </summary>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static LambdaExpression Lambda(Expression body, IEnumerable<ParameterExpression> parameters) {
- return Lambda(body, null, false, parameters);
- }
-
- /// <summary>
- /// Creates a LambdaExpression by first constructing a delegate type.
- /// </summary>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
- /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static LambdaExpression Lambda(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) {
- return Lambda(body, null, tailCall, parameters);
- }
-
- /// <summary>
- /// Creates a LambdaExpression by first constructing a delegate type.
- /// </summary>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
- /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static LambdaExpression Lambda(Type delegateType, Expression body, params ParameterExpression[] parameters) {
- return Lambda(delegateType, body, null, false, parameters);
- }
-
- /// <summary>
- /// Creates a LambdaExpression by first constructing a delegate type.
- /// </summary>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
- /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
- /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, params ParameterExpression[] parameters) {
- return Lambda(delegateType, body, null, tailCall, parameters);
- }
-
- /// <summary>
- /// Creates a LambdaExpression by first constructing a delegate type.
- /// </summary>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
- /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static LambdaExpression Lambda(Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters) {
- return Lambda(delegateType, body, null, false, parameters);
- }
-
- /// <summary>
- /// Creates a LambdaExpression by first constructing a delegate type.
- /// </summary>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
- /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
- /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) {
- return Lambda(delegateType, body, null, tailCall, parameters);
- }
-
- /// <summary>
- /// Creates a LambdaExpression by first constructing a delegate type.
- /// </summary>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <param name="name">The name for the lambda. Used for emitting debug information.</param>
- /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static LambdaExpression Lambda(Expression body, string name, IEnumerable<ParameterExpression> parameters) {
- return Lambda(body, name, false, parameters);
- }
-
- /// <summary>
- /// Creates a LambdaExpression by first constructing a delegate type.
- /// </summary>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="name">The name for the lambda. Used for emitting debug information.</param>
- /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
- /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static LambdaExpression Lambda(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) {
- ContractUtils.RequiresNotNull(body, "body");
-
- var parameterList = parameters.ToReadOnly();
-
- int paramCount = parameterList.Count;
- Type[] typeArgs = new Type[paramCount + 1];
- if (paramCount > 0) {
- var set = new Set<ParameterExpression>(parameterList.Count);
- for (int i = 0; i < paramCount; i++) {
- var param = parameterList[i];
- ContractUtils.RequiresNotNull(param, "parameter");
- typeArgs[i] = param.IsByRef ? param.Type.MakeByRefType() : param.Type;
- if (set.Contains(param)) {
- throw Error.DuplicateVariable(param);
- }
- set.Add(param);
- }
- }
- typeArgs[paramCount] = body.Type;
-
- Type delegateType = DelegateHelpers.MakeDelegateType(typeArgs);
-
- return CreateLambda(delegateType, body, name, tailCall, parameterList);
- }
-
- /// <summary>
- /// Creates a LambdaExpression by first constructing a delegate type.
- /// </summary>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <param name="name">The name for the lambda. Used for emitting debug information.</param>
- /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
- /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static LambdaExpression Lambda(Type delegateType, Expression body, string name, IEnumerable<ParameterExpression> parameters) {
- var paramList = parameters.ToReadOnly();
- ValidateLambdaArgs(delegateType, ref body, paramList);
-
- return CreateLambda(delegateType, body, name, false, paramList);
- }
-
- /// <summary>
- /// Creates a LambdaExpression by first constructing a delegate type.
- /// </summary>
- /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
- /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
- /// <param name="name">The name for the lambda. Used for emitting debug information.</param>
- /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
- /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
- /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
- public static LambdaExpression Lambda(Type delegateType, Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) {
- var paramList = parameters.ToReadOnly();
- ValidateLambdaArgs(delegateType, ref body, paramList);
-
- return CreateLambda(delegateType, body, name, tailCall, paramList);
- }
-
- private static void ValidateLambdaArgs(Type delegateType, ref Expression body, ReadOnlyCollection<ParameterExpression> parameters) {
- ContractUtils.RequiresNotNull(delegateType, "delegateType");
- RequiresCanRead(body, "body");
-
- if (!typeof(MulticastDelegate).IsAssignableFrom(delegateType) || delegateType == typeof(MulticastDelegate)) {
- throw Error.LambdaTypeMustBeDerivedFromSystemDelegate();
- }
-
- MethodInfo mi;
- lock (_LambdaDelegateCache) {
- if (!_LambdaDelegateCache.TryGetValue(delegateType, out mi)) {
- mi = delegateType.GetMethod("Invoke");
- if (TypeUtils.CanCache(delegateType)) {
- _LambdaDelegateCache[delegateType] = mi;
- }
- }
- }
-
- ParameterInfo[] pis = mi.GetParametersCached();
-
- if (pis.Length > 0) {
- if (pis.Length != parameters.Count) {
- throw Error.IncorrectNumberOfLambdaDeclarationParameters();
- }
- var set = new Set<ParameterExpression>(pis.Length);
- for (int i = 0, n = pis.Length; i < n; i++) {
- ParameterExpression pex = parameters[i];
- ParameterInfo pi = pis[i];
- RequiresCanRead(pex, "parameters");
- Type pType = pi.ParameterType;
- if (pex.IsByRef) {
- if (!pType.IsByRef) {
- //We cannot pass a parameter of T& to a delegate that takes T or any non-ByRef type.
- throw Error.ParameterExpressionNotValidAsDelegate(pex.Type.MakeByRefType(), pType);
- }
- pType = pType.GetElementType();
- }
- if (!TypeUtils.AreReferenceAssignable(pex.Type, pType)) {
- throw Error.ParameterExpressionNotValidAsDelegate(pex.Type, pType);
- }
- if (set.Contains(pex)) {
- throw Error.DuplicateVariable(pex);
- }
- set.Add(pex);
- }
- } else if (parameters.Count > 0) {
- throw Error.IncorrectNumberOfLambdaDeclarationParameters();
- }
- if (mi.ReturnType != typeof(void) && !TypeUtils.AreReferenceAssignable(mi.ReturnType, body.Type)) {
- if (!TryQuote(mi.ReturnType, ref body)) {
- throw Error.ExpressionTypeDoesNotMatchReturn(body.Type, mi.ReturnType);
- }
- }
- }
-
- private static bool ValidateTryGetFuncActionArgs(Type[] typeArgs) {
- if (typeArgs == null) {
- throw new ArgumentNullException("typeArgs");
- }
- for (int i = 0, n = typeArgs.Length; i < n; i++) {
- var a = typeArgs[i];
- if (a == null) {
- throw new ArgumentNullException("typeArgs");
- }
- if (a.IsByRef) {
- return false;
- }
- }
- return true;
- }
-
- /// <summary>
- /// Creates a <see cref="Type"/> object that represents a generic System.Func delegate type that has specific type arguments.
- /// The last type argument specifies the return type of the created delegate.
- /// </summary>
- /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Func delegate type.</param>
- /// <returns>The type of a System.Func delegate that has the specified type arguments.</returns>
- public static Type GetFuncType(params Type[] typeArgs) {
- if (!ValidateTryGetFuncActionArgs(typeArgs)) throw Error.TypeMustNotBeByRef();
-
- Type result = DelegateHelpers.GetFuncType(typeArgs);
- if (result == null) {
- throw Error.IncorrectNumberOfTypeArgsForFunc();
- }
- return result;
- }
-
- /// <summary>
- /// Creates a <see cref="Type"/> object that represents a generic System.Func delegate type that has specific type arguments.
- /// The last type argument specifies the return type of the created delegate.
- /// </summary>
- /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Func delegate type.</param>
- /// <param name="funcType">When this method returns, contains the generic System.Func delegate type that has specific type arguments. Contains null if there is no generic System.Func delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param>
- /// <returns>true if generic System.Func delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns>
- public static bool TryGetFuncType(Type[] typeArgs, out Type funcType) {
- if (ValidateTryGetFuncActionArgs(typeArgs)) {
- return (funcType = DelegateHelpers.GetFuncType(typeArgs)) != null;
- }
- funcType = null;
- return false;
- }
-
- /// <summary>
- /// Creates a <see cref="Type"/> object that represents a generic System.Action delegate type that has specific type arguments.
- /// </summary>
- /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Action delegate type.</param>
- /// <returns>The type of a System.Action delegate that has the specified type arguments.</returns>
- public static Type GetActionType(params Type[] typeArgs) {
- if (!ValidateTryGetFuncActionArgs(typeArgs)) throw Error.TypeMustNotBeByRef();
-
- Type result = DelegateHelpers.GetActionType(typeArgs);
- if (result == null) {
- throw Error.IncorrectNumberOfTypeArgsForAction();
- }
- return result;
- }
-
- /// <summary>
- /// Creates a <see cref="Type"/> object that represents a generic System.Action delegate type that has specific type arguments.
- /// </summary>
- /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Action delegate type.</param>
- /// <param name="actionType">When this method returns, contains the generic System.Action delegate type that has specific type arguments. Contains null if there is no generic System.Action delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param>
- /// <returns>true if generic System.Action delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns>
- public static bool TryGetActionType(Type[] typeArgs, out Type actionType) {
- if (ValidateTryGetFuncActionArgs(typeArgs)) {
- return (actionType = DelegateHelpers.GetActionType(typeArgs)) != null;
- }
- actionType = null;
- return false;
- }
-
- /// <summary>
- /// Gets a <see cref="Type"/> object that represents a generic System.Func or System.Action delegate type that has specific type arguments.
- /// The last type argument determines the return type of the delegate. If no Func or Action is large enough, it will generate a custom
- /// delegate type.
- /// </summary>
- /// <param name="typeArgs">The type arguments of the delegate.</param>
- /// <returns>The delegate type.</returns>
- /// <remarks>
- /// As with Func, the last argument is the return type. It can be set
- /// to System.Void to produce an Action.</remarks>
- public static Type GetDelegateType(params Type[] typeArgs) {
- ContractUtils.RequiresNotEmpty(typeArgs, "typeArgs");
- ContractUtils.RequiresNotNullItems(typeArgs, "typeArgs");
- return DelegateHelpers.MakeDelegateType(typeArgs);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ListArgumentProvider.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ListArgumentProvider.cs
deleted file mode 100644
index da57959aa6d..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ListArgumentProvider.cs
+++ /dev/null
@@ -1,143 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Provides a wrapper around an IArgumentProvider which exposes the argument providers
- /// members out as an IList of Expression. This is used to avoid allocating an array
- /// which needs to be stored inside of a ReadOnlyCollection. Instead this type has
- /// the same amount of overhead as an array without duplicating the storage of the
- /// elements. This ensures that internally we can avoid creating and copying arrays
- /// while users of the Expression trees also don't pay a size penalty for this internal
- /// optimization. See IArgumentProvider for more general information on the Expression
- /// tree optimizations being used here.
- /// </summary>
- class ListArgumentProvider : IList<Expression> {
- private readonly IArgumentProvider _provider;
- private readonly Expression _arg0;
-
- internal ListArgumentProvider(IArgumentProvider provider, Expression arg0) {
- _provider = provider;
- _arg0 = arg0;
- }
-
- #region IList<Expression> Members
-
- public int IndexOf(Expression item) {
- if (_arg0 == item) {
- return 0;
- }
-
- for (int i = 1; i < _provider.ArgumentCount; i++) {
- if (_provider.GetArgument(i) == item) {
- return i;
- }
- }
-
- return -1;
- }
-
- public void Insert(int index, Expression item) {
- throw ContractUtils.Unreachable;
- }
-
- public void RemoveAt(int index) {
- throw ContractUtils.Unreachable;
- }
-
- public Expression this[int index] {
- get {
- if (index == 0) {
- return _arg0;
- }
-
- return _provider.GetArgument(index);
- }
- set {
- throw ContractUtils.Unreachable;
- }
- }
-
- #endregion
-
- #region ICollection<Expression> Members
-
- public void Add(Expression item) {
- throw ContractUtils.Unreachable;
- }
-
- public void Clear() {
- throw ContractUtils.Unreachable;
- }
-
- public bool Contains(Expression item) {
- return IndexOf(item) != -1;
- }
-
- public void CopyTo(Expression[] array, int arrayIndex) {
- array[arrayIndex++] = _arg0;
- for (int i = 1; i < _provider.ArgumentCount; i++) {
- array[arrayIndex++] = _provider.GetArgument(i);
- }
- }
-
- public int Count {
- get { return _provider.ArgumentCount; }
- }
-
- public bool IsReadOnly {
- get { return true; }
- }
-
- public bool Remove(Expression item) {
- throw ContractUtils.Unreachable;
- }
-
- #endregion
-
- #region IEnumerable<Expression> Members
-
- public IEnumerator<Expression> GetEnumerator() {
- yield return _arg0;
-
- for (int i = 1; i < _provider.ArgumentCount; i++) {
- yield return _provider.GetArgument(i);
- }
- }
-
- #endregion
-
- #region IEnumerable Members
-
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
- yield return _arg0;
-
- for (int i = 1; i < _provider.ArgumentCount; i++) {
- yield return _provider.GetArgument(i);
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ListInitExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ListInitExpression.cs
deleted file mode 100644
index 023fd1f3ad9..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ListInitExpression.cs
+++ /dev/null
@@ -1,231 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents a constructor call that has a collection initializer.
- /// </summary>
- /// <remarks>
- /// Use the <see cref="M:ListInit"/> factory methods to create a ListInitExpression.
- /// The value of the NodeType property of a ListInitExpression is ListInit.
- /// </remarks>
- [DebuggerTypeProxy(typeof(Expression.ListInitExpressionProxy))]
- public sealed class ListInitExpression : Expression {
- private readonly NewExpression _newExpression;
- private readonly ReadOnlyCollection<ElementInit> _initializers;
-
- internal ListInitExpression(NewExpression newExpression, ReadOnlyCollection<ElementInit> initializers) {
- _newExpression = newExpression;
- _initializers = initializers;
- }
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.ListInit; }
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return _newExpression.Type; }
- }
-
- /// <summary>
- /// Gets a value that indicates whether the expression tree node can be reduced.
- /// </summary>
- public override bool CanReduce {
- get {
- return true;
- }
- }
-
- /// <summary>
- /// Gets the expression that contains a call to the constructor of a collection type.
- /// </summary>
- public NewExpression NewExpression {
- get { return _newExpression; }
- }
-
- /// <summary>
- /// Gets the element initializers that are used to initialize a collection.
- /// </summary>
- public ReadOnlyCollection<ElementInit> Initializers {
- get { return _initializers; }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitListInit(this);
- }
-
- /// <summary>
- /// Reduces the binary expression node to a simpler expression.
- /// If CanReduce returns true, this should return a valid expression.
- /// This method is allowed to return another node which itself
- /// must be reduced.
- /// </summary>
- /// <returns>The reduced expression.</returns>
- public override Expression Reduce() {
- return MemberInitExpression.ReduceListInit(_newExpression, _initializers, true);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="newExpression">The <see cref="NewExpression" /> property of the result.</param>
- /// <param name="initializers">The <see cref="Initializers" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public ListInitExpression Update(NewExpression newExpression, IEnumerable<ElementInit> initializers) {
- if (newExpression == NewExpression && initializers == Initializers) {
- return this;
- }
- return Expression.ListInit(newExpression, initializers);
- }
- }
-
-
- public partial class Expression {
- /// <summary>
- /// Creates a <see cref="ListInitExpression"/> that uses a method named "Add" to add elements to a collection.
- /// </summary>
- /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
- /// <param name="initializers">An array of <see cref="Expression"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
- /// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
- public static ListInitExpression ListInit(NewExpression newExpression, params Expression[] initializers) {
- ContractUtils.RequiresNotNull(newExpression, "newExpression");
- ContractUtils.RequiresNotNull(initializers, "initializers");
- return ListInit(newExpression, initializers as IEnumerable<Expression>);
- }
-
- /// <summary>
- /// Creates a <see cref="ListInitExpression"/> that uses a method named "Add" to add elements to a collection.
- /// </summary>
- /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
- /// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
- /// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
- public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<Expression> initializers) {
- ContractUtils.RequiresNotNull(newExpression, "newExpression");
- ContractUtils.RequiresNotNull(initializers, "initializers");
-
- var initializerlist = initializers.ToReadOnly();
- if (initializerlist.Count == 0) {
- throw Error.ListInitializerWithZeroMembers();
- }
-
- MethodInfo addMethod = FindMethod(newExpression.Type, "Add", null, new Expression[] { initializerlist[0] }, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
- return ListInit(newExpression, addMethod, initializers);
- }
-
- /// <summary>
- /// Creates a <see cref="ListInitExpression"/> that uses a specified method to add elements to a collection.
- /// </summary>
- /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
- /// <param name="addMethod">A <see cref="MethodInfo"/> that represents an instance method named "Add" (case insensitive), that adds an element to a collection. </param>
- /// <param name="initializers">An array of <see cref="Expression"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
- /// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
- public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo addMethod, params Expression[] initializers) {
- if (addMethod == null) {
- return ListInit(newExpression, initializers as IEnumerable<Expression>);
- }
- ContractUtils.RequiresNotNull(newExpression, "newExpression");
- ContractUtils.RequiresNotNull(initializers, "initializers");
- return ListInit(newExpression, addMethod, initializers as IEnumerable<Expression>);
- }
-
- /// <summary>
- /// Creates a <see cref="ListInitExpression"/> that uses a specified method to add elements to a collection.
- /// </summary>
- /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
- /// <param name="addMethod">A <see cref="MethodInfo"/> that represents an instance method named "Add" (case insensitive), that adds an element to a collection. </param>
- /// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="Expression"/> objects to use to populate the Initializers collection.</param>
- /// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns>
- public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo addMethod, IEnumerable<Expression> initializers) {
- if (addMethod == null) {
- return ListInit(newExpression, initializers);
- }
- ContractUtils.RequiresNotNull(newExpression, "newExpression");
- ContractUtils.RequiresNotNull(initializers, "initializers");
-
- var initializerlist = initializers.ToReadOnly();
- if (initializerlist.Count == 0) {
- throw Error.ListInitializerWithZeroMembers();
- }
- ElementInit[] initList = new ElementInit[initializerlist.Count];
- for (int i = 0; i < initializerlist.Count; i++) {
- initList[i] = ElementInit(addMethod, initializerlist[i]);
- }
- return ListInit(newExpression, new TrueReadOnlyCollection<ElementInit>(initList));
- }
-
- /// <summary>
- /// Creates a <see cref="ListInitExpression"/> that uses specified <see cref="M:ElementInit"/> objects to initialize a collection.
- /// </summary>
- /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
- /// <param name="initializers">An array that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
- /// <returns>
- /// A <see cref="ListInitExpression"/> that has the <see cref="P:Expressions.NodeType"/> property equal to ListInit
- /// and the <see cref="P:ListInitExpression.NewExpression"/> and <see cref="P:ListInitExpression.Initializers"/> properties set to the specified values.
- /// </returns>
- /// <remarks>
- /// The <see cref="P:Expressions.Type"/> property of <paramref name="newExpression"/> must represent a type that implements <see cref="System.Collections.IEnumerable"/>.
- /// The <see cref="P:Expressions.Type"/> property of the resulting <see cref="ListInitExpression"/> is equal to newExpression.Type.
- /// </remarks>
- public static ListInitExpression ListInit(NewExpression newExpression, params ElementInit[] initializers) {
- return ListInit(newExpression, (IEnumerable<ElementInit>)initializers);
- }
-
- /// <summary>
- /// Creates a <see cref="ListInitExpression"/> that uses specified <see cref="M:ElementInit"/> objects to initialize a collection.
- /// </summary>
- /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param>
- /// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
- /// <returns>An <see cref="IEnumerable{T}"/> that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</returns>
- /// <remarks>
- /// The <see cref="P:Expressions.Type"/> property of <paramref name="newExpression"/> must represent a type that implements <see cref="System.Collections.IEnumerable"/>.
- /// The <see cref="P:Expressions.Type"/> property of the resulting <see cref="ListInitExpression"/> is equal to newExpression.Type.
- /// </remarks>
- public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<ElementInit> initializers) {
- ContractUtils.RequiresNotNull(newExpression, "newExpression");
- ContractUtils.RequiresNotNull(initializers, "initializers");
- var initializerlist = initializers.ToReadOnly();
- if (initializerlist.Count == 0) {
- throw Error.ListInitializerWithZeroMembers();
- }
- ValidateListInitArgs(newExpression.Type, initializerlist);
- return new ListInitExpression(newExpression, initializerlist);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LoopExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LoopExpression.cs
deleted file mode 100644
index f9801246150..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LoopExpression.cs
+++ /dev/null
@@ -1,135 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents an infinite loop. It can be exited with "break".
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.LoopExpressionProxy))]
- public sealed class LoopExpression : Expression {
- private readonly Expression _body;
- private readonly LabelTarget _break;
- private readonly LabelTarget _continue;
-
- internal LoopExpression(Expression body, LabelTarget @break, LabelTarget @continue) {
- _body = body;
- _break = @break;
- _continue = @continue;
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents.
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return _break == null ? typeof(void) : _break.Type; }
- }
-
- /// <summary>
- /// Returns the node type of this Expression. Extension nodes should return
- /// ExpressionType.Extension when overriding this method.
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Loop; }
- }
-
- /// <summary>
- /// Gets the <see cref="Expression"/> that is the body of the loop.
- /// </summary>
- public Expression Body {
- get { return _body; }
- }
-
- /// <summary>
- /// Gets the <see cref="LabelTarget"/> that is used by the loop body as a break statement target.
- /// </summary>
- public LabelTarget BreakLabel {
- get { return _break; }
- }
-
- /// <summary>
- /// Gets the <see cref="LabelTarget"/> that is used by the loop body as a continue statement target.
- /// </summary>
- public LabelTarget ContinueLabel {
- get { return _continue; }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitLoop(this);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="breakLabel">The <see cref="BreakLabel" /> property of the result.</param>
- /// <param name="continueLabel">The <see cref="ContinueLabel" /> property of the result.</param>
- /// <param name="body">The <see cref="Body" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public LoopExpression Update(LabelTarget breakLabel, LabelTarget continueLabel, Expression body) {
- if (breakLabel == BreakLabel && continueLabel == ContinueLabel && body == Body) {
- return this;
- }
- return Expression.Loop(body, breakLabel, continueLabel);
- }
- }
-
- public partial class Expression {
- /// <summary>
- /// Creates a <see cref="LoopExpression"/> with the given body.
- /// </summary>
- /// <param name="body">The body of the loop.</param>
- /// <returns>The created <see cref="LoopExpression"/>.</returns>
- public static LoopExpression Loop(Expression body) {
- return Loop(body, null);
- }
-
- /// <summary>
- /// Creates a <see cref="LoopExpression"/> with the given body and break target.
- /// </summary>
- /// <param name="body">The body of the loop.</param>
- /// <param name="break">The break target used by the loop body.</param>
- /// <returns>The created <see cref="LoopExpression"/>.</returns>
- public static LoopExpression Loop(Expression body, LabelTarget @break) {
- return Loop(body, @break, null);
- }
-
- /// <summary>
- /// Creates a <see cref="LoopExpression"/> with the given body.
- /// </summary>
- /// <param name="body">The body of the loop.</param>
- /// <param name="break">The break target used by the loop body.</param>
- /// <param name="continue">The continue target used by the loop body.</param>
- /// <returns>The created <see cref="LoopExpression"/>.</returns>
- public static LoopExpression Loop(Expression body, LabelTarget @break, LabelTarget @continue) {
- RequiresCanRead(body, "body");
- if (@continue != null && @continue.Type != typeof(void)) throw Error.LabelTypeMustBeVoid();
- return new LoopExpression(body, @break, @continue);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberAssignment.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberAssignment.cs
deleted file mode 100644
index b5b205444eb..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberAssignment.cs
+++ /dev/null
@@ -1,107 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Dynamic.Utils;
-using System.Reflection;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents assignment to a member of an object.
- /// </summary>
- public sealed class MemberAssignment : MemberBinding {
- Expression _expression;
- internal MemberAssignment(MemberInfo member, Expression expression)
-#pragma warning disable 618
- : base(MemberBindingType.Assignment, member) {
-#pragma warning restore 618
- _expression = expression;
- }
- /// <summary>
- /// Gets the <see cref="Expression"/> which represents the object whose member is being assigned to.
- /// </summary>
- public Expression Expression {
- get { return _expression; }
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="expression">The <see cref="Expression" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public MemberAssignment Update(Expression expression) {
- if (expression == Expression) {
- return this;
- }
- return Expression.Bind(Member, expression);
- }
- }
-
-
- public partial class Expression {
- /// <summary>
- /// Creates a <see cref="MemberAssignment"/> binding the specified value to the given member.
- /// </summary>
- /// <param name="member">The <see cref="MemberInfo"/> for the member which is being assigned to.</param>
- /// <param name="expression">The value to be assigned to <paramref name="member"/>.</param>
- /// <returns>The created <see cref="MemberAssignment"/>.</returns>
- public static MemberAssignment Bind(MemberInfo member, Expression expression) {
- ContractUtils.RequiresNotNull(member, "member");
- RequiresCanRead(expression, "expression");
- Type memberType;
- ValidateSettableFieldOrPropertyMember(member, out memberType);
- if (!memberType.IsAssignableFrom(expression.Type)) {
- throw Error.ArgumentTypesMustMatch();
- }
- return new MemberAssignment(member, expression);
- }
-
- /// <summary>
- /// Creates a <see cref="MemberAssignment"/> binding the specified value to the given property.
- /// </summary>
- /// <param name="propertyAccessor">The <see cref="PropertyInfo"/> for the property which is being assigned to.</param>
- /// <param name="expression">The value to be assigned to <paramref name="propertyAccessor"/>.</param>
- /// <returns>The created <see cref="MemberAssignment"/>.</returns>
- public static MemberAssignment Bind(MethodInfo propertyAccessor, Expression expression) {
- ContractUtils.RequiresNotNull(propertyAccessor, "propertyAccessor");
- ContractUtils.RequiresNotNull(expression, "expression");
- ValidateMethodInfo(propertyAccessor);
- return Bind(GetProperty(propertyAccessor), expression);
- }
-
-
- private static void ValidateSettableFieldOrPropertyMember(MemberInfo member, out Type memberType) {
- FieldInfo fi = member as FieldInfo;
- if (fi == null) {
- PropertyInfo pi = member as PropertyInfo;
- if (pi == null) {
- throw Error.ArgumentMustBeFieldInfoOrPropertInfo();
- }
- if (!pi.CanWrite) {
- throw Error.PropertyDoesNotHaveSetter(pi);
- }
- memberType = pi.PropertyType;
- } else {
- memberType = fi.FieldType;
- }
- }
- }
-} \ No newline at end of file
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberBinding.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberBinding.cs
deleted file mode 100644
index c9d7ed846a9..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberBinding.cs
+++ /dev/null
@@ -1,82 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Reflection;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Describes the binding types that are used in MemberInitExpression objects.
- /// </summary>
- public enum MemberBindingType {
- /// <summary>
- /// A binding that represents initializing a member with the value of an expression.
- /// </summary>
- Assignment,
- /// <summary>
- /// A binding that represents recursively initializing members of a member.
- /// </summary>
- MemberBinding,
- /// <summary>
- /// A binding that represents initializing a member of type <see cref="System.Collections.IList"/> or <see cref="System.Collections.Generic.ICollection{T}"/> from a list of elements.
- /// </summary>
- ListBinding
- }
-
- /// <summary>
- /// Provides the base class from which the classes that represent bindings that are used to initialize members of a newly created object derive.
- /// </summary>
- public abstract class MemberBinding {
- MemberBindingType _type;
- MemberInfo _member;
-
- /// <summary>
- /// Initializes an instance of <see cref="MemberBinding"/> class.
- /// </summary>
- /// <param name="type">The type of member binding.</param>
- /// <param name="member">The field or property to be initialized.</param>
- [Obsolete("Do not use this constructor. It will be removed in future releases.")]
- protected MemberBinding(MemberBindingType type, MemberInfo member) {
- _type = type;
- _member = member;
- }
-
- /// <summary>
- /// Gets the type of binding that is represented.
- /// </summary>
- public MemberBindingType BindingType {
- get { return _type; }
- }
-
- /// <summary>
- /// Gets the field or property to be initialized.
- /// </summary>
- public MemberInfo Member {
- get { return _member; }
- }
-
- /// <summary>
- /// Returns a <see cref="String"/> that represents the current <see cref="Object"/>.
- /// </summary>
- /// <returns>A <see cref="String"/> that represents the current <see cref="Object"/>. </returns>
- public override string ToString() {
- return ExpressionStringBuilder.MemberBindingToString(this);
- }
- }
-} \ No newline at end of file
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberExpression.cs
deleted file mode 100644
index 0c06640e32c..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberExpression.cs
+++ /dev/null
@@ -1,362 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- /// <summary>
- /// Represents accessing a field or property.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.MemberExpressionProxy))]
- public class MemberExpression : Expression {
- private readonly Expression _expression;
-
- /// <summary>
- /// Gets the field or property to be accessed.
- /// </summary>
- public MemberInfo Member {
- get { return GetMember(); }
- }
-
- /// <summary>
- /// Gets the containing object of the field or property.
- /// </summary>
- public Expression Expression {
- get { return _expression; }
- }
-
- // param order: factories args in order, then other args
- internal MemberExpression(Expression expression) {
-
- _expression = expression;
- }
-
- internal static MemberExpression Make(Expression expression, MemberInfo member) {
- if (member.MemberType == MemberTypes.Field) {
- FieldInfo fi = (FieldInfo)member;
- return new FieldExpression(expression, fi);
- } else {
- PropertyInfo pi = (PropertyInfo)member;
- return new PropertyExpression(expression, pi);
- }
- }
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.MemberAccess; }
- }
-
- internal virtual MemberInfo GetMember() {
- throw ContractUtils.Unreachable;
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitMember(this);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="expression">The <see cref="Expression" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public MemberExpression Update(Expression expression) {
- if (expression == Expression) {
- return this;
- }
- return Expression.MakeMemberAccess(expression, Member);
- }
- }
-
- internal class FieldExpression : MemberExpression {
- private readonly FieldInfo _field;
-
- public FieldExpression(Expression expression, FieldInfo member)
- : base(expression) {
- _field = member;
- }
-
- internal override MemberInfo GetMember() {
- return _field;
- }
-
- public sealed override Type Type {
- get { return _field.FieldType; }
- }
- }
-
- internal class PropertyExpression : MemberExpression {
- private readonly PropertyInfo _property;
- public PropertyExpression(Expression expression, PropertyInfo member)
- : base(expression) {
- _property = member;
- }
-
- internal override MemberInfo GetMember() {
- return _property;
- }
-
- public sealed override Type Type {
- get { return _property.PropertyType; }
- }
- }
-
- public partial class Expression {
-
- #region Field
-
- /// <summary>
- /// Creates a <see cref="MemberExpression"/> accessing a field.
- /// </summary>
- /// <param name="expression">The containing object of the field. This can be null for static fields.</param>
- /// <param name="field">The field to be accessed.</param>
- /// <returns>The created <see cref="MemberExpression"/>.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
- public static MemberExpression Field(Expression expression, FieldInfo field) {
- ContractUtils.RequiresNotNull(field, "field");
-
- if (field.IsStatic) {
- if (expression != null) throw new ArgumentException(Strings.OnlyStaticFieldsHaveNullInstance, "expression");
- } else {
- if (expression == null) throw new ArgumentException(Strings.OnlyStaticFieldsHaveNullInstance, "field");
- RequiresCanRead(expression, "expression");
- if (!TypeUtils.AreReferenceAssignable(field.DeclaringType, expression.Type)) {
- throw Error.FieldInfoNotDefinedForType(field.DeclaringType, field.Name, expression.Type);
- }
- }
- return MemberExpression.Make(expression, field);
- }
-
- /// <summary>
- /// Creates a <see cref="MemberExpression"/> accessing a field.
- /// </summary>
- /// <param name="expression">The containing object of the field. This can be null for static fields.</param>
- /// <param name="fieldName">The field to be accessed.</param>
- /// <returns>The created <see cref="MemberExpression"/>.</returns>
- public static MemberExpression Field(Expression expression, string fieldName) {
- RequiresCanRead(expression, "expression");
-
- // bind to public names first
- FieldInfo fi = expression.Type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
- if (fi == null) {
- fi = expression.Type.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
- }
- if (fi == null) {
- throw Error.InstanceFieldNotDefinedForType(fieldName, expression.Type);
- }
- return Expression.Field(expression, fi);
- }
-
-
- /// <summary>
- /// Creates a <see cref="MemberExpression"/> accessing a field.
- /// </summary>
- /// <param name="expression">The containing object of the field. This can be null for static fields.</param>
- /// <param name="type">The <see cref="Type"/> containing the field.</param>
- /// <param name="fieldName">The field to be accessed.</param>
- /// <returns>The created <see cref="MemberExpression"/>.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
- public static MemberExpression Field(Expression expression, Type type, string fieldName) {
- ContractUtils.RequiresNotNull(type, "type");
-
- // bind to public names first
- FieldInfo fi = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
- if (fi == null) {
- fi = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
- }
-
- if (fi == null) {
- throw Error.FieldNotDefinedForType(fieldName, type);
- }
- return Expression.Field(expression, fi);
- }
- #endregion
-
- #region Property
-
- /// <summary>
- /// Creates a <see cref="MemberExpression"/> accessing a property.
- /// </summary>
- /// <param name="expression">The containing object of the property. This can be null for static properties.</param>
- /// <param name="propertyName">The property to be accessed.</param>
- /// <returns>The created <see cref="MemberExpression"/>.</returns>
- public static MemberExpression Property(Expression expression, string propertyName) {
- RequiresCanRead(expression, "expression");
- ContractUtils.RequiresNotNull(propertyName, "propertyName");
- // bind to public names first
- PropertyInfo pi = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
- if (pi == null) {
- pi = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
- }
- if (pi == null) {
- throw Error.InstancePropertyNotDefinedForType(propertyName, expression.Type);
- }
- return Property(expression, pi);
- }
-
- /// <summary>
- /// Creates a <see cref="MemberExpression"/> accessing a property.
- /// </summary>
- /// <param name="expression">The containing object of the property. This can be null for static properties.</param>
- /// <param name="type">The <see cref="Type"/> containing the property.</param>
- /// <param name="propertyName">The property to be accessed.</param>
- /// <returns>The created <see cref="MemberExpression"/>.</returns>
- public static MemberExpression Property(Expression expression, Type type, string propertyName) {
- ContractUtils.RequiresNotNull(type, "type");
- ContractUtils.RequiresNotNull(propertyName, "propertyName");
- // bind to public names first
- PropertyInfo pi = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
- if (pi == null) {
- pi = type.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
- }
- if (pi == null) {
- throw Error.PropertyNotDefinedForType(propertyName, type);
- }
- return Property(expression, pi);
- }
-
- /// <summary>
- /// Creates a <see cref="MemberExpression"/> accessing a property.
- /// </summary>
- /// <param name="expression">The containing object of the property. This can be null for static properties.</param>
- /// <param name="property">The property to be accessed.</param>
- /// <returns>The created <see cref="MemberExpression"/>.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
- public static MemberExpression Property(Expression expression, PropertyInfo property) {
- ContractUtils.RequiresNotNull(property, "property");
-
- MethodInfo mi = property.GetGetMethod(true) ?? property.GetSetMethod(true);
-
- if (mi == null) {
- throw Error.PropertyDoesNotHaveAccessor(property);
- }
-
- if (mi.IsStatic) {
- if (expression != null) throw new ArgumentException(Strings.OnlyStaticPropertiesHaveNullInstance, "expression");
- } else {
- if (expression == null) throw new ArgumentException(Strings.OnlyStaticPropertiesHaveNullInstance, "property");
- RequiresCanRead(expression, "expression");
- if (!TypeUtils.IsValidInstanceType(property, expression.Type)) {
- throw Error.PropertyNotDefinedForType(property, expression.Type);
- }
- }
- return MemberExpression.Make(expression, property);
- }
-
- /// <summary>
- /// Creates a <see cref="MemberExpression"/> accessing a property.
- /// </summary>
- /// <param name="expression">The containing object of the property. This can be null for static properties.</param>
- /// <param name="propertyAccessor">An accessor method of the property to be accessed.</param>
- /// <returns>The created <see cref="MemberExpression"/>.</returns>
- public static MemberExpression Property(Expression expression, MethodInfo propertyAccessor) {
- ContractUtils.RequiresNotNull(propertyAccessor, "propertyAccessor");
- ValidateMethodInfo(propertyAccessor);
- return Property(expression, GetProperty(propertyAccessor));
- }
-
- private static PropertyInfo GetProperty(MethodInfo mi) {
- Type type = mi.DeclaringType;
- BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic;
- flags |= (mi.IsStatic) ? BindingFlags.Static : BindingFlags.Instance;
- PropertyInfo[] props = type.GetProperties(flags);
- foreach (PropertyInfo pi in props) {
- if (pi.CanRead && CheckMethod(mi, pi.GetGetMethod(true))) {
- return pi;
- }
- if (pi.CanWrite && CheckMethod(mi, pi.GetSetMethod(true))) {
- return pi;
- }
- }
- throw Error.MethodNotPropertyAccessor(mi.DeclaringType, mi.Name);
- }
-
- private static bool CheckMethod(MethodInfo method, MethodInfo propertyMethod) {
- if (method == propertyMethod) {
- return true;
- }
- // If the type is an interface then the handle for the method got by the compiler will not be the
- // same as that returned by reflection.
- // Check for this condition and try and get the method from reflection.
- Type type = method.DeclaringType;
- if (type.IsInterface && method.Name == propertyMethod.Name && type.GetMethod(method.Name) == propertyMethod) {
- return true;
- }
- return false;
- }
-
- #endregion
-
- /// <summary>
- /// Creates a <see cref="MemberExpression"/> accessing a property or field.
- /// </summary>
- /// <param name="expression">The containing object of the member. This can be null for static members.</param>
- /// <param name="propertyOrFieldName">The member to be accessed.</param>
- /// <returns>The created <see cref="MemberExpression"/>.</returns>
- public static MemberExpression PropertyOrField(Expression expression, string propertyOrFieldName) {
- RequiresCanRead(expression, "expression");
- // bind to public names first
- PropertyInfo pi = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
- if (pi != null)
- return Property(expression, pi);
- FieldInfo fi = expression.Type.GetField(propertyOrFieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
- if (fi != null)
- return Field(expression, fi);
- pi = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
- if (pi != null)
- return Property(expression, pi);
- fi = expression.Type.GetField(propertyOrFieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
- if (fi != null)
- return Field(expression, fi);
-
- throw Error.NotAMemberOfType(propertyOrFieldName, expression.Type);
- }
-
- /// <summary>
- /// Creates a <see cref="MemberExpression"/> accessing a property or field.
- /// </summary>
- /// <param name="expression">The containing object of the member. This can be null for static members.</param>
- /// <param name="member">The member to be accessed.</param>
- /// <returns>The created <see cref="MemberExpression"/>.</returns>
- public static MemberExpression MakeMemberAccess(Expression expression, MemberInfo member) {
- ContractUtils.RequiresNotNull(member, "member");
-
- FieldInfo fi = member as FieldInfo;
- if (fi != null) {
- return Expression.Field(expression, fi);
- }
- PropertyInfo pi = member as PropertyInfo;
- if (pi != null) {
- return Expression.Property(expression, pi);
- }
- throw Error.MemberNotFieldOrProperty(member);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberInitExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberInitExpression.cs
deleted file mode 100644
index 04cdd20785f..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberInitExpression.cs
+++ /dev/null
@@ -1,178 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents calling a constructor and initializing one or more members of the new object.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.MemberInitExpressionProxy))]
- public sealed class MemberInitExpression : Expression {
- private readonly NewExpression _newExpression;
- private readonly ReadOnlyCollection<MemberBinding> _bindings;
-
- internal MemberInitExpression(NewExpression newExpression, ReadOnlyCollection<MemberBinding> bindings) {
- _newExpression = newExpression;
- _bindings = bindings;
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents.
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return _newExpression.Type; }
- }
-
- /// <summary>
- /// Gets a value that indicates whether the expression tree node can be reduced.
- /// </summary>
- public override bool CanReduce {
- get {
- return true;
- }
- }
-
- /// <summary>
- /// Returns the node type of this Expression. Extension nodes should return
- /// ExpressionType.Extension when overriding this method.
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.MemberInit; }
- }
-
- ///<summary>Gets the expression that represents the constructor call.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.NewExpression" /> that represents the constructor call.</returns>
- public NewExpression NewExpression {
- get { return _newExpression; }
- }
-
- ///<summary>Gets the bindings that describe how to initialize the members of the newly created object.</summary>
- ///<returns>A <see cref="T:System.Collections.ObjectModel.ReadOnlyCollection`1" /> of <see cref="T:System.Linq.Expressions.MemberBinding" /> objects which describe how to initialize the members.</returns>
- public ReadOnlyCollection<MemberBinding> Bindings {
- get { return _bindings; }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitMemberInit(this);
- }
-
- /// <summary>
- /// Reduces the <see cref="MemberInitExpression"/> to a simpler expression.
- /// If CanReduce returns true, this should return a valid expression.
- /// This method is allowed to return another node which itself
- /// must be reduced.
- /// </summary>
- /// <returns>The reduced expression.</returns>
- public override Expression Reduce() {
- return ReduceMemberInit(_newExpression, _bindings, true);
- }
-
- internal static Expression ReduceMemberInit(Expression objExpression, ReadOnlyCollection<MemberBinding> bindings, bool keepOnStack) {
- var objVar = Expression.Variable(objExpression.Type, null);
- int count = bindings.Count;
- var block = new Expression[count + 2];
- block[0] = Expression.Assign(objVar, objExpression);
- for (int i = 0; i < count; i++) {
- block[i + 1] = ReduceMemberBinding(objVar, bindings[i]);
- }
- block[count + 1] = keepOnStack ? (Expression)objVar : Expression.Empty();
- return Expression.Block(new TrueReadOnlyCollection<Expression>(block));
- }
-
- internal static Expression ReduceListInit(Expression listExpression, ReadOnlyCollection<ElementInit> initializers, bool keepOnStack) {
- var listVar = Expression.Variable(listExpression.Type, null);
- int count = initializers.Count;
- var block = new Expression[count + 2];
- block[0] = Expression.Assign(listVar, listExpression);
- for (int i = 0; i < count; i++) {
- ElementInit element = initializers[i];
- block[i + 1] = Expression.Call(listVar, element.AddMethod, element.Arguments);
- }
- block[count + 1] = keepOnStack ? (Expression)listVar : Expression.Empty();
- return Expression.Block(new TrueReadOnlyCollection<Expression>(block));
- }
-
- internal static Expression ReduceMemberBinding(ParameterExpression objVar, MemberBinding binding) {
- MemberExpression member = Expression.MakeMemberAccess(objVar, binding.Member);
- switch (binding.BindingType) {
- case MemberBindingType.Assignment:
- return Expression.Assign(member, ((MemberAssignment)binding).Expression);
- case MemberBindingType.ListBinding:
- return ReduceListInit(member, ((MemberListBinding)binding).Initializers, false);
- case MemberBindingType.MemberBinding:
- return ReduceMemberInit(member, ((MemberMemberBinding)binding).Bindings, false);
- default: throw ContractUtils.Unreachable;
- }
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="newExpression">The <see cref="NewExpression" /> property of the result.</param>
- /// <param name="bindings">The <see cref="Bindings" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public MemberInitExpression Update(NewExpression newExpression, IEnumerable<MemberBinding> bindings) {
- if (newExpression == NewExpression && bindings == Bindings) {
- return this;
- }
- return Expression.MemberInit(newExpression, bindings);
- }
- }
-
- public partial class Expression {
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MemberInitExpression" />.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MemberInitExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.MemberInit" /> and the <see cref="P:System.Linq.Expressions.MemberInitExpression.NewExpression" /> and <see cref="P:System.Linq.Expressions.MemberInitExpression.Bindings" /> properties set to the specified values.</returns>
- ///<param name="newExpression">A <see cref="T:System.Linq.Expressions.NewExpression" /> to set the <see cref="P:System.Linq.Expressions.MemberInitExpression.NewExpression" /> property equal to.</param>
- ///<param name="bindings">An array of <see cref="T:System.Linq.Expressions.MemberBinding" /> objects to use to populate the <see cref="P:System.Linq.Expressions.MemberInitExpression.Bindings" /> collection.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="newExpression" /> or <paramref name="bindings" /> is null.</exception>
- ///<exception cref="T:System.ArgumentException">The <see cref="P:System.Linq.Expressions.MemberBinding.Member" /> property of an element of <paramref name="bindings" /> does not represent a member of the type that <paramref name="newExpression" />.Type represents.</exception>
- public static MemberInitExpression MemberInit(NewExpression newExpression, params MemberBinding[] bindings) {
- return MemberInit(newExpression, (IEnumerable<MemberBinding>)bindings);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MemberInitExpression" />.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MemberInitExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.MemberInit" /> and the <see cref="P:System.Linq.Expressions.MemberInitExpression.NewExpression" /> and <see cref="P:System.Linq.Expressions.MemberInitExpression.Bindings" /> properties set to the specified values.</returns>
- ///<param name="newExpression">A <see cref="T:System.Linq.Expressions.NewExpression" /> to set the <see cref="P:System.Linq.Expressions.MemberInitExpression.NewExpression" /> property equal to.</param>
- ///<param name="bindings">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> that contains <see cref="T:System.Linq.Expressions.MemberBinding" /> objects to use to populate the <see cref="P:System.Linq.Expressions.MemberInitExpression.Bindings" /> collection.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="newExpression" /> or <paramref name="bindings" /> is null.</exception>
- ///<exception cref="T:System.ArgumentException">The <see cref="P:System.Linq.Expressions.MemberBinding.Member" /> property of an element of <paramref name="bindings" /> does not represent a member of the type that <paramref name="newExpression" />.Type represents.</exception>
- public static MemberInitExpression MemberInit(NewExpression newExpression, IEnumerable<MemberBinding> bindings) {
- ContractUtils.RequiresNotNull(newExpression, "newExpression");
- ContractUtils.RequiresNotNull(bindings, "bindings");
- var roBindings = bindings.ToReadOnly();
- ValidateMemberInitArgs(newExpression.Type, roBindings);
- return new MemberInitExpression(newExpression, roBindings);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberListBinding.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberListBinding.cs
deleted file mode 100644
index 52774f06e4d..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberListBinding.cs
+++ /dev/null
@@ -1,137 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Dynamic.Utils;
-using System.Reflection;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- /// <summary>
- /// Represents initializing the elements of a collection member of a newly created object.
- /// </summary>
- public sealed class MemberListBinding : MemberBinding {
- ReadOnlyCollection<ElementInit> _initializers;
- internal MemberListBinding(MemberInfo member, ReadOnlyCollection<ElementInit> initializers)
-#pragma warning disable 618
- : base(MemberBindingType.ListBinding, member) {
-#pragma warning restore 618
- _initializers = initializers;
- }
-
- /// <summary>
- /// Gets the element initializers for initializing a collection member of a newly created object.
- /// </summary>
- public ReadOnlyCollection<ElementInit> Initializers {
- get { return _initializers; }
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="initializers">The <see cref="Initializers" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public MemberListBinding Update(IEnumerable<ElementInit> initializers) {
- if (initializers == Initializers) {
- return this;
- }
- return Expression.ListBind(Member, initializers);
- }
- }
-
-
- public partial class Expression {
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MemberListBinding" /> where the member is a field or property.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MemberListBinding" /> that has the <see cref="P:System.Linq.Expressions.MemberBinding.BindingType" /> property equal to <see cref="F:System.Linq.Expressions.MemberBindingType.ListBinding" /> and the <see cref="P:System.Linq.Expressions.MemberBinding.Member" /> and <see cref="P:System.Linq.Expressions.MemberListBinding.Initializers" /> properties set to the specified values.</returns>
- ///<param name="member">A <see cref="T:System.Reflection.MemberInfo" /> that represents a field or property to set the <see cref="P:System.Linq.Expressions.MemberBinding.Member" /> property equal to.</param>
- ///<param name="initializers">An array of <see cref="T:System.Linq.Expressions.ElementInit" /> objects to use to populate the <see cref="P:System.Linq.Expressions.MemberListBinding.Initializers" /> collection.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="member" /> is null. -or-One or more elements of <paramref name="initializers" /> is null.</exception>
- ///<exception cref="T:System.ArgumentException">
- ///<paramref name="member" /> does not represent a field or property.-or-The <see cref="P:System.Reflection.FieldInfo.FieldType" /> or <see cref="P:System.Reflection.PropertyInfo.PropertyType" /> of the field or property that <paramref name="member" /> represents does not implement <see cref="T:System.Collections.IEnumerable" />.</exception>
- public static MemberListBinding ListBind(MemberInfo member, params ElementInit[] initializers) {
- ContractUtils.RequiresNotNull(member, "member");
- ContractUtils.RequiresNotNull(initializers, "initializers");
- return ListBind(member, (IEnumerable<ElementInit>)initializers);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MemberListBinding" /> where the member is a field or property.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MemberListBinding" /> that has the <see cref="P:System.Linq.Expressions.MemberBinding.BindingType" /> property equal to <see cref="F:System.Linq.Expressions.MemberBindingType.ListBinding" /> and the <see cref="P:System.Linq.Expressions.MemberBinding.Member" /> and <see cref="P:System.Linq.Expressions.MemberListBinding.Initializers" /> properties set to the specified values.</returns>
- ///<param name="member">A <see cref="T:System.Reflection.MemberInfo" /> that represents a field or property to set the <see cref="P:System.Linq.Expressions.MemberBinding.Member" /> property equal to.</param>
- ///<param name="initializers">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> that contains <see cref="T:System.Linq.Expressions.ElementInit" /> objects to use to populate the <see cref="P:System.Linq.Expressions.MemberListBinding.Initializers" /> collection.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="member" /> is null. -or-One or more elements of <paramref name="initializers" /> is null.</exception>
- ///<exception cref="T:System.ArgumentException">
- ///<paramref name="member" /> does not represent a field or property.-or-The <see cref="P:System.Reflection.FieldInfo.FieldType" /> or <see cref="P:System.Reflection.PropertyInfo.PropertyType" /> of the field or property that <paramref name="member" /> represents does not implement <see cref="T:System.Collections.IEnumerable" />.</exception>
- public static MemberListBinding ListBind(MemberInfo member, IEnumerable<ElementInit> initializers) {
- ContractUtils.RequiresNotNull(member, "member");
- ContractUtils.RequiresNotNull(initializers, "initializers");
- Type memberType;
- ValidateGettableFieldOrPropertyMember(member, out memberType);
- var initList = initializers.ToReadOnly();
- ValidateListInitArgs(memberType, initList);
- return new MemberListBinding(member, initList);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MemberListBinding" /> object based on a specified property accessor method.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MemberListBinding" /> that has the <see cref="P:System.Linq.Expressions.MemberBinding.BindingType" /> property equal to <see cref="F:System.Linq.Expressions.MemberBindingType.ListBinding" />, the <see cref="P:System.Linq.Expressions.MemberBinding.Member" /> property set to the <see cref="T:System.Reflection.MemberInfo" /> that represents the property accessed in <paramref name="propertyAccessor" />, and <see cref="P:System.Linq.Expressions.MemberListBinding.Initializers" /> populated with the elements of <paramref name="initializers" />.</returns>
- ///<param name="propertyAccessor">A <see cref="T:System.Reflection.MethodInfo" /> that represents a property accessor method.</param>
- ///<param name="initializers">An array of <see cref="T:System.Linq.Expressions.ElementInit" /> objects to use to populate the <see cref="P:System.Linq.Expressions.MemberListBinding.Initializers" /> collection.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="propertyAccessor" /> is null. -or-One or more elements of <paramref name="initializers" /> is null.</exception>
- ///<exception cref="T:System.ArgumentException">
- ///<paramref name="propertyAccessor" /> does not represent a property accessor method.-or-The <see cref="P:System.Reflection.PropertyInfo.PropertyType" /> of the property that the method represented by <paramref name="propertyAccessor" /> accesses does not implement <see cref="T:System.Collections.IEnumerable" />.</exception>
- public static MemberListBinding ListBind(MethodInfo propertyAccessor, params ElementInit[] initializers) {
- ContractUtils.RequiresNotNull(propertyAccessor, "propertyAccessor");
- ContractUtils.RequiresNotNull(initializers, "initializers");
- return ListBind(propertyAccessor, (IEnumerable<ElementInit>)initializers);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MemberListBinding" /> based on a specified property accessor method.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MemberListBinding" /> that has the <see cref="P:System.Linq.Expressions.MemberBinding.BindingType" /> property equal to <see cref="F:System.Linq.Expressions.MemberBindingType.ListBinding" />, the <see cref="P:System.Linq.Expressions.MemberBinding.Member" /> property set to the <see cref="T:System.Reflection.MemberInfo" /> that represents the property accessed in <paramref name="propertyAccessor" />, and <see cref="P:System.Linq.Expressions.MemberListBinding.Initializers" /> populated with the elements of <paramref name="initializers" />.</returns>
- ///<param name="propertyAccessor">A <see cref="T:System.Reflection.MethodInfo" /> that represents a property accessor method.</param>
- ///<param name="initializers">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> that contains <see cref="T:System.Linq.Expressions.ElementInit" /> objects to use to populate the <see cref="P:System.Linq.Expressions.MemberListBinding.Initializers" /> collection.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="propertyAccessor" /> is null. -or-One or more elements of <paramref name="initializers" /> are null.</exception>
- ///<exception cref="T:System.ArgumentException">
- ///<paramref name="propertyAccessor" /> does not represent a property accessor method.-or-The <see cref="P:System.Reflection.PropertyInfo.PropertyType" /> of the property that the method represented by <paramref name="propertyAccessor" /> accesses does not implement <see cref="T:System.Collections.IEnumerable" />.</exception>
- public static MemberListBinding ListBind(MethodInfo propertyAccessor, IEnumerable<ElementInit> initializers) {
- ContractUtils.RequiresNotNull(propertyAccessor, "propertyAccessor");
- ContractUtils.RequiresNotNull(initializers, "initializers");
- return ListBind(GetProperty(propertyAccessor), initializers);
- }
-
- private static void ValidateListInitArgs(Type listType, ReadOnlyCollection<ElementInit> initializers) {
- if (!typeof(IEnumerable).IsAssignableFrom(listType)) {
- throw Error.TypeNotIEnumerable(listType);
- }
- for (int i = 0, n = initializers.Count; i < n; i++) {
- ElementInit element = initializers[i];
- ContractUtils.RequiresNotNull(element, "initializers");
- ValidateCallInstanceType(listType, element.AddMethod);
- }
- }
- }
-} \ No newline at end of file
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberMemberBinding.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberMemberBinding.cs
deleted file mode 100644
index 6a54633c933..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberMemberBinding.cs
+++ /dev/null
@@ -1,151 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Dynamic.Utils;
-using System.Reflection;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents initializing members of a member of a newly created object.
- /// </summary>
- /// <remarks>
- /// Use the <see cref="M:MemberBind"/> factory methods to create a <see cref="MemberMemberBinding"/>.
- /// The value of the <see cref="P:MemberBinding.BindingType"/> property of a <see cref="MemberMemberBinding"/> object is <see cref="MemberBinding"/>.
- /// </remarks>
- public sealed class MemberMemberBinding : MemberBinding {
- ReadOnlyCollection<MemberBinding> _bindings;
- internal MemberMemberBinding(MemberInfo member, ReadOnlyCollection<MemberBinding> bindings)
-#pragma warning disable 618
- : base(MemberBindingType.MemberBinding, member) {
-#pragma warning restore 618
- _bindings = bindings;
- }
-
- /// <summary>
- /// Gets the bindings that describe how to initialize the members of a member.
- /// </summary>
- public ReadOnlyCollection<MemberBinding> Bindings {
- get { return _bindings; }
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="bindings">The <see cref="Bindings" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public MemberMemberBinding Update(IEnumerable<MemberBinding> bindings) {
- if (bindings == Bindings) {
- return this;
- }
- return Expression.MemberBind(Member, bindings);
- }
- }
-
-
- public partial class Expression {
- /// <summary>
- /// Creates a <see cref="MemberMemberBinding"/> that represents the recursive initialization of members of a field or property.
- /// </summary>
- /// <param name="member">The <see cref="MemberInfo"/> to set the <see cref="P:MemberBinding.Member"/> property equal to.</param>
- /// <param name="bindings">An array of <see cref="MemberBinding"/> objects to use to populate the <see cref="P:MemberMemberBindings.Bindings"/> collection.</param>
- /// <returns>A <see cref="MemberMemberBinding"/> that has the <see cref="P:MemberBinding.BindingType"/> property equal to <see cref="MemberBinding"/> and the <see cref="P:MemberBinding.Member"/> and <see cref="P:MemberMemberBindings.Bindings"/> properties set to the specified values.</returns>
- public static MemberMemberBinding MemberBind(MemberInfo member, params MemberBinding[] bindings) {
- ContractUtils.RequiresNotNull(member, "member");
- ContractUtils.RequiresNotNull(bindings, "bindings");
- return MemberBind(member, (IEnumerable<MemberBinding>)bindings);
- }
-
- /// <summary>
- /// Creates a <see cref="MemberMemberBinding"/> that represents the recursive initialization of members of a field or property.
- /// </summary>
- /// <param name="member">The <see cref="MemberInfo"/> to set the <see cref="P:MemberBinding.Member"/> property equal to.</param>
- /// <param name="bindings">An <see cref="IEnumerable{T}"/> that contains <see cref="MemberBinding"/> objects to use to populate the <see cref="P:MemberMemberBindings.Bindings"/> collection.</param>
- /// <returns>A <see cref="MemberMemberBinding"/> that has the <see cref="P:MemberBinding.BindingType"/> property equal to <see cref="MemberBinding"/> and the <see cref="P:MemberBinding.Member"/> and <see cref="P:MemberMemberBindings.Bindings"/> properties set to the specified values.</returns>
- public static MemberMemberBinding MemberBind(MemberInfo member, IEnumerable<MemberBinding> bindings) {
- ContractUtils.RequiresNotNull(member, "member");
- ContractUtils.RequiresNotNull(bindings, "bindings");
- ReadOnlyCollection<MemberBinding> roBindings = bindings.ToReadOnly();
- Type memberType;
- ValidateGettableFieldOrPropertyMember(member, out memberType);
- ValidateMemberInitArgs(memberType, roBindings);
- return new MemberMemberBinding(member, roBindings);
- }
-
- /// <summary>
- /// Creates a <see cref="MemberMemberBinding"/> that represents the recursive initialization of members of a member that is accessed by using a property accessor method.
- /// </summary>
- /// <param name="propertyAccessor">The <see cref="MemberInfo"/> that represents a property accessor method.</param>
- /// <param name="bindings">An <see cref="IEnumerable{T}"/> that contains <see cref="MemberBinding"/> objects to use to populate the <see cref="P:MemberMemberBindings.Bindings"/> collection.</param>
- /// <returns>
- /// A <see cref="MemberMemberBinding"/> that has the <see cref="P:MemberBinding.BindingType"/> property equal to <see cref="MemberBinding"/>,
- /// the Member property set to the <see cref="PropertyInfo"/> that represents the property accessed in <paramref name="propertyAccessor"/>,
- /// and <see cref="P:MemberMemberBindings.Bindings"/> properties set to the specified values.
- /// </returns>
- public static MemberMemberBinding MemberBind(MethodInfo propertyAccessor, params MemberBinding[] bindings) {
- ContractUtils.RequiresNotNull(propertyAccessor, "propertyAccessor");
- return MemberBind(GetProperty(propertyAccessor), bindings);
- }
-
- /// <summary>
- /// Creates a <see cref="MemberMemberBinding"/> that represents the recursive initialization of members of a member that is accessed by using a property accessor method.
- /// </summary>
- /// <param name="propertyAccessor">The <see cref="MemberInfo"/> that represents a property accessor method.</param>
- /// <param name="bindings">An <see cref="IEnumerable{T}"/> that contains <see cref="MemberBinding"/> objects to use to populate the <see cref="P:MemberMemberBindings.Bindings"/> collection.</param>
- /// <returns>
- /// A <see cref="MemberMemberBinding"/> that has the <see cref="P:MemberBinding.BindingType"/> property equal to <see cref="MemberBinding"/>,
- /// the Member property set to the <see cref="PropertyInfo"/> that represents the property accessed in <paramref name="propertyAccessor"/>,
- /// and <see cref="P:MemberMemberBindings.Bindings"/> properties set to the specified values.
- /// </returns>
- public static MemberMemberBinding MemberBind(MethodInfo propertyAccessor, IEnumerable<MemberBinding> bindings) {
- ContractUtils.RequiresNotNull(propertyAccessor, "propertyAccessor");
- return MemberBind(GetProperty(propertyAccessor), bindings);
- }
-
- private static void ValidateGettableFieldOrPropertyMember(MemberInfo member, out Type memberType) {
- FieldInfo fi = member as FieldInfo;
- if (fi == null) {
- PropertyInfo pi = member as PropertyInfo;
- if (pi == null) {
- throw Error.ArgumentMustBeFieldInfoOrPropertInfo();
- }
- if (!pi.CanRead) {
- throw Error.PropertyDoesNotHaveGetter(pi);
- }
- memberType = pi.PropertyType;
- } else {
- memberType = fi.FieldType;
- }
- }
-
- private static void ValidateMemberInitArgs(Type type, ReadOnlyCollection<MemberBinding> bindings) {
- for (int i = 0, n = bindings.Count; i < n; i++) {
- MemberBinding b = bindings[i];
- ContractUtils.RequiresNotNull(b, "bindings");
- if (!b.Member.DeclaringType.IsAssignableFrom(type)) {
- throw Error.NotAMemberOfType(b.Member.Name, type);
- }
- }
- }
- }
-} \ No newline at end of file
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MethodCallExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MethodCallExpression.cs
deleted file mode 100644
index 1656811de99..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/MethodCallExpression.cs
+++ /dev/null
@@ -1,1041 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents a call to either static or an instance method.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.MethodCallExpressionProxy))]
- public class MethodCallExpression : Expression, IArgumentProvider {
- private readonly MethodInfo _method;
-
- internal MethodCallExpression(MethodInfo method) {
-
- _method = method;
- }
-
- internal virtual Expression GetInstance() {
- return null;
- }
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Call; }
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return _method.ReturnType; }
- }
-
- /// <summary>
- /// Gets the <see cref="MethodInfo" /> for the method to be called.
- /// </summary>
- public MethodInfo Method {
- get { return _method; }
- }
-
- /// <summary>
- /// Gets the <see cref="Expression" /> that represents the instance
- /// for instance method calls or null for static method cals.
- /// </summary>
- public Expression Object {
- get { return GetInstance(); }
- }
-
- /// <summary>
- /// Gets a collection of expressions that represent arguments to the method call.
- /// </summary>
- public ReadOnlyCollection<Expression> Arguments {
- get { return GetOrMakeArguments(); }
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="object">The <see cref="Object" /> property of the result.</param>
- /// <param name="arguments">The <see cref="Arguments" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public MethodCallExpression Update(Expression @object, IEnumerable<Expression> arguments) {
- if (@object == Object && arguments == Arguments) {
- return this;
- }
- return Expression.Call(@object, Method, arguments);
- }
-
- internal virtual ReadOnlyCollection<Expression> GetOrMakeArguments() {
- throw ContractUtils.Unreachable;
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitMethodCall(this);
- }
-
- /// <summary>
- /// Returns a new MethodCallExpression replacing the existing instance/args with the
- /// newly provided instance and args. Arguments can be null to use the existing
- /// arguments.
- ///
- /// This helper is provided to allow re-writing of nodes to not depend on the specific optimized
- /// subclass of MethodCallExpression which is being used.
- /// </summary>
- internal virtual MethodCallExpression Rewrite(Expression instance, IList<Expression> args) {
- throw ContractUtils.Unreachable;
- }
-
- #region IArgumentProvider Members
-
- Expression IArgumentProvider.GetArgument(int index) {
- throw ContractUtils.Unreachable;
- }
-
- int IArgumentProvider.ArgumentCount {
- get { throw ContractUtils.Unreachable; }
- }
-
- #endregion
- }
-
- #region Specialized Subclasses
-
- internal class MethodCallExpressionN : MethodCallExpression, IArgumentProvider {
- private IList<Expression> _arguments;
-
- public MethodCallExpressionN(MethodInfo method, IList<Expression> args)
- : base(method) {
- _arguments = args;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- return _arguments[index];
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return _arguments.Count;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(ref _arguments);
- }
-
- internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args) {
- Debug.Assert(instance == null);
- Debug.Assert(args == null || args.Count == _arguments.Count);
-
- return Expression.Call(Method, args ?? _arguments);
- }
- }
-
- internal class InstanceMethodCallExpressionN : MethodCallExpression, IArgumentProvider {
- private IList<Expression> _arguments;
- private readonly Expression _instance;
-
- public InstanceMethodCallExpressionN(MethodInfo method, Expression instance, IList<Expression> args)
- : base(method) {
- _instance = instance;
- _arguments = args;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- return _arguments[index];
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return _arguments.Count;
- }
- }
-
- internal override Expression GetInstance() {
- return _instance;
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(ref _arguments);
- }
-
- internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args) {
- Debug.Assert(instance != null);
- Debug.Assert(args == null || args.Count == _arguments.Count);
-
- return Expression.Call(instance, Method, args ?? _arguments);
- }
- }
-
- internal class MethodCallExpression1 : MethodCallExpression, IArgumentProvider {
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
-
- public MethodCallExpression1(MethodInfo method, Expression arg0)
- : base(method) {
- _arg0 = arg0;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- default: throw new InvalidOperationException();
- }
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return 1;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(this, ref _arg0);
- }
-
- internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args) {
- Debug.Assert(instance == null);
- Debug.Assert(args == null || args.Count == 1);
-
- if (args != null) {
- return Expression.Call(Method, args[0]);
- }
-
- return Expression.Call(Method, ReturnObject<Expression>(_arg0));
- }
- }
-
- internal class MethodCallExpression2 : MethodCallExpression, IArgumentProvider {
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
- private readonly Expression _arg1; // storage for the 2nd arg
-
- public MethodCallExpression2(MethodInfo method, Expression arg0, Expression arg1)
- : base(method) {
- _arg0 = arg0;
- _arg1 = arg1;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- case 1: return _arg1;
- default: throw new InvalidOperationException();
- }
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return 2;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(this, ref _arg0);
- }
-
- internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args) {
- Debug.Assert(instance == null);
- Debug.Assert(args == null || args.Count == 2);
-
- if (args != null) {
- return Expression.Call(Method, args[0], args[1]);
- }
- return Expression.Call(Method, ReturnObject<Expression>(_arg0), _arg1);
- }
- }
-
- internal class MethodCallExpression3 : MethodCallExpression, IArgumentProvider {
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
- private readonly Expression _arg1, _arg2; // storage for the 2nd - 3rd args.
-
- public MethodCallExpression3(MethodInfo method, Expression arg0, Expression arg1, Expression arg2)
- : base(method) {
- _arg0 = arg0;
- _arg1 = arg1;
- _arg2 = arg2;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- case 1: return _arg1;
- case 2: return _arg2;
- default: throw new InvalidOperationException();
- }
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return 3;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(this, ref _arg0);
- }
-
- internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args) {
- Debug.Assert(instance == null);
- Debug.Assert(args == null || args.Count == 3);
-
- if (args != null) {
- return Expression.Call(Method, args[0], args[1], args[2]);
- }
- return Expression.Call(Method, ReturnObject<Expression>(_arg0), _arg1, _arg2);
- }
- }
-
- internal class MethodCallExpression4 : MethodCallExpression, IArgumentProvider {
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
- private readonly Expression _arg1, _arg2, _arg3; // storage for the 2nd - 4th args.
-
- public MethodCallExpression4(MethodInfo method, Expression arg0, Expression arg1, Expression arg2, Expression arg3)
- : base(method) {
- _arg0 = arg0;
- _arg1 = arg1;
- _arg2 = arg2;
- _arg3 = arg3;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- case 1: return _arg1;
- case 2: return _arg2;
- case 3: return _arg3;
- default: throw new InvalidOperationException();
- }
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return 4;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(this, ref _arg0);
- }
-
- internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args) {
- Debug.Assert(instance == null);
- Debug.Assert(args == null || args.Count == 4);
-
- if (args != null) {
- return Expression.Call(Method, args[0], args[1], args[2], args[3]);
- }
- return Expression.Call(Method, ReturnObject<Expression>(_arg0), _arg1, _arg2, _arg3);
- }
- }
-
- internal class MethodCallExpression5 : MethodCallExpression, IArgumentProvider {
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
- private readonly Expression _arg1, _arg2, _arg3, _arg4; // storage for the 2nd - 5th args.
-
- public MethodCallExpression5(MethodInfo method, Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4)
- : base(method) {
- _arg0 = arg0;
- _arg1 = arg1;
- _arg2 = arg2;
- _arg3 = arg3;
- _arg4 = arg4;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- case 1: return _arg1;
- case 2: return _arg2;
- case 3: return _arg3;
- case 4: return _arg4;
- default: throw new InvalidOperationException();
- }
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return 5;
- }
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(this, ref _arg0);
- }
-
- internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args) {
- Debug.Assert(instance == null);
- Debug.Assert(args == null || args.Count == 5);
-
- if (args != null) {
- return Expression.Call(Method, args[0], args[1], args[2], args[3], args[4]);
- }
-
- return Expression.Call(Method, ReturnObject<Expression>(_arg0), _arg1, _arg2, _arg3, _arg4);
- }
- }
-
- internal class InstanceMethodCallExpression2 : MethodCallExpression, IArgumentProvider {
- private readonly Expression _instance;
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
- private readonly Expression _arg1; // storage for the 2nd argument
-
- public InstanceMethodCallExpression2(MethodInfo method, Expression instance, Expression arg0, Expression arg1)
- : base(method) {
- Debug.Assert(instance != null);
-
- _instance = instance;
- _arg0 = arg0;
- _arg1 = arg1;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- case 1: return _arg1;
- default: throw new InvalidOperationException();
- }
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return 2;
- }
- }
-
- internal override Expression GetInstance() {
- return _instance;
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(this, ref _arg0);
- }
-
- internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args) {
- Debug.Assert(instance != null);
- Debug.Assert(args == null || args.Count == 2);
-
- if (args != null) {
- return Expression.Call(instance, Method, args[0], args[1]);
- }
- return Expression.Call(instance, Method, ReturnObject<Expression>(_arg0), _arg1);
- }
- }
-
- internal class InstanceMethodCallExpression3 : MethodCallExpression, IArgumentProvider {
- private readonly Expression _instance;
- private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
- private readonly Expression _arg1, _arg2; // storage for the 2nd - 3rd argument
-
- public InstanceMethodCallExpression3(MethodInfo method, Expression instance, Expression arg0, Expression arg1, Expression arg2)
- : base(method) {
- Debug.Assert(instance != null);
-
- _instance = instance;
- _arg0 = arg0;
- _arg1 = arg1;
- _arg2 = arg2;
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- switch (index) {
- case 0: return ReturnObject<Expression>(_arg0);
- case 1: return _arg1;
- case 2: return _arg2;
- default: throw new InvalidOperationException();
- }
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return 3;
- }
- }
-
- internal override Expression GetInstance() {
- return _instance;
- }
-
- internal override ReadOnlyCollection<Expression> GetOrMakeArguments() {
- return ReturnReadOnly(this, ref _arg0);
- }
-
- internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args) {
- Debug.Assert(instance != null);
- Debug.Assert(args == null || args.Count == 3);
-
- if (args != null) {
- return Expression.Call(instance, Method, args[0], args[1], args[2]);
- }
- return Expression.Call(instance, Method, ReturnObject<Expression>(_arg0), _arg1, _arg2);
- }
- }
-
- #endregion
-
- public partial class Expression {
-
- #region Call
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to a static method that takes one argument.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property equal to.</param>
- ///<param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="method" /> is null.</exception>
- public static MethodCallExpression Call(MethodInfo method, Expression arg0) {
- ContractUtils.RequiresNotNull(method, "method");
- ContractUtils.RequiresNotNull(arg0, "arg0");
-
- ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method);
-
- ValidateArgumentCount(method, ExpressionType.Call, 1, pis);
-
- arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
-
- return new MethodCallExpression1(method, arg0);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to a static method that takes two arguments.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property equal to.</param>
- ///<param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
- ///<param name="arg1">The <see cref="Expression" /> that represents the second argument.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="method" /> is null.</exception>
- public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expression arg1) {
- ContractUtils.RequiresNotNull(method, "method");
- ContractUtils.RequiresNotNull(arg0, "arg0");
- ContractUtils.RequiresNotNull(arg1, "arg1");
-
- ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method);
-
- ValidateArgumentCount(method, ExpressionType.Call, 2, pis);
-
- arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
- arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1]);
-
- return new MethodCallExpression2(method, arg0, arg1);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to a static method that takes three arguments.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property equal to.</param>
- ///<param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
- ///<param name="arg1">The <see cref="Expression" /> that represents the second argument.</param>
- ///<param name="arg2">The <see cref="Expression" /> that represents the third argument.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="method" /> is null.</exception>
- public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expression arg1, Expression arg2) {
- ContractUtils.RequiresNotNull(method, "method");
- ContractUtils.RequiresNotNull(arg0, "arg0");
- ContractUtils.RequiresNotNull(arg1, "arg1");
- ContractUtils.RequiresNotNull(arg2, "arg2");
-
- ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method);
-
- ValidateArgumentCount(method, ExpressionType.Call, 3, pis);
-
- arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
- arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1]);
- arg2 = ValidateOneArgument(method, ExpressionType.Call, arg2, pis[2]);
-
- return new MethodCallExpression3(method, arg0, arg1, arg2);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to a static method that takes four arguments.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property equal to.</param>
- ///<param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
- ///<param name="arg1">The <see cref="Expression" /> that represents the second argument.</param>
- ///<param name="arg2">The <see cref="Expression" /> that represents the third argument.</param>
- ///<param name="arg3">The <see cref="Expression" /> that represents the fourth argument.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="method" /> is null.</exception>
- public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expression arg1, Expression arg2, Expression arg3) {
- ContractUtils.RequiresNotNull(method, "method");
- ContractUtils.RequiresNotNull(arg0, "arg0");
- ContractUtils.RequiresNotNull(arg1, "arg1");
- ContractUtils.RequiresNotNull(arg2, "arg2");
- ContractUtils.RequiresNotNull(arg3, "arg3");
-
- ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method);
-
- ValidateArgumentCount(method, ExpressionType.Call, 4, pis);
-
- arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
- arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1]);
- arg2 = ValidateOneArgument(method, ExpressionType.Call, arg2, pis[2]);
- arg3 = ValidateOneArgument(method, ExpressionType.Call, arg3, pis[3]);
-
- return new MethodCallExpression4(method, arg0, arg1, arg2, arg3);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to a static method that takes five arguments.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property equal to.</param>
- ///<param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
- ///<param name="arg1">The <see cref="Expression" /> that represents the second argument.</param>
- ///<param name="arg2">The <see cref="Expression" /> that represents the third argument.</param>
- ///<param name="arg3">The <see cref="Expression" /> that represents the fourth argument.</param>
- ///<param name="arg4">The <see cref="Expression" /> that represents the fifth argument.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="method" /> is null.</exception>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
- public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) {
- ContractUtils.RequiresNotNull(method, "method");
- ContractUtils.RequiresNotNull(arg0, "arg0");
- ContractUtils.RequiresNotNull(arg1, "arg1");
- ContractUtils.RequiresNotNull(arg2, "arg2");
- ContractUtils.RequiresNotNull(arg3, "arg3");
- ContractUtils.RequiresNotNull(arg4, "arg4");
-
- ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method);
-
- ValidateArgumentCount(method, ExpressionType.Call, 5, pis);
-
- arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
- arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1]);
- arg2 = ValidateOneArgument(method, ExpressionType.Call, arg2, pis[2]);
- arg3 = ValidateOneArgument(method, ExpressionType.Call, arg3, pis[3]);
- arg4 = ValidateOneArgument(method, ExpressionType.Call, arg4, pis[4]);
-
- return new MethodCallExpression5(method, arg0, arg1, arg2, arg3, arg4);
- }
-
- /// <summary>
- /// Creates a <see cref="MethodCallExpression" /> that represents a call to a static (Shared in Visual Basic) method.
- /// </summary>
- /// <param name="method">The <see cref="MethodInfo" /> that represents the target method.</param>
- /// <param name="arguments">The array of one or more of <see cref="Expression" /> that represents the call arguments.</param>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
- public static MethodCallExpression Call(MethodInfo method, params Expression[] arguments) {
- return Call(null, method, arguments);
- }
-
- /// <summary>
- /// Creates a <see cref="MethodCallExpression" /> that represents a call to a static (Shared in Visual Basic) method.
- /// </summary>
- /// <param name="method">The <see cref="MethodInfo" /> that represents the target method.</param>
- /// <param name="arguments">A collection of <see cref="Expression" /> that represents the call arguments.</param>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
- public static MethodCallExpression Call(MethodInfo method, IEnumerable<Expression> arguments) {
- return Call(null, method, arguments);
- }
-
- /// <summary>
- /// Creates a <see cref="MethodCallExpression" /> that represents a call to a method that takes no arguments.
- /// </summary>
- /// <param name="instance">An <see cref="Expression" /> that specifies the instance for an instance call. (pass null for a static (Shared in Visual Basic) method).</param>
- /// <param name="method">The <see cref="MethodInfo" /> that represents the target method.</param>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
- public static MethodCallExpression Call(Expression instance, MethodInfo method) {
- return Call(instance, method, EmptyReadOnlyCollection<Expression>.Instance);
- }
-
- /// <summary>
- /// Creates a <see cref="MethodCallExpression" /> that represents a method call.
- /// </summary>
- /// <param name="instance">An <see cref="Expression" /> that specifies the instance for an instance call. (pass null for a static (Shared in Visual Basic) method).</param>
- /// <param name="method">The <see cref="MethodInfo" /> that represents the target method.</param>
- /// <param name="arguments">An array of one or more of <see cref="Expression" /> that represents the call arguments.</param>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
- public static MethodCallExpression Call(Expression instance, MethodInfo method, params Expression[] arguments) {
- return Call(instance, method, (IEnumerable<Expression>)arguments);
- }
-
- /// <summary>
- /// Creates a <see cref="MethodCallExpression" /> that represents a call to a method that takes two arguments.
- /// </summary>
- /// <param name="instance">An <see cref="Expression" /> that specifies the instance for an instance call. (pass null for a static (Shared in Visual Basic) method).</param>
- /// <param name="method">The <see cref="MethodInfo" /> that represents the target method.</param>
- /// <param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
- /// <param name="arg1">The <see cref="Expression" /> that represents the second argument.</param>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
- public static MethodCallExpression Call(Expression instance, MethodInfo method, Expression arg0, Expression arg1) {
- ContractUtils.RequiresNotNull(method, "method");
- ContractUtils.RequiresNotNull(arg0, "arg0");
- ContractUtils.RequiresNotNull(arg1, "arg1");
-
- ParameterInfo[] pis = ValidateMethodAndGetParameters(instance, method);
-
- ValidateArgumentCount(method, ExpressionType.Call, 2, pis);
-
- arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
- arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1]);
-
- if (instance != null) {
- return new InstanceMethodCallExpression2(method, instance, arg0, arg1);
- }
-
- return new MethodCallExpression2(method, arg0, arg1);
- }
-
- /// <summary>
- /// Creates a <see cref="MethodCallExpression" /> that represents a call to a method that takes three arguments.
- /// </summary>
- /// <param name="instance">An <see cref="Expression" /> that specifies the instance for an instance call. (pass null for a static (Shared in Visual Basic) method).</param>
- /// <param name="method">The <see cref="MethodInfo" /> that represents the target method.</param>
- /// <param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
- /// <param name="arg1">The <see cref="Expression" /> that represents the second argument.</param>
- /// <param name="arg2">The <see cref="Expression" /> that represents the third argument.</param>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
- public static MethodCallExpression Call(Expression instance, MethodInfo method, Expression arg0, Expression arg1, Expression arg2) {
- ContractUtils.RequiresNotNull(method, "method");
- ContractUtils.RequiresNotNull(arg0, "arg0");
- ContractUtils.RequiresNotNull(arg1, "arg1");
- ContractUtils.RequiresNotNull(arg2, "arg2");
-
- ParameterInfo[] pis = ValidateMethodAndGetParameters(instance, method);
-
- ValidateArgumentCount(method, ExpressionType.Call, 3, pis);
-
- arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
- arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1]);
- arg2 = ValidateOneArgument(method, ExpressionType.Call, arg2, pis[2]);
-
- if (instance != null) {
- return new InstanceMethodCallExpression3(method, instance, arg0, arg1, arg2);
- }
- return new MethodCallExpression3(method, arg0, arg1, arg2);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to an instance method by calling the appropriate factory method.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" />, the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> property equal to <paramref name="instance" />, <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> set to the <see cref="T:System.Reflection.MethodInfo" /> that represents the specified instance method, and <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> set to the specified arguments.</returns>
- ///<param name="instance">An <see cref="T:System.Linq.Expressions.Expression" /> whose <see cref="P:System.Linq.Expressions.Expression.Type" /> property value will be searched for a specific method.</param>
- ///<param name="methodName">The name of the method.</param>
- ///<param name="typeArguments">
- ///An array of <see cref="T:System.Type" /> objects that specify the type parameters of the generic method.
- ///This argument should be null when <paramref name="methodName" /> specifies a non-generic method.
- ///</param>
- ///<param name="arguments">An array of <see cref="T:System.Linq.Expressions.Expression" /> objects that represents the arguments to the method.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="instance" /> or <paramref name="methodName" /> is null.</exception>
- ///<exception cref="T:System.InvalidOperationException">No method whose name is <paramref name="methodName" />, whose type parameters match <paramref name="typeArguments" />, and whose parameter types match <paramref name="arguments" /> is found in <paramref name="instance" />.Type or its base types.-or-More than one method whose name is <paramref name="methodName" />, whose type parameters match <paramref name="typeArguments" />, and whose parameter types match <paramref name="arguments" /> is found in <paramref name="instance" />.Type or its base types.</exception>
- public static MethodCallExpression Call(Expression instance, string methodName, Type[] typeArguments, params Expression[] arguments) {
- ContractUtils.RequiresNotNull(instance, "instance");
- ContractUtils.RequiresNotNull(methodName, "methodName");
- if (arguments == null) {
- arguments = new Expression[0];
- }
-
- BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
- return Expression.Call(instance, FindMethod(instance.Type, methodName, typeArguments, arguments, flags), arguments);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to a static (Shared in Visual Basic) method by calling the appropriate factory method.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" />, the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property set to the <see cref="T:System.Reflection.MethodInfo" /> that represents the specified static (Shared in Visual Basic) method, and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> property set to the specified arguments.</returns>
- ///<param name="type">The <see cref="T:System.Type" /> that specifies the type that contains the specified static (Shared in Visual Basic) method.</param>
- ///<param name="methodName">The name of the method.</param>
- ///<param name="typeArguments">
- ///An array of <see cref="T:System.Type" /> objects that specify the type parameters of the generic method.
- ///This argument should be null when <paramref name="methodName" /> specifies a non-generic method.
- ///</param>
- ///<param name="arguments">An array of <see cref="T:System.Linq.Expressions.Expression" /> objects that represent the arguments to the method.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="type" /> or <paramref name="methodName" /> is null.</exception>
- ///<exception cref="T:System.InvalidOperationException">No method whose name is <paramref name="methodName" />, whose type parameters match <paramref name="typeArguments" />, and whose parameter types match <paramref name="arguments" /> is found in <paramref name="type" /> or its base types.-or-More than one method whose name is <paramref name="methodName" />, whose type parameters match <paramref name="typeArguments" />, and whose parameter types match <paramref name="arguments" /> is found in <paramref name="type" /> or its base types.</exception>
- public static MethodCallExpression Call(Type type, string methodName, Type[] typeArguments, params Expression[] arguments) {
- ContractUtils.RequiresNotNull(type, "type");
- ContractUtils.RequiresNotNull(methodName, "methodName");
-
- if (arguments == null) arguments = new Expression[] { };
- BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
- return Expression.Call(null, FindMethod(type, methodName, typeArguments, arguments, flags), arguments);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a method call.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" />, <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" />, and <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> properties set to the specified values.</returns>
- ///<param name="instance">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> property equal to (pass null for a static (Shared in Visual Basic) method).</param>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property equal to.</param>
- ///<param name="arguments">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> that contains <see cref="T:System.Linq.Expressions.Expression" /> objects to use to populate the <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> collection.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="method" /> is null.-or-<paramref name="instance" /> is null and <paramref name="method" /> represents an instance method.</exception>
- ///<exception cref="T:System.ArgumentException">
- ///<paramref name="instance" />.Type is not assignable to the declaring type of the method represented by <paramref name="method" />.-or-The number of elements in <paramref name="arguments" /> does not equal the number of parameters for the method represented by <paramref name="method" />.-or-One or more of the elements of <paramref name="arguments" /> is not assignable to the corresponding parameter for the method represented by <paramref name="method" />.</exception>
- public static MethodCallExpression Call(Expression instance, MethodInfo method, IEnumerable<Expression> arguments) {
- ContractUtils.RequiresNotNull(method, "method");
-
- ReadOnlyCollection<Expression> argList = arguments.ToReadOnly();
-
- ValidateMethodInfo(method);
- ValidateStaticOrInstanceMethod(instance, method);
- ValidateArgumentTypes(method, ExpressionType.Call, ref argList);
-
- if (instance == null) {
- return new MethodCallExpressionN(method, argList);
- } else {
- return new InstanceMethodCallExpressionN(method, instance, argList);
- }
- }
-
- private static ParameterInfo[] ValidateMethodAndGetParameters(Expression instance, MethodInfo method) {
- ValidateMethodInfo(method);
- ValidateStaticOrInstanceMethod(instance, method);
-
- return GetParametersForValidation(method, ExpressionType.Call);
- }
-
- private static void ValidateStaticOrInstanceMethod(Expression instance, MethodInfo method) {
- if (method.IsStatic) {
- if (instance != null) throw new ArgumentException(Strings.OnlyStaticMethodsHaveNullInstance, "instance");
- } else {
- if (instance == null) throw new ArgumentException(Strings.OnlyStaticMethodsHaveNullInstance, "method");
- RequiresCanRead(instance, "instance");
- ValidateCallInstanceType(instance.Type, method);
- }
- }
-
- private static void ValidateCallInstanceType(Type instanceType, MethodInfo method) {
- if (!TypeUtils.IsValidInstanceType(method, instanceType)) {
- throw Error.InstanceAndMethodTypeMismatch(method, method.DeclaringType, instanceType);
- }
- }
-
- private static void ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ref ReadOnlyCollection<Expression> arguments) {
- Debug.Assert(nodeKind == ExpressionType.Invoke || nodeKind == ExpressionType.Call || nodeKind == ExpressionType.Dynamic || nodeKind == ExpressionType.New);
-
- ParameterInfo[] pis = GetParametersForValidation(method, nodeKind);
-
- ValidateArgumentCount(method, nodeKind, arguments.Count, pis);
-
- Expression[] newArgs = null;
- for (int i = 0, n = pis.Length; i < n; i++) {
- Expression arg = arguments[i];
- ParameterInfo pi = pis[i];
- arg = ValidateOneArgument(method, nodeKind, arg, pi);
-
- if (newArgs == null && arg != arguments[i]) {
- newArgs = new Expression[arguments.Count];
- for (int j = 0; j < i; j++) {
- newArgs[j] = arguments[j];
- }
- }
- if (newArgs != null) {
- newArgs[i] = arg;
- }
- }
- if (newArgs != null) {
- arguments = new TrueReadOnlyCollection<Expression>(newArgs);
- }
- }
-
- private static ParameterInfo[] GetParametersForValidation(MethodBase method, ExpressionType nodeKind) {
- ParameterInfo[] pis = method.GetParametersCached();
-
- if (nodeKind == ExpressionType.Dynamic) {
- pis = pis.RemoveFirst(); // ignore CallSite argument
- }
- return pis;
- }
-
- private static void ValidateArgumentCount(MethodBase method, ExpressionType nodeKind, int count, ParameterInfo[] pis) {
- if (pis.Length != count) {
- // Throw the right error for the node we were given
- switch (nodeKind) {
- case ExpressionType.New:
- throw Error.IncorrectNumberOfConstructorArguments();
- case ExpressionType.Invoke:
- throw Error.IncorrectNumberOfLambdaArguments();
- case ExpressionType.Dynamic:
- case ExpressionType.Call:
- throw Error.IncorrectNumberOfMethodCallArguments(method);
- default:
- throw ContractUtils.Unreachable;
- }
- }
- }
-
- private static Expression ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arg, ParameterInfo pi) {
- RequiresCanRead(arg, "arguments");
- Type pType = pi.ParameterType;
- if (pType.IsByRef) {
- pType = pType.GetElementType();
- }
- TypeUtils.ValidateType(pType);
- if (!TypeUtils.AreReferenceAssignable(pType, arg.Type)) {
- if (!TryQuote(pType, ref arg)) {
- // Throw the right error for the node we were given
- switch (nodeKind) {
- case ExpressionType.New:
- throw Error.ExpressionTypeDoesNotMatchConstructorParameter(arg.Type, pType);
- case ExpressionType.Invoke:
- throw Error.ExpressionTypeDoesNotMatchParameter(arg.Type, pType);
- case ExpressionType.Dynamic:
- case ExpressionType.Call:
- throw Error.ExpressionTypeDoesNotMatchMethodParameter(arg.Type, pType, method);
- default:
- throw ContractUtils.Unreachable;
- }
- }
- }
- return arg;
- }
-
- // Attempts to auto-quote the expression tree. Returns true if it succeeded, false otherwise.
- private static bool TryQuote(Type parameterType, ref Expression argument) {
- // We used to allow quoting of any expression, but the behavior of
- // quote (produce a new tree closed over parameter values), only
- // works consistently for lambdas
- Type quoteable = typeof(LambdaExpression);
- if (TypeUtils.IsSameOrSubclass(quoteable, parameterType) &&
- parameterType.IsAssignableFrom(argument.GetType())) {
- argument = Expression.Quote(argument);
- return true;
- }
- return false;
- }
-
- private static MethodInfo FindMethod(Type type, string methodName, Type[] typeArgs, Expression[] args, BindingFlags flags) {
- MemberInfo[] members = type.FindMembers(MemberTypes.Method, flags, Type.FilterNameIgnoreCase, methodName);
- if (members == null || members.Length == 0)
- throw Error.MethodDoesNotExistOnType(methodName, type);
-
- MethodInfo method;
-
- var methodInfos = members.Map(t => (MethodInfo)t);
- int count = FindBestMethod(methodInfos, typeArgs, args, out method);
-
- if (count == 0) {
- if (typeArgs != null && typeArgs.Length > 0) {
- throw Error.GenericMethodWithArgsDoesNotExistOnType(methodName, type);
- } else {
- throw Error.MethodWithArgsDoesNotExistOnType(methodName, type);
- }
- }
- if (count > 1)
- throw Error.MethodWithMoreThanOneMatch(methodName, type);
- return method;
- }
-
- private static int FindBestMethod(IEnumerable<MethodInfo> methods, Type[] typeArgs, Expression[] args, out MethodInfo method) {
- int count = 0;
- method = null;
- foreach (MethodInfo mi in methods) {
- MethodInfo moo = ApplyTypeArgs(mi, typeArgs);
- if (moo != null && IsCompatible(moo, args)) {
- // favor public over non-public methods
- if (method == null || (!method.IsPublic && moo.IsPublic)) {
- method = moo;
- count = 1;
- }
- // only count it as additional method if they both public or both non-public
- else if (method.IsPublic == moo.IsPublic) {
- count++;
- }
- }
- }
- return count;
- }
-
- private static bool IsCompatible(MethodBase m, Expression[] args) {
- ParameterInfo[] parms = m.GetParametersCached();
- if (parms.Length != args.Length)
- return false;
- for (int i = 0; i < args.Length; i++) {
- Expression arg = args[i];
- ContractUtils.RequiresNotNull(arg, "argument");
- Type argType = arg.Type;
- Type pType = parms[i].ParameterType;
- if (pType.IsByRef) {
- pType = pType.GetElementType();
- }
- if (!TypeUtils.AreReferenceAssignable(pType, argType) &&
- !(TypeUtils.IsSameOrSubclass(typeof(LambdaExpression), pType) && pType.IsAssignableFrom(arg.GetType()))) {
- return false;
- }
- }
- return true;
- }
-
- private static MethodInfo ApplyTypeArgs(MethodInfo m, Type[] typeArgs) {
- if (typeArgs == null || typeArgs.Length == 0) {
- if (!m.IsGenericMethodDefinition)
- return m;
- } else {
- if (m.IsGenericMethodDefinition && m.GetGenericArguments().Length == typeArgs.Length)
- return m.MakeGenericMethod(typeArgs);
- }
- return null;
- }
-
-
- #endregion
-
- #region ArrayIndex
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents applying an array index operator to a multi-dimensional array.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.BinaryExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.ArrayIndex" /> and the <see cref="P:System.Linq.Expressions.BinaryExpression.Left" /> and <see cref="P:System.Linq.Expressions.BinaryExpression.Right" /> properties set to the specified values.</returns>
- ///<param name="array">An array of <see cref="T:System.Linq.Expressions.Expression" /> instances - indexes for the array index operation.</param>
- ///<param name="indexes">An array that contains <see cref="T:System.Linq.Expressions.Expression" /> objects to use to populate the <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> collection.</param>
- public static MethodCallExpression ArrayIndex(Expression array, params Expression[] indexes) {
- return ArrayIndex(array, (IEnumerable<Expression>)indexes);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents applying an array index operator to an array of rank more than one.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> properties set to the specified values.</returns>
- ///<param name="array">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> property equal to.</param>
- ///<param name="indexes">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> that contains <see cref="T:System.Linq.Expressions.Expression" /> objects to use to populate the <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> collection.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="array" /> or <paramref name="indexes" /> is null.</exception>
- ///<exception cref="T:System.ArgumentException">
- ///<paramref name="array" />.Type does not represent an array type.-or-The rank of <paramref name="array" />.Type does not match the number of elements in <paramref name="indexes" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of one or more elements of <paramref name="indexes" /> does not represent the <see cref="T:System.Int32" /> type.</exception>
- public static MethodCallExpression ArrayIndex(Expression array, IEnumerable<Expression> indexes) {
- RequiresCanRead(array, "array");
- ContractUtils.RequiresNotNull(indexes, "indexes");
-
- Type arrayType = array.Type;
- if (!arrayType.IsArray) {
- throw Error.ArgumentMustBeArray();
- }
-
- ReadOnlyCollection<Expression> indexList = indexes.ToReadOnly();
- if (arrayType.GetArrayRank() != indexList.Count) {
- throw Error.IncorrectNumberOfIndexes();
- }
-
- foreach (Expression e in indexList) {
- RequiresCanRead(e, "indexes");
- if (e.Type != typeof(int)) {
- throw Error.ArgumentMustBeArrayIndexType();
- }
- }
-
- MethodInfo mi = array.Type.GetMethod("Get", BindingFlags.Public | BindingFlags.Instance);
- return Call(array, mi, indexList);
- }
-
- #endregion
-
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/NewArrayExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/NewArrayExpression.cs
deleted file mode 100644
index d8bf56adea8..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/NewArrayExpression.cs
+++ /dev/null
@@ -1,234 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- /// <summary>
- /// Represents creating a new array and possibly initializing the elements of the new array.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.NewArrayExpressionProxy))]
- public class NewArrayExpression : Expression {
- private readonly ReadOnlyCollection<Expression> _expressions;
- private readonly Type _type;
-
- internal NewArrayExpression(Type type, ReadOnlyCollection<Expression> expressions) {
- _expressions = expressions;
- _type = type;
- }
-
- internal static NewArrayExpression Make(ExpressionType nodeType, Type type, ReadOnlyCollection<Expression> expressions) {
- if (nodeType == ExpressionType.NewArrayInit) {
- return new NewArrayInitExpression(type, expressions);
- } else {
- return new NewArrayBoundsExpression(type, expressions);
- }
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return _type; }
- }
-
- /// <summary>
- /// Gets the bounds of the array if the value of the <see cref="P:NodeType"/> property is NewArrayBounds, or the values to initialize the elements of the new array if the value of the <see cref="P:NodeType"/> property is NewArrayInit.
- /// </summary>
- public ReadOnlyCollection<Expression> Expressions {
- get { return _expressions; }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitNewArray(this);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="expressions">The <see cref="Expressions" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public NewArrayExpression Update(IEnumerable<Expression> expressions) {
- if (expressions == Expressions) {
- return this;
- }
- if (NodeType == ExpressionType.NewArrayInit) {
- return Expression.NewArrayInit(Type.GetElementType(), expressions);
- }
- return Expression.NewArrayBounds(Type.GetElementType(), expressions);
- }
- }
-
- internal sealed class NewArrayInitExpression : NewArrayExpression {
- internal NewArrayInitExpression(Type type, ReadOnlyCollection<Expression> expressions)
- : base(type, expressions) {
- }
-
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.NewArrayInit; }
- }
- }
-
- internal sealed class NewArrayBoundsExpression : NewArrayExpression {
- internal NewArrayBoundsExpression(Type type, ReadOnlyCollection<Expression> expressions)
- : base(type, expressions) {
- }
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.NewArrayBounds; }
- }
- }
-
- public partial class Expression {
-
- #region NewArrayInit
-
-
- /// <summary>
- /// Creates a new array expression of the specified type from the provided initializers.
- /// </summary>
- /// <param name="type">A Type that represents the element type of the array.</param>
- /// <param name="initializers">The expressions used to create the array elements.</param>
- /// <returns>An instance of the <see cref="NewArrayExpression"/>.</returns>
- public static NewArrayExpression NewArrayInit(Type type, params Expression[] initializers) {
- return NewArrayInit(type, (IEnumerable<Expression>)initializers);
- }
-
- /// <summary>
- /// Creates a new array expression of the specified type from the provided initializers.
- /// </summary>
- /// <param name="type">A Type that represents the element type of the array.</param>
- /// <param name="initializers">The expressions used to create the array elements.</param>
- /// <returns>An instance of the <see cref="NewArrayExpression"/>.</returns>
- public static NewArrayExpression NewArrayInit(Type type, IEnumerable<Expression> initializers) {
- ContractUtils.RequiresNotNull(type, "type");
- ContractUtils.RequiresNotNull(initializers, "initializers");
- if (type.Equals(typeof(void))) {
- throw Error.ArgumentCannotBeOfTypeVoid();
- }
-
- ReadOnlyCollection<Expression> initializerList = initializers.ToReadOnly();
-
- Expression[] newList = null;
- for (int i = 0, n = initializerList.Count; i < n; i++) {
- Expression expr = initializerList[i];
- RequiresCanRead(expr, "initializers");
-
- if (!TypeUtils.AreReferenceAssignable(type, expr.Type)) {
- if (!TryQuote(type, ref expr)){
- throw Error.ExpressionTypeCannotInitializeArrayType(expr.Type, type);
- }
- if (newList == null) {
- newList = new Expression[initializerList.Count];
- for (int j = 0; j < i; j++) {
- newList[j] = initializerList[j];
- }
- }
- }
- if (newList != null) {
- newList[i] = expr;
- }
- }
- if (newList != null) {
- initializerList = new TrueReadOnlyCollection<Expression>(newList);
- }
-
- return NewArrayExpression.Make(ExpressionType.NewArrayInit, type.MakeArrayType(), initializerList);
- }
-
- #endregion
-
- #region NewArrayBounds
-
-
- /// <summary>
- /// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank.
- /// </summary>
- /// <param name="type">A <see cref="Type"/> that represents the element type of the array.</param>
- /// <param name="bounds">An array that contains Expression objects to use to populate the Expressions collection.</param>
- /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="P:NodeType"/> property equal to type and the <see cref="P:Expressions"/> property set to the specified value.</returns>
- public static NewArrayExpression NewArrayBounds(Type type, params Expression[] bounds) {
- return NewArrayBounds(type, (IEnumerable<Expression>)bounds);
- }
-
-
- /// <summary>
- /// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank.
- /// </summary>
- /// <param name="type">A <see cref="Type"/> that represents the element type of the array.</param>
- /// <param name="bounds">An IEnumerable{T} that contains Expression objects to use to populate the Expressions collection.</param>
- /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="P:NodeType"/> property equal to type and the <see cref="P:Expressions"/> property set to the specified value.</returns>
- public static NewArrayExpression NewArrayBounds(Type type, IEnumerable<Expression> bounds) {
- ContractUtils.RequiresNotNull(type, "type");
- ContractUtils.RequiresNotNull(bounds, "bounds");
-
- if (type.Equals(typeof(void))) {
- throw Error.ArgumentCannotBeOfTypeVoid();
- }
-
- ReadOnlyCollection<Expression> boundsList = bounds.ToReadOnly();
-
- int dimensions = boundsList.Count;
- if (dimensions <= 0) throw Error.BoundsCannotBeLessThanOne();
-
- for (int i = 0; i < dimensions; i++) {
- Expression expr = boundsList[i];
- RequiresCanRead(expr, "bounds");
- if (!TypeUtils.IsInteger(expr.Type)) {
- throw Error.ArgumentMustBeInteger();
- }
- }
-
- Type arrayType;
- if (dimensions == 1) {
- //To get a vector, need call Type.MakeArrayType().
- //Type.MakeArrayType(1) gives a non-vector array, which will cause type check error.
- arrayType = type.MakeArrayType();
- } else {
- arrayType = type.MakeArrayType(dimensions);
- }
-
- return NewArrayExpression.Make(ExpressionType.NewArrayBounds, arrayType, bounds.ToReadOnly());
- }
-
- #endregion
-
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/NewExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/NewExpression.cs
deleted file mode 100644
index 9a60fa44285..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/NewExpression.cs
+++ /dev/null
@@ -1,326 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-//using Microsoft.Scripting.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents a constructor call.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.NewExpressionProxy))]
- public class NewExpression : Expression, IArgumentProvider {
- private readonly ConstructorInfo _constructor;
- private IList<Expression> _arguments;
- private readonly ReadOnlyCollection<MemberInfo> _members;
-
- internal NewExpression(ConstructorInfo constructor, IList<Expression> arguments, ReadOnlyCollection<MemberInfo> members) {
- _constructor = constructor;
- _arguments = arguments;
- _members = members;
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public override Type Type {
- get { return _constructor.DeclaringType; }
- }
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.New; }
- }
-
- /// <summary>
- /// Gets the called constructor.
- /// </summary>
- public ConstructorInfo Constructor {
- get { return _constructor; }
- }
-
- /// <summary>
- /// Gets the arguments to the constructor.
- /// </summary>
- public ReadOnlyCollection<Expression> Arguments {
- get { return ReturnReadOnly(ref _arguments); }
- }
-
- Expression IArgumentProvider.GetArgument(int index) {
- return _arguments[index];
- }
-
- int IArgumentProvider.ArgumentCount {
- get {
- return _arguments.Count;
- }
- }
-
- /// <summary>
- /// Gets the members that can retrieve the values of the fields that were initialized with constructor arguments.
- /// </summary>
- public ReadOnlyCollection<MemberInfo> Members {
- get { return _members; }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitNew(this);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="arguments">The <see cref="Arguments" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public NewExpression Update(IEnumerable<Expression> arguments) {
- if (arguments == Arguments) {
- return this;
- }
- if (Members != null) {
- return Expression.New(Constructor, arguments, Members);
- }
- return Expression.New(Constructor, arguments);
- }
- }
-
- internal class NewValueTypeExpression : NewExpression {
- private readonly Type _valueType;
-
- internal NewValueTypeExpression(Type type, ReadOnlyCollection<Expression> arguments, ReadOnlyCollection<MemberInfo> members)
- : base(null, arguments, members) {
- _valueType = type;
- }
-
- public sealed override Type Type {
- get { return _valueType; }
- }
- }
-
- public partial class Expression {
-
- /// <summary>
- /// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments.
- /// </summary>
- /// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
- /// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> property set to the specified value.</returns>
- public static NewExpression New(ConstructorInfo constructor) {
- return New(constructor, (IEnumerable<Expression>)null);
- }
-
-
- /// <summary>
- /// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments.
- /// </summary>
- /// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
- /// <param name="arguments">An array of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
- /// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> and <see cref="P:Arguments"/> properties set to the specified value.</returns>
- public static NewExpression New(ConstructorInfo constructor, params Expression[] arguments) {
- return New(constructor, (IEnumerable<Expression>)arguments);
- }
-
-
- /// <summary>
- /// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments.
- /// </summary>
- /// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
- /// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
- /// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> and <see cref="P:Arguments"/> properties set to the specified value.</returns>
- public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments) {
- ContractUtils.RequiresNotNull(constructor, "constructor");
- ContractUtils.RequiresNotNull(constructor.DeclaringType, "constructor.DeclaringType");
- TypeUtils.ValidateType(constructor.DeclaringType);
- var argList = arguments.ToReadOnly();
- ValidateArgumentTypes(constructor, ExpressionType.New, ref argList);
-
- return new NewExpression(constructor, argList, null);
- }
-
-
- /// <summary>
- /// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor with the specified arguments. The members that access the constructor initialized fields are specified.
- /// </summary>
- /// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
- /// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
- /// <param name="members">An <see cref="IEnumerable{T}"/> of <see cref="MemberInfo"/> objects to use to populate the Members collection.</param>
- /// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/>, <see cref="P:Arguments"/> and <see cref="P:Members"/> properties set to the specified value.</returns>
- public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments, IEnumerable<MemberInfo> members) {
- ContractUtils.RequiresNotNull(constructor, "constructor");
- var memberList = members.ToReadOnly();
- var argList = arguments.ToReadOnly();
- ValidateNewArgs(constructor, ref argList, ref memberList);
- return new NewExpression(constructor, argList, memberList);
- }
-
-
- /// <summary>
- /// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor with the specified arguments. The members that access the constructor initialized fields are specified.
- /// </summary>
- /// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
- /// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
- /// <param name="members">An Array of <see cref="MemberInfo"/> objects to use to populate the Members collection.</param>
- /// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/>, <see cref="P:Arguments"/> and <see cref="P:Members"/> properties set to the specified value.</returns>
- public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments, params MemberInfo[] members) {
- return New(constructor, arguments, (IEnumerable<MemberInfo>)members);
- }
-
-
- /// <summary>
- /// Creates a <see cref="NewExpression"/> that represents calling the parameterless constructor of the specified type.
- /// </summary>
- /// <param name="type">A <see cref="Type"/> that has a constructor that takes no arguments. </param>
- /// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to New and the Constructor property set to the ConstructorInfo that represents the parameterless constructor of the specified type.</returns>
- public static NewExpression New(Type type) {
- ContractUtils.RequiresNotNull(type, "type");
- if (type == typeof(void)) {
- throw Error.ArgumentCannotBeOfTypeVoid();
- }
- ConstructorInfo ci = null;
- if (!type.IsValueType) {
- ci = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Microsoft.Scripting.Utils.ReflectionUtils.EmptyTypes, null);
- if (ci == null) {
- throw Error.TypeMissingDefaultConstructor(type);
- }
- return New(ci);
- }
- return new NewValueTypeExpression(type, EmptyReadOnlyCollection<Expression>.Instance, null);
- }
-
-
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- private static void ValidateNewArgs(ConstructorInfo constructor, ref ReadOnlyCollection<Expression> arguments, ref ReadOnlyCollection<MemberInfo> members) {
- ParameterInfo[] pis;
- if ((pis = constructor.GetParametersCached()).Length > 0) {
- if (arguments.Count != pis.Length) {
- throw Error.IncorrectNumberOfConstructorArguments();
- }
- if (arguments.Count != members.Count) {
- throw Error.IncorrectNumberOfArgumentsForMembers();
- }
- Expression[] newArguments = null;
- MemberInfo[] newMembers = null;
- for (int i = 0, n = arguments.Count; i < n; i++) {
- Expression arg = arguments[i];
- RequiresCanRead(arg, "argument");
- MemberInfo member = members[i];
- ContractUtils.RequiresNotNull(member, "member");
- if (!TypeUtils.AreEquivalent(member.DeclaringType, constructor.DeclaringType)) {
- throw Error.ArgumentMemberNotDeclOnType(member.Name, constructor.DeclaringType.Name);
- }
- Type memberType;
- ValidateAnonymousTypeMember(ref member, out memberType);
- if (!TypeUtils.AreReferenceAssignable(memberType, arg.Type)) {
- if (!TryQuote(memberType, ref arg)) {
- throw Error.ArgumentTypeDoesNotMatchMember(arg.Type, memberType);
- }
- }
- ParameterInfo pi = pis[i];
- Type pType = pi.ParameterType;
- if (pType.IsByRef) {
- pType = pType.GetElementType();
- }
- if (!TypeUtils.AreReferenceAssignable(pType, arg.Type)) {
- if (!TryQuote(pType, ref arg)) {
- throw Error.ExpressionTypeDoesNotMatchConstructorParameter(arg.Type, pType);
- }
- }
- if (newArguments == null && arg != arguments[i]) {
- newArguments = new Expression[arguments.Count];
- for (int j = 0; j < i; j++) {
- newArguments[j] = arguments[j];
- }
- }
- if (newArguments != null) {
- newArguments[i] = arg;
- }
-
- if (newMembers == null && member != members[i]) {
- newMembers = new MemberInfo[members.Count];
- for (int j = 0; j < i; j++) {
- newMembers[j] = members[j];
- }
- }
- if (newMembers != null) {
- newMembers[i] = member;
- }
- }
- if (newArguments != null) {
- arguments = new TrueReadOnlyCollection<Expression>(newArguments);
- }
- if (newMembers != null) {
- members = new TrueReadOnlyCollection<MemberInfo>(newMembers);
- }
- } else if (arguments != null && arguments.Count > 0) {
- throw Error.IncorrectNumberOfConstructorArguments();
- } else if (members != null && members.Count > 0) {
- throw Error.IncorrectNumberOfMembersForGivenConstructor();
- }
- }
-
-
- private static void ValidateAnonymousTypeMember(ref MemberInfo member, out Type memberType) {
- switch (member.MemberType) {
- case MemberTypes.Field:
- FieldInfo field = member as FieldInfo;
- if (field.IsStatic) {
- throw Error.ArgumentMustBeInstanceMember();
- }
- memberType = field.FieldType;
- return;
- case MemberTypes.Property:
- PropertyInfo pi = member as PropertyInfo;
- if (!pi.CanRead) {
- throw Error.PropertyDoesNotHaveGetter(pi);
- }
- if (pi.GetGetMethod().IsStatic) {
- throw Error.ArgumentMustBeInstanceMember();
- }
- memberType = pi.PropertyType;
- return;
- case MemberTypes.Method:
- MethodInfo method = member as MethodInfo;
- if (method.IsStatic) {
- throw Error.ArgumentMustBeInstanceMember();
- }
- PropertyInfo prop = GetProperty(method);
- member = prop;
- memberType = prop.PropertyType;
- return;
- default:
- throw Error.ArgumentMustBeFieldInfoOrPropertInfoOrMethod();
- }
- // don't add code here, we've already returned
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ParameterExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ParameterExpression.cs
deleted file mode 100644
index 42a8628181a..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/ParameterExpression.cs
+++ /dev/null
@@ -1,222 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- /// <summary>
- /// Represents a named parameter expression.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.ParameterExpressionProxy))]
- public class ParameterExpression : Expression {
- private readonly string _name;
-
- internal ParameterExpression(string name) {
- _name = name;
- }
-
- internal static ParameterExpression Make(Type type, string name, bool isByRef) {
- if (isByRef) {
- return new ByRefParameterExpression(type, name);
- } else {
- if (!type.IsEnum) {
- switch (Type.GetTypeCode(type)) {
- case TypeCode.Boolean: return new PrimitiveParameterExpression<Boolean>(name);
- case TypeCode.Byte: return new PrimitiveParameterExpression<Byte>(name);
- case TypeCode.Char: return new PrimitiveParameterExpression<Char>(name);
- case TypeCode.DateTime: return new PrimitiveParameterExpression<DateTime>(name);
- case TypeCode.DBNull: return new PrimitiveParameterExpression<DBNull>(name);
- case TypeCode.Decimal: return new PrimitiveParameterExpression<Decimal>(name);
- case TypeCode.Double: return new PrimitiveParameterExpression<Double>(name);
- case TypeCode.Int16: return new PrimitiveParameterExpression<Int16>(name);
- case TypeCode.Int32: return new PrimitiveParameterExpression<Int32>(name);
- case TypeCode.Int64: return new PrimitiveParameterExpression<Int64>(name);
- case TypeCode.Object:
- // common reference types which we optimize go here. Of course object is in
- // the list, the others are driven by profiling of various workloads. This list
- // should be kept short.
- if (type == typeof(object)) {
- return new ParameterExpression(name);
- } else if (type == typeof(Exception)) {
- return new PrimitiveParameterExpression<Exception>(name);
- } else if (type == typeof(object[])) {
- return new PrimitiveParameterExpression<object[]>(name);
- }
- break;
- case TypeCode.SByte: return new PrimitiveParameterExpression<SByte>(name);
- case TypeCode.Single: return new PrimitiveParameterExpression<Single>(name);
- case TypeCode.String: return new PrimitiveParameterExpression<String>(name);
- case TypeCode.UInt16: return new PrimitiveParameterExpression<UInt16>(name);
- case TypeCode.UInt32: return new PrimitiveParameterExpression<UInt32>(name);
- case TypeCode.UInt64: return new PrimitiveParameterExpression<UInt64>(name);
- }
- }
- }
-
- return new TypedParameterExpression(type, name);
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public override Type Type {
- get { return typeof(object); }
- }
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Parameter; }
- }
-
- /// <summary>
- /// The Name of the parameter or variable.
- /// </summary>
- public string Name {
- get { return _name; }
- }
-
- /// <summary>
- /// Indicates that this ParameterExpression is to be treated as a ByRef parameter.
- /// </summary>
- public bool IsByRef {
- get {
- return GetIsByRef();
- }
- }
-
- internal virtual bool GetIsByRef() {
- return false;
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitParameter(this);
- }
- }
-
- /// <summary>
- /// Specialized subclass to avoid holding onto the byref flag in a
- /// parameter expression. This version always holds onto the expression
- /// type explicitly and therefore derives from TypedParameterExpression.
- /// </summary>
- internal sealed class ByRefParameterExpression : TypedParameterExpression {
- internal ByRefParameterExpression(Type type, string name)
- : base(type, name) {
- }
-
- internal override bool GetIsByRef() {
- return true;
- }
- }
-
- /// <summary>
- /// Specialized subclass which holds onto the type of the expression for
- /// uncommon types.
- /// </summary>
- internal class TypedParameterExpression : ParameterExpression {
- private readonly Type _paramType;
-
- internal TypedParameterExpression(Type type, string name)
- : base(name) {
- _paramType = type;
- }
-
- public sealed override Type Type {
- get { return _paramType; }
- }
- }
-
- /// <summary>
- /// Generic type to avoid needing explicit storage for primitive data types
- /// which are commonly used.
- /// </summary>
- internal sealed class PrimitiveParameterExpression<T> : ParameterExpression {
- internal PrimitiveParameterExpression(string name)
- : base(name) {
- }
-
- public sealed override Type Type {
- get { return typeof(T); }
- }
- }
-
- public partial class Expression {
-
- /// <summary>
- /// Creates a <see cref="ParameterExpression" /> node that can be used to identify a parameter or a variable in an expression tree.
- /// </summary>
- /// <param name="type">The type of the parameter or variable.</param>
- /// <returns>A <see cref="ParameterExpression" /> node with the specified name and type.</returns>
- public static ParameterExpression Parameter(Type type) {
- return Parameter(type, null);
- }
-
- /// <summary>
- /// Creates a <see cref="ParameterExpression" /> node that can be used to identify a parameter or a variable in an expression tree.
- /// </summary>
- /// <param name="type">The type of the parameter or variable.</param>
- /// <returns>A <see cref="ParameterExpression" /> node with the specified name and type.</returns>
- public static ParameterExpression Variable(Type type) {
- return Variable(type, null);
- }
-
- /// <summary>
- /// Creates a <see cref="ParameterExpression" /> node that can be used to identify a parameter or a variable in an expression tree.
- /// </summary>
- /// <param name="type">The type of the parameter or variable.</param>
- /// <param name="name">The name of the parameter or variable, used for debugging or pretty printing purpose only.</param>
- /// <returns>A <see cref="ParameterExpression" /> node with the specified name and type.</returns>
- public static ParameterExpression Parameter(Type type, string name) {
- ContractUtils.RequiresNotNull(type, "type");
-
- if (type == typeof(void)) {
- throw Error.ArgumentCannotBeOfTypeVoid();
- }
-
- bool byref = type.IsByRef;
- if (byref) {
- type = type.GetElementType();
- }
-
- return ParameterExpression.Make(type, name, byref);
- }
-
- /// <summary>
- /// Creates a <see cref="ParameterExpression" /> node that can be used to identify a parameter or a variable in an expression tree.
- /// </summary>
- /// <param name="type">The type of the parameter or variable.</param>
- /// <param name="name">The name of the parameter or variable, used for debugging or pretty printing purpose only.</param>
- /// <returns>A <see cref="ParameterExpression" /> node with the specified name and type.</returns>
- public static ParameterExpression Variable(Type type, string name) {
- ContractUtils.RequiresNotNull(type, "type");
- if (type == typeof(void)) throw Error.ArgumentCannotBeOfTypeVoid();
- if (type.IsByRef) throw Error.TypeMustNotBeByRef();
- return ParameterExpression.Make(type, name, false);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/RuntimeVariablesExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/RuntimeVariablesExpression.cs
deleted file mode 100644
index a79b12657e3..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/RuntimeVariablesExpression.cs
+++ /dev/null
@@ -1,117 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// An expression that provides runtime read/write access to variables.
- /// Needed to implement "eval" in some dynamic languages.
- /// Evaluates to an instance of <see cref="IList{IStrongBox}" /> when executed.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.RuntimeVariablesExpressionProxy))]
- public sealed class RuntimeVariablesExpression : Expression {
- private readonly ReadOnlyCollection<ParameterExpression> _variables;
-
- internal RuntimeVariablesExpression(ReadOnlyCollection<ParameterExpression> variables) {
- _variables = variables;
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents.
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return typeof(IRuntimeVariables); }
- }
-
- /// <summary>
- /// Returns the node type of this Expression. Extension nodes should return
- /// ExpressionType.Extension when overriding this method.
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.RuntimeVariables; }
- }
-
- /// <summary>
- /// The variables or parameters to which to provide runtime access.
- /// </summary>
- public ReadOnlyCollection<ParameterExpression> Variables {
- get { return _variables; }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitRuntimeVariables(this);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="variables">The <see cref="Variables" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public RuntimeVariablesExpression Update(IEnumerable<ParameterExpression> variables) {
- if (variables == Variables) {
- return this;
- }
- return Expression.RuntimeVariables(variables);
- }
- }
-
- public partial class Expression {
-
- /// <summary>
- /// Creates an instance of <see cref="T:System.Linq.Expressions.RuntimeVariablesExpression" />.
- /// </summary>
- /// <param name="variables">An array of <see cref="T:System.Linq.Expressions.ParameterExpression" /> objects to use to populate the <see cref="P:System.Linq.Expressions.RuntimeVariablesExpression.Variables" /> collection.</param>
- /// <returns>An instance of <see cref="T:System.Linq.Expressions.RuntimeVariablesExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.RuntimeVariables" /> and the <see cref="P:System.Linq.Expressions.RuntimeVariablesExpression.Variables" /> property set to the specified value.</returns>
- public static RuntimeVariablesExpression RuntimeVariables(params ParameterExpression[] variables) {
- return RuntimeVariables((IEnumerable<ParameterExpression>)variables);
- }
-
- /// <summary>
- /// Creates an instance of <see cref="T:System.Linq.Expressions.RuntimeVariablesExpression" />.
- /// </summary>
- /// <param name="variables">A collection of <see cref="T:System.Linq.Expressions.ParameterExpression" /> objects to use to populate the <see cref="P:System.Linq.Expressions.RuntimeVariablesExpression.Variables" /> collection.</param>
- /// <returns>An instance of <see cref="T:System.Linq.Expressions.RuntimeVariablesExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.RuntimeVariables" /> and the <see cref="P:System.Linq.Expressions.RuntimeVariablesExpression.Variables" /> property set to the specified value.</returns>
- public static RuntimeVariablesExpression RuntimeVariables(IEnumerable<ParameterExpression> variables) {
- ContractUtils.RequiresNotNull(variables, "variables");
-
- var vars = variables.ToReadOnly();
- for (int i = 0; i < vars.Count; i++) {
- Expression v = vars[i];
- if (v == null) {
- throw new ArgumentNullException("variables[" + i + "]");
- }
- }
-
- return new RuntimeVariablesExpression(vars);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/SwitchCase.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/SwitchCase.cs
deleted file mode 100644
index ed080daa52c..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/SwitchCase.cs
+++ /dev/null
@@ -1,105 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents one case of a <see cref="SwitchExpression"/>.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.SwitchCaseProxy))]
- public sealed class SwitchCase {
- private readonly ReadOnlyCollection<Expression> _testValues;
- private readonly Expression _body;
-
- internal SwitchCase(Expression body, ReadOnlyCollection<Expression> testValues) {
- _body = body;
- _testValues = testValues;
- }
-
- /// <summary>
- /// Gets the values of this case. This case is selected for execution when the <see cref="SwitchExpression.SwitchValue"/> matches any of these values.
- /// </summary>
- public ReadOnlyCollection<Expression> TestValues {
- get { return _testValues; }
- }
-
- /// <summary>
- /// Gets the body of this case.
- /// </summary>
- public Expression Body {
- get { return _body; }
- }
-
- /// <summary>
- /// Returns a <see cref="String"/> that represents the current <see cref="Object"/>.
- /// </summary>
- /// <returns>A <see cref="String"/> that represents the current <see cref="Object"/>. </returns>
- public override string ToString() {
- return ExpressionStringBuilder.SwitchCaseToString(this);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="testValues">The <see cref="TestValues" /> property of the result.</param>
- /// <param name="body">The <see cref="Body" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public SwitchCase Update(IEnumerable<Expression> testValues, Expression body) {
- if (testValues == TestValues && body == Body) {
- return this;
- }
- return Expression.SwitchCase(body, testValues);
- }
- }
-
- public partial class Expression {
- /// <summary>
- /// Creates a <see cref="T:SwitchCase">SwitchCase</see> for use in a <see cref="SwitchExpression"/>.
- /// </summary>
- /// <param name="body">The body of the case.</param>
- /// <param name="testValues">The test values of the case.</param>
- /// <returns>The created <see cref="T:SwitchCase">SwitchCase</see>.</returns>
- public static SwitchCase SwitchCase(Expression body, params Expression[] testValues) {
- return SwitchCase(body, (IEnumerable<Expression>)testValues);
- }
-
- /// <summary>
- /// Creates a <see cref="T:SwitchCase">SwitchCase</see> for use in a <see cref="SwitchExpression"/>.
- /// </summary>
- /// <param name="body">The body of the case.</param>
- /// <param name="testValues">The test values of the case.</param>
- /// <returns>The created <see cref="T:SwitchCase">SwitchCase</see>.</returns>
- public static SwitchCase SwitchCase(Expression body, IEnumerable<Expression> testValues) {
- RequiresCanRead(body, "body");
-
- var values = testValues.ToReadOnly();
- RequiresCanRead(values, "testValues");
- ContractUtils.RequiresNotEmpty(values, "testValues");
-
- return new SwitchCase(body, values);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/SwitchExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/SwitchExpression.cs
deleted file mode 100644
index 2bc10185b43..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/SwitchExpression.cs
+++ /dev/null
@@ -1,298 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents a control expression that handles multiple selections by passing control to a <see cref="SwitchCase"/>.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.SwitchExpressionProxy))]
- public sealed class SwitchExpression : Expression {
- private readonly Type _type;
- private readonly Expression _switchValue;
- private readonly ReadOnlyCollection<SwitchCase> _cases;
- private readonly Expression _defaultBody;
- private readonly MethodInfo _comparison;
-
- internal SwitchExpression(Type type, Expression switchValue, Expression defaultBody, MethodInfo comparison, ReadOnlyCollection<SwitchCase> cases) {
- _type = type;
- _switchValue = switchValue;
- _defaultBody = defaultBody;
- _comparison = comparison;
- _cases = cases;
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents.
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return _type; }
- }
-
- /// <summary>
- /// Returns the node type of this Expression. Extension nodes should return
- /// ExpressionType.Extension when overriding this method.
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Switch; }
- }
-
- /// <summary>
- /// Gets the test for the switch.
- /// </summary>
- public Expression SwitchValue {
- get { return _switchValue; }
- }
-
- /// <summary>
- /// Gets the collection of <see cref="SwitchCase"/> objects for the switch.
- /// </summary>
- public ReadOnlyCollection<SwitchCase> Cases {
- get { return _cases; }
- }
-
- /// <summary>
- /// Gets the test for the switch.
- /// </summary>
- public Expression DefaultBody {
- get { return _defaultBody; }
- }
-
- /// <summary>
- /// Gets the equality comparison method, if any.
- /// </summary>
- public MethodInfo Comparison {
- get { return _comparison; }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitSwitch(this);
- }
-
- internal bool IsLifted {
- get {
- if (_switchValue.Type.IsNullableType()) {
- return (_comparison == null) ||
- !TypeUtils.AreEquivalent(_switchValue.Type, _comparison.GetParametersCached()[0].ParameterType.GetNonRefType());
- }
- return false;
- }
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="switchValue">The <see cref="SwitchValue" /> property of the result.</param>
- /// <param name="cases">The <see cref="Cases" /> property of the result.</param>
- /// <param name="defaultBody">The <see cref="DefaultBody" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public SwitchExpression Update(Expression switchValue, IEnumerable<SwitchCase> cases, Expression defaultBody) {
- if (switchValue == SwitchValue && cases == Cases && defaultBody == DefaultBody) {
- return this;
- }
- return Expression.Switch(Type, switchValue, defaultBody, Comparison, cases);
- }
- }
-
- public partial class Expression {
- /// <summary>
- /// Creates a <see cref="SwitchExpression"/>.
- /// </summary>
- /// <param name="switchValue">The value to be tested against each case.</param>
- /// <param name="cases">The valid cases for this switch.</param>
- /// <returns>The created <see cref="SwitchExpression"/>.</returns>
- public static SwitchExpression Switch(Expression switchValue, params SwitchCase[] cases) {
- return Switch(switchValue, null, null, (IEnumerable<SwitchCase>)cases);
- }
-
- /// <summary>
- /// Creates a <see cref="SwitchExpression"/>.
- /// </summary>
- /// <param name="switchValue">The value to be tested against each case.</param>
- /// <param name="defaultBody">The result of the switch if no cases are matched.</param>
- /// <param name="cases">The valid cases for this switch.</param>
- /// <returns>The created <see cref="SwitchExpression"/>.</returns>
- public static SwitchExpression Switch(Expression switchValue, Expression defaultBody, params SwitchCase[] cases) {
- return Switch(switchValue, defaultBody, null, (IEnumerable<SwitchCase>)cases);
- }
-
- /// <summary>
- /// Creates a <see cref="SwitchExpression"/>.
- /// </summary>
- /// <param name="switchValue">The value to be tested against each case.</param>
- /// <param name="defaultBody">The result of the switch if no cases are matched.</param>
- /// <param name="comparison">The equality comparison method to use.</param>
- /// <param name="cases">The valid cases for this switch.</param>
- /// <returns>The created <see cref="SwitchExpression"/>.</returns>
- public static SwitchExpression Switch(Expression switchValue, Expression defaultBody, MethodInfo comparison, params SwitchCase[] cases) {
- return Switch(switchValue, defaultBody, comparison, (IEnumerable<SwitchCase>)cases);
- }
-
- /// <summary>
- /// Creates a <see cref="SwitchExpression"/>.
- /// </summary>
- /// <param name="type">The result type of the switch.</param>
- /// <param name="switchValue">The value to be tested against each case.</param>
- /// <param name="defaultBody">The result of the switch if no cases are matched.</param>
- /// <param name="comparison">The equality comparison method to use.</param>
- /// <param name="cases">The valid cases for this switch.</param>
- /// <returns>The created <see cref="SwitchExpression"/>.</returns>
- public static SwitchExpression Switch(Type type, Expression switchValue, Expression defaultBody, MethodInfo comparison, params SwitchCase[] cases) {
- return Switch(type, switchValue, defaultBody, comparison, (IEnumerable<SwitchCase>)cases);
- }
-
- /// <summary>
- /// Creates a <see cref="SwitchExpression"/>.
- /// </summary>
- /// <param name="switchValue">The value to be tested against each case.</param>
- /// <param name="defaultBody">The result of the switch if no cases are matched.</param>
- /// <param name="comparison">The equality comparison method to use.</param>
- /// <param name="cases">The valid cases for this switch.</param>
- /// <returns>The created <see cref="SwitchExpression"/>.</returns>
- public static SwitchExpression Switch(Expression switchValue, Expression defaultBody, MethodInfo comparison, IEnumerable<SwitchCase> cases) {
- return Switch(null, switchValue, defaultBody, comparison, cases);
- }
-
- /// <summary>
- /// Creates a <see cref="SwitchExpression"/>.
- /// </summary>
- /// <param name="type">The result type of the switch.</param>
- /// <param name="switchValue">The value to be tested against each case.</param>
- /// <param name="defaultBody">The result of the switch if no cases are matched.</param>
- /// <param name="comparison">The equality comparison method to use.</param>
- /// <param name="cases">The valid cases for this switch.</param>
- /// <returns>The created <see cref="SwitchExpression"/>.</returns>
- public static SwitchExpression Switch(Type type, Expression switchValue, Expression defaultBody, MethodInfo comparison, IEnumerable<SwitchCase> cases) {
- RequiresCanRead(switchValue, "switchValue");
- if (switchValue.Type == typeof(void)) throw Error.ArgumentCannotBeOfTypeVoid();
-
- var caseList = cases.ToReadOnly();
- ContractUtils.RequiresNotEmpty(caseList, "cases");
- ContractUtils.RequiresNotNullItems(caseList, "cases");
-
- // Type of the result. Either provided, or it is type of the branches.
- Type resultType = type ?? caseList[0].Body.Type;
- bool customType = type != null;
-
- if (comparison != null) {
- var pms = comparison.GetParametersCached();
- if (pms.Length != 2) {
- throw Error.IncorrectNumberOfMethodCallArguments(comparison);
- }
- // Validate that the switch value's type matches the comparison method's
- // left hand side parameter type.
- var leftParam = pms[0];
- bool liftedCall = false;
- if (!ParameterIsAssignable(leftParam, switchValue.Type)) {
- liftedCall = ParameterIsAssignable(leftParam, switchValue.Type.GetNonNullableType());
- if (!liftedCall) {
- throw Error.SwitchValueTypeDoesNotMatchComparisonMethodParameter(switchValue.Type, leftParam.ParameterType);
- }
- }
-
- var rightParam = pms[1];
- foreach (var c in caseList) {
- ContractUtils.RequiresNotNull(c, "cases");
- ValidateSwitchCaseType(c.Body, customType, resultType, "cases");
- for (int i = 0; i < c.TestValues.Count; i++) {
- // When a comparison method is provided, test values can have different type but have to
- // be reference assignable to the right hand side parameter of the method.
- Type rightOperandType = c.TestValues[i].Type;
- if (liftedCall) {
- if (!rightOperandType.IsNullableType()) {
- throw Error.TestValueTypeDoesNotMatchComparisonMethodParameter(rightOperandType, rightParam.ParameterType);
- }
- rightOperandType = rightOperandType.GetNonNullableType();
- }
- if (!ParameterIsAssignable(rightParam, rightOperandType)) {
- throw Error.TestValueTypeDoesNotMatchComparisonMethodParameter(rightOperandType, rightParam.ParameterType);
- }
- }
- }
- } else {
- // When comparison method is not present, all the test values must have
- // the same type. Use the first test value's type as the baseline.
- var firstTestValue = caseList[0].TestValues[0];
- foreach (var c in caseList) {
- ContractUtils.RequiresNotNull(c, "cases");
- ValidateSwitchCaseType(c.Body, customType, resultType, "cases");
- // When no comparison method is provided, require all test values to have the same type.
- for (int i = 0; i < c.TestValues.Count; i++) {
- if (!TypeUtils.AreEquivalent(firstTestValue.Type, c.TestValues[i].Type)) {
- throw new ArgumentException(Strings.AllTestValuesMustHaveSameType, "cases");
- }
- }
- }
-
- // Now we need to validate that switchValue.Type and testValueType
- // make sense in an Equal node. Fortunately, Equal throws a
- // reasonable error, so just call it.
- var equal = Equal(switchValue, firstTestValue, false, comparison);
-
- // Get the comparison function from equals node.
- comparison = equal.Method;
- }
-
- if (defaultBody == null) {
- if (resultType != typeof(void)) throw Error.DefaultBodyMustBeSupplied();
- } else {
- ValidateSwitchCaseType(defaultBody, customType, resultType, "defaultBody");
- }
-
- // if we have a non-boolean userdefined equals, we don't want it.
- if (comparison != null && comparison.ReturnType != typeof(bool)) {
- throw Error.EqualityMustReturnBoolean(comparison);
- }
-
- return new SwitchExpression(resultType, switchValue, defaultBody, comparison, caseList);
- }
-
-
- /// <summary>
- /// If custom type is provided, all branches must be reference assignable to the result type.
- /// If no custom type is provided, all branches must have the same type - resultType.
- /// </summary>
- private static void ValidateSwitchCaseType(Expression @case, bool customType, Type resultType, string parameterName) {
- if (customType) {
- if (resultType != typeof(void)) {
- if (!TypeUtils.AreReferenceAssignable(resultType, @case.Type)) {
- throw new ArgumentException(Strings.ArgumentTypesMustMatch, parameterName);
- }
- }
- } else {
- if (!TypeUtils.AreEquivalent(resultType, @case.Type)) {
- throw new ArgumentException(Strings.AllCaseBodiesMustHaveSameType, parameterName);
- }
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/SymbolDocumentInfo.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/SymbolDocumentInfo.cs
deleted file mode 100644
index 1bb206e63dc..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/SymbolDocumentInfo.cs
+++ /dev/null
@@ -1,153 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Stores information needed to emit debugging symbol information for a
- /// source file, in particular the file name and unique language identifier.
- /// </summary>
- public class SymbolDocumentInfo {
- private readonly string _fileName;
-
- internal SymbolDocumentInfo(string fileName) {
- ContractUtils.RequiresNotNull(fileName, "fileName");
- _fileName = fileName;
- }
-
- /// <summary>
- /// The source file name.
- /// </summary>
- public string FileName {
- get { return _fileName; }
- }
-
- /// <summary>
- /// Returns the language's unique identifier, if any.
- /// </summary>
- public virtual Guid Language {
- get { return Guid.Empty; }
- }
-
- /// <summary>
- /// Returns the language vendor's unique identifier, if any.
- /// </summary>
- public virtual Guid LanguageVendor {
- get { return Guid.Empty; }
- }
-
- /// <summary>
- /// Returns the document type's unique identifier, if any.
- /// Defaults to the guid for a text file.
- /// </summary>
- public virtual Guid DocumentType {
- get { return Compiler.SymbolGuids.DocumentType_Text; }
- }
- }
-
- internal sealed class SymbolDocumentWithGuids : SymbolDocumentInfo {
- private readonly Guid _language;
- private readonly Guid _vendor;
- private readonly Guid _documentType;
-
- internal SymbolDocumentWithGuids(string fileName, ref Guid language)
- : base(fileName) {
- _language = language;
- _documentType = Compiler.SymbolGuids.DocumentType_Text;
- }
-
- internal SymbolDocumentWithGuids(string fileName, ref Guid language, ref Guid vendor)
- : base(fileName) {
- _language = language;
- _vendor = vendor;
- _documentType = Compiler.SymbolGuids.DocumentType_Text;
- }
-
- internal SymbolDocumentWithGuids(string fileName, ref Guid language, ref Guid vendor, ref Guid documentType)
- : base(fileName) {
- _language = language;
- _vendor = vendor;
- _documentType = documentType;
- }
-
- public override Guid Language {
- get { return _language; }
- }
-
- public override Guid LanguageVendor {
- get { return _vendor; }
- }
-
- public override Guid DocumentType {
- get { return _documentType; }
- }
- }
-
- public partial class Expression {
- /// <summary>
- /// Creates an instance of <see cref="T:System.Linq.Expressions.SymbolDocumentInfo" />.
- /// </summary>
- /// <param name="fileName">A <see cref="T:System.String" /> to set the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.FileName" /> equal to.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.SymbolDocumentInfo" /> that has the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.FileName" /> property set to the specified value.</returns>
- public static SymbolDocumentInfo SymbolDocument(string fileName) {
- return new SymbolDocumentInfo(fileName);
- }
-
- /// <summary>
- /// Creates an instance of <see cref="T:System.Linq.Expressions.SymbolDocumentInfo" />.
- /// </summary>
- /// <param name="fileName">A <see cref="T:System.String" /> to set the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.FileName" /> equal to.</param>
- /// <param name="language">A <see cref="T:System.Guid" /> to set the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.Language" /> equal to.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.SymbolDocumentInfo" /> that has the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.FileName" />
- /// and <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.Language" /> properties set to the specified value.</returns>
- public static SymbolDocumentInfo SymbolDocument(string fileName, Guid language) {
- return new SymbolDocumentWithGuids(fileName, ref language);
- }
-
- /// <summary>
- /// Creates an instance of <see cref="T:System.Linq.Expressions.SymbolDocumentInfo" />.
- /// </summary>
- /// <param name="fileName">A <see cref="T:System.String" /> to set the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.FileName" /> equal to.</param>
- /// <param name="language">A <see cref="T:System.Guid" /> to set the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.Language" /> equal to.</param>
- /// <param name="languageVendor">A <see cref="T:System.Guid" /> to set the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.LanguageVendor" /> equal to.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.SymbolDocumentInfo" /> that has the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.FileName" />
- /// and <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.Language" />
- /// and <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.LanguageVendor" /> properties set to the specified value.</returns>
- public static SymbolDocumentInfo SymbolDocument(string fileName, Guid language, Guid languageVendor) {
- return new SymbolDocumentWithGuids(fileName, ref language, ref languageVendor);
- }
-
- /// <summary>
- /// Creates an instance of <see cref="T:System.Linq.Expressions.SymbolDocumentInfo" />.
- /// </summary>
- /// <param name="fileName">A <see cref="T:System.String" /> to set the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.FileName" /> equal to.</param>
- /// <param name="language">A <see cref="T:System.Guid" /> to set the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.Language" /> equal to.</param>
- /// <param name="languageVendor">A <see cref="T:System.Guid" /> to set the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.LanguageVendor" /> equal to.</param>
- /// <param name="documentType">A <see cref="T:System.Guid" /> to set the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.DocumentType" /> equal to.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.SymbolDocumentInfo" /> that has the <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.FileName" />
- /// and <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.Language" />
- /// and <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.LanguageVendor" />
- /// and <see cref="P:System.Linq.Expressions.SymbolDocumentInfo.DocumentType" /> properties set to the specified value.</returns>
- public static SymbolDocumentInfo SymbolDocument(string fileName, Guid language, Guid languageVendor, Guid documentType) {
- return new SymbolDocumentWithGuids(fileName, ref language, ref languageVendor, ref documentType);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/TryExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/TryExpression.cs
deleted file mode 100644
index 9d19f67a981..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/TryExpression.cs
+++ /dev/null
@@ -1,228 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents a try/catch/finally/fault block.
- ///
- /// The body is protected by the try block.
- /// The handlers consist of a set of <see cref="CatchBlock"/>s that can either be catch or filters.
- /// The fault runs if an exception is thrown.
- /// The finally runs regardless of how control exits the body.
- /// Only one of fault or finally can be supplied.
- /// The return type of the try block must match the return type of any associated catch statements.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.TryExpressionProxy))]
- public sealed class TryExpression : Expression {
- private readonly Type _type;
- private readonly Expression _body;
- private readonly ReadOnlyCollection<CatchBlock> _handlers;
- private readonly Expression _finally;
- private readonly Expression _fault;
-
- internal TryExpression(Type type, Expression body, Expression @finally, Expression fault, ReadOnlyCollection<CatchBlock> handlers) {
- _type = type;
- _body = body;
- _handlers = handlers;
- _finally = @finally;
- _fault = fault;
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return _type; }
- }
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return ExpressionType.Try; }
- }
-
- /// <summary>
- /// Gets the <see cref="Expression"/> representing the body of the try block.
- /// </summary>
- public Expression Body {
- get { return _body; }
- }
-
- /// <summary>
- /// Gets the collection of <see cref="CatchBlock"/>s associated with the try block.
- /// </summary>
- public ReadOnlyCollection<CatchBlock> Handlers {
- get { return _handlers; }
- }
-
- /// <summary>
- /// Gets the <see cref="Expression"/> representing the finally block.
- /// </summary>
- public Expression Finally {
- get { return _finally; }
- }
-
- /// <summary>
- /// Gets the <see cref="Expression"/> representing the fault block.
- /// </summary>
- public Expression Fault {
- get { return _fault; }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitTry(this);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="body">The <see cref="Body" /> property of the result.</param>
- /// <param name="handlers">The <see cref="Handlers" /> property of the result.</param>
- /// <param name="finally">The <see cref="Finally" /> property of the result.</param>
- /// <param name="fault">The <see cref="Fault" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public TryExpression Update(Expression body, IEnumerable<CatchBlock> handlers, Expression @finally, Expression fault) {
- if (body == Body && handlers == Handlers && @finally == Finally && fault == Fault) {
- return this;
- }
- return Expression.MakeTry(Type, body, @finally, fault, handlers);
- }
- }
-
- public partial class Expression {
-
- /// <summary>
- /// Creates a <see cref="TryExpression"/> representing a try block with a fault block and no catch statements.
- /// </summary>
- /// <param name="body">The body of the try block.</param>
- /// <param name="fault">The body of the fault block.</param>
- /// <returns>The created <see cref="TryExpression"/>.</returns>
- public static TryExpression TryFault(Expression body, Expression fault) {
- return MakeTry(null, body, null, fault, null);
- }
-
- /// <summary>
- /// Creates a <see cref="TryExpression"/> representing a try block with a finally block and no catch statements.
- /// </summary>
- /// <param name="body">The body of the try block.</param>
- /// <param name="finally">The body of the finally block.</param>
- /// <returns>The created <see cref="TryExpression"/>.</returns>
- public static TryExpression TryFinally(Expression body, Expression @finally) {
- return MakeTry(null, body, @finally, null, null);
- }
-
- /// <summary>
- /// Creates a <see cref="TryExpression"/> representing a try block with any number of catch statements and neither a fault nor finally block.
- /// </summary>
- /// <param name="body">The body of the try block.</param>
- /// <param name="handlers">The array of zero or more <see cref="CatchBlock"/>s representing the catch statements to be associated with the try block.</param>
- /// <returns>The created <see cref="TryExpression"/>.</returns>
- public static TryExpression TryCatch(Expression body, params CatchBlock[] handlers) {
- return MakeTry(null, body, null, null, handlers);
- }
-
- /// <summary>
- /// Creates a <see cref="TryExpression"/> representing a try block with any number of catch statements and a finally block.
- /// </summary>
- /// <param name="body">The body of the try block.</param>
- /// <param name="finally">The body of the finally block.</param>
- /// <param name="handlers">The array of zero or more <see cref="CatchBlock"/>s representing the catch statements to be associated with the try block.</param>
- /// <returns>The created <see cref="TryExpression"/>.</returns>
- public static TryExpression TryCatchFinally(Expression body, Expression @finally, params CatchBlock[] handlers) {
- return MakeTry(null, body, @finally, null, handlers);
- }
-
- /// <summary>
- /// Creates a <see cref="TryExpression"/> representing a try block with the specified elements.
- /// </summary>
- /// <param name="type">The result type of the try expression. If null, bodh and all handlers must have identical type.</param>
- /// <param name="body">The body of the try block.</param>
- /// <param name="finally">The body of the finally block. Pass null if the try block has no finally block associated with it.</param>
- /// <param name="fault">The body of the t block. Pass null if the try block has no fault block associated with it.</param>
- /// <param name="handlers">A collection of <see cref="CatchBlock"/>s representing the catch statements to be associated with the try block.</param>
- /// <returns>The created <see cref="TryExpression"/>.</returns>
- public static TryExpression MakeTry(Type type, Expression body, Expression @finally, Expression fault, IEnumerable<CatchBlock> handlers) {
- RequiresCanRead(body, "body");
-
- var @catch = handlers.ToReadOnly();
- ContractUtils.RequiresNotNullItems(@catch, "handlers");
- ValidateTryAndCatchHaveSameType(type, body, @catch);
-
- if (fault != null) {
- if (@finally != null || @catch.Count > 0) {
- throw Error.FaultCannotHaveCatchOrFinally();
- }
- RequiresCanRead(fault, "fault");
- } else if (@finally != null) {
- RequiresCanRead(@finally, "finally");
- } else if (@catch.Count == 0) {
- throw Error.TryMustHaveCatchFinallyOrFault();
- }
-
- return new TryExpression(type ?? body.Type, body, @finally, fault, @catch);
- }
-
- //Validate that the body of the try expression must have the same type as the body of every try block.
- private static void ValidateTryAndCatchHaveSameType(Type type, Expression tryBody, ReadOnlyCollection<CatchBlock> handlers) {
- // Type unification ... all parts must be reference assignable to "type"
- if (type != null) {
- if (type != typeof(void)) {
- if (!TypeUtils.AreReferenceAssignable(type, tryBody.Type)) {
- throw Error.ArgumentTypesMustMatch();
- }
- foreach (var cb in handlers) {
- if (!TypeUtils.AreReferenceAssignable(type, cb.Body.Type)) {
- throw Error.ArgumentTypesMustMatch();
- }
- }
- }
- } else if (tryBody == null || tryBody.Type == typeof(void)) {
- //The body of every try block must be null or have void type.
- foreach (CatchBlock cb in handlers) {
- if (cb.Body != null && cb.Body.Type != typeof(void)) {
- throw Error.BodyOfCatchMustHaveSameTypeAsBodyOfTry();
- }
- }
- } else {
- //Body of every catch must have the same type of body of try.
- type = tryBody.Type;
- foreach (CatchBlock cb in handlers) {
- if (cb.Body == null || !TypeUtils.AreEquivalent(cb.Body.Type, type)) {
- throw Error.BodyOfCatchMustHaveSameTypeAsBodyOfTry();
- }
- }
- }
- }
- }
-
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/TypeBinaryExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/TypeBinaryExpression.cs
deleted file mode 100644
index 0e3b2eee7a5..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/TypeBinaryExpression.cs
+++ /dev/null
@@ -1,211 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
- /// <summary>
- /// Represents an operation between an expression and a type.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.TypeBinaryExpressionProxy))]
- public sealed class TypeBinaryExpression : Expression {
- private readonly Expression _expression;
- private readonly Type _typeOperand;
- private readonly ExpressionType _nodeKind;
-
- internal TypeBinaryExpression(Expression expression, Type typeOperand, ExpressionType nodeKind) {
- _expression = expression;
- _typeOperand = typeOperand;
- _nodeKind = nodeKind;
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents.
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return typeof(bool); }
- }
-
- /// <summary>
- /// Returns the node type of this Expression. Extension nodes should return
- /// ExpressionType.Extension when overriding this method.
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return _nodeKind; }
- }
-
- /// <summary>
- /// Gets the expression operand of a type test operation.
- /// </summary>
- public Expression Expression {
- get { return _expression; }
- }
-
- /// <summary>
- /// Gets the type operand of a type test operation.
- /// </summary>
- public Type TypeOperand {
- get { return _typeOperand; }
- }
-
- #region Reduce TypeEqual
-
- internal Expression ReduceTypeEqual() {
- Type cType = Expression.Type;
-
- // For value types (including Void, but not nullables), we can
- // determine the result now
- if (cType.IsValueType && !cType.IsNullableType()) {
- return Expression.Block(Expression, Expression.Constant(cType == _typeOperand.GetNonNullableType()));
- }
-
- // Can check the value right now for constants.
- if (Expression.NodeType == ExpressionType.Constant) {
- return ReduceConstantTypeEqual();
- }
-
- // If the operand type is a sealed reference type or a nullable
- // type, it will match if value is not null
- if (cType.IsSealed && (cType == _typeOperand)) {
- if (cType.IsNullableType()) {
- return Expression.NotEqual(Expression, Expression.Constant(null, Expression.Type));
- } else {
- return Expression.ReferenceNotEqual(Expression, Expression.Constant(null, Expression.Type));
- }
- }
-
- // expression is a ByVal parameter. Can safely reevaluate.
- var parameter = Expression as ParameterExpression;
- if (parameter != null && !parameter.IsByRef) {
- return ByValParameterTypeEqual(parameter);
- }
-
- // Create a temp so we only evaluate the left side once
- parameter = Expression.Parameter(typeof(object));
-
- // Convert to object if necessary
- var expression = Expression;
- if (!TypeUtils.AreReferenceAssignable(typeof(object), expression.Type)) {
- expression = Expression.Convert(expression, typeof(object));
- }
-
- return Expression.Block(
- new[] { parameter },
- Expression.Assign(parameter, expression),
- ByValParameterTypeEqual(parameter)
- );
- }
-
- // Helper that is used when re-eval of LHS is safe.
- private Expression ByValParameterTypeEqual(ParameterExpression value) {
- Expression getType = Expression.Call(value, typeof(object).GetMethod("GetType"));
-
- // In remoting scenarios, obj.GetType() can return an interface.
- // But there's a bug in the JIT32's optimized "obj.GetType() ==
- // typeof(ISomething)" codegen, causing it to always return false.
- // We workaround the bug by generating different, less optimal IL
- // if TypeOperand is an interface.
- if (_typeOperand.IsInterface) {
- var temp = Expression.Parameter(typeof(Type));
- getType = Expression.Block(new[] { temp }, Expression.Assign(temp, getType), temp);
- }
-
- // We use reference equality when comparing to null for correctness
- // (don't invoke a user defined operator), and reference equality
- // on types for performance (so the JIT can optimize the IL).
- return Expression.AndAlso(
- Expression.ReferenceNotEqual(value, Expression.Constant(null)),
- Expression.ReferenceEqual(
- getType,
- Expression.Constant(_typeOperand.GetNonNullableType(), typeof(Type))
- )
- );
- }
-
- private Expression ReduceConstantTypeEqual() {
- ConstantExpression ce = Expression as ConstantExpression;
- //TypeEqual(null, T) always returns false.
- if (ce.Value == null) {
- return Expression.Constant(false);
- } else {
- return Expression.Constant(_typeOperand.GetNonNullableType() == ce.Value.GetType());
- }
- }
-
- #endregion
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitTypeBinary(this);
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="expression">The <see cref="Expression" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public TypeBinaryExpression Update(Expression expression) {
- if (expression == Expression) {
- return this;
- }
- if (NodeType == ExpressionType.TypeIs) {
- return Expression.TypeIs(expression, TypeOperand);
- }
- return Expression.TypeEqual(expression, TypeOperand);
- }
- }
-
- public partial class Expression {
- /// <summary>
- /// Creates a <see cref="TypeBinaryExpression"/>.
- /// </summary>
- /// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param>
- /// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param>
- /// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="TypeIs"/> and for which the <see cref="Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns>
- public static TypeBinaryExpression TypeIs(Expression expression, Type type) {
- RequiresCanRead(expression, "expression");
- ContractUtils.RequiresNotNull(type, "type");
- if (type.IsByRef) throw Error.TypeMustNotBeByRef();
-
- return new TypeBinaryExpression(expression, type, ExpressionType.TypeIs);
- }
-
- /// <summary>
- /// Creates a <see cref="TypeBinaryExpression"/> that compares run-time type identity.
- /// </summary>
- /// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param>
- /// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param>
- /// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="TypeEqual"/> and for which the <see cref="Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns>
- public static TypeBinaryExpression TypeEqual(Expression expression, Type type) {
- RequiresCanRead(expression, "expression");
- ContractUtils.RequiresNotNull(type, "type");
- if (type.IsByRef) throw Error.TypeMustNotBeByRef();
-
- return new TypeBinaryExpression(expression, type, ExpressionType.TypeEqual);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/TypeUtils.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/TypeUtils.cs
deleted file mode 100644
index 41a30c1007d..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/TypeUtils.cs
+++ /dev/null
@@ -1,715 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-#else
-using System.Linq.Expressions;
-#endif
-
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-
-namespace System.Dynamic.Utils {
-
- internal static class TypeUtils {
- private const BindingFlags AnyStatic = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
- internal const MethodAttributes PublicStatic = MethodAttributes.Public | MethodAttributes.Static;
-
- internal static Type GetNonNullableType(this Type type) {
- if (IsNullableType(type)) {
- return type.GetGenericArguments()[0];
- }
- return type;
- }
-
- internal static Type GetNullableType(Type type) {
- Debug.Assert(type != null, "type cannot be null");
- if (type.IsValueType && !IsNullableType(type)) {
- return typeof(Nullable<>).MakeGenericType(type);
- }
- return type;
- }
-
- internal static bool IsNullableType(this Type type) {
- return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
- }
-
- internal static bool IsBool(Type type) {
- return GetNonNullableType(type) == typeof(bool);
- }
-
- internal static bool IsNumeric(Type type) {
- type = GetNonNullableType(type);
- if (!type.IsEnum) {
- switch (Type.GetTypeCode(type)) {
- case TypeCode.Char:
- case TypeCode.SByte:
- case TypeCode.Byte:
- case TypeCode.Int16:
- case TypeCode.Int32:
- case TypeCode.Int64:
- case TypeCode.Double:
- case TypeCode.Single:
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- return true;
- }
- }
- return false;
- }
-
- internal static bool IsInteger(Type type) {
- type = GetNonNullableType(type);
- if (type.IsEnum) {
- return false;
- }
- switch (Type.GetTypeCode(type)) {
- case TypeCode.Byte:
- case TypeCode.SByte:
- case TypeCode.Int16:
- case TypeCode.Int32:
- case TypeCode.Int64:
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- return true;
- default:
- return false;
- }
- }
-
-
- internal static bool IsArithmetic(Type type) {
- type = GetNonNullableType(type);
- if (!type.IsEnum) {
- switch (Type.GetTypeCode(type)) {
- case TypeCode.Int16:
- case TypeCode.Int32:
- case TypeCode.Int64:
- case TypeCode.Double:
- case TypeCode.Single:
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- return true;
- }
- }
- return false;
- }
-
- internal static bool IsUnsignedInt(Type type) {
- type = GetNonNullableType(type);
- if (!type.IsEnum) {
- switch (Type.GetTypeCode(type)) {
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- return true;
- }
- }
- return false;
- }
-
- internal static bool IsIntegerOrBool(Type type) {
- type = GetNonNullableType(type);
- if (!type.IsEnum) {
- switch (Type.GetTypeCode(type)) {
- case TypeCode.Int64:
- case TypeCode.Int32:
- case TypeCode.Int16:
- case TypeCode.UInt64:
- case TypeCode.UInt32:
- case TypeCode.UInt16:
- case TypeCode.Boolean:
- case TypeCode.SByte:
- case TypeCode.Byte:
- return true;
- }
- }
- return false;
- }
-
- internal static bool AreEquivalent(Type t1, Type t2) {
-#if FEATURE_TYPE_EQUIVALENCE
- return t1 == t2 || t1.IsEquivalentTo(t2);
-#else
- return t1 == t2;
-#endif
- }
-
- internal static bool AreReferenceAssignable(Type dest, Type src) {
- // WARNING: This actually implements "Is this identity assignable and/or reference assignable?"
- if (AreEquivalent(dest, src)) {
- return true;
- }
- if (!dest.IsValueType && !src.IsValueType && dest.IsAssignableFrom(src)) {
- return true;
- }
- return false;
- }
-
- // Checks if the type is a valid target for an instance call
- internal static bool IsValidInstanceType(MemberInfo member, Type instanceType) {
- Type targetType = member.DeclaringType;
- if (AreReferenceAssignable(targetType, instanceType)) {
- return true;
- }
- if (instanceType.IsValueType) {
- if (AreReferenceAssignable(targetType, typeof(System.Object))) {
- return true;
- }
- if (AreReferenceAssignable(targetType, typeof(System.ValueType))) {
- return true;
- }
- if (instanceType.IsEnum && AreReferenceAssignable(targetType, typeof(System.Enum))) {
- return true;
- }
- // A call to an interface implemented by a struct is legal whether the struct has
- // been boxed or not.
- if (targetType.IsInterface) {
- foreach (Type interfaceType in instanceType.GetInterfaces()) {
- if (AreReferenceAssignable(targetType, interfaceType)) {
- return true;
- }
- }
- }
- }
- return false;
- }
-
- internal static bool HasIdentityPrimitiveOrNullableConversion(Type source, Type dest) {
- Debug.Assert(source != null && dest != null);
-
- // Identity conversion
- if (AreEquivalent(source, dest)) {
- return true;
- }
-
- // Nullable conversions
- if (IsNullableType(source) && AreEquivalent(dest, GetNonNullableType(source))) {
- return true;
- }
- if (IsNullableType(dest) && AreEquivalent(source, GetNonNullableType(dest))) {
- return true;
- }
- // Primitive runtime conversions
- // All conversions amongst enum, bool, char, integer and float types
- // (and their corresponding nullable types) are legal except for
- // nonbool==>bool and nonbool==>bool?
- // Since we have already covered bool==>bool, bool==>bool?, etc, above,
- // we can just disallow having a bool or bool? destination type here.
- if (IsConvertible(source) && IsConvertible(dest) && GetNonNullableType(dest) != typeof(bool)) {
- return true;
- }
- return false;
- }
-
- internal static bool HasReferenceConversion(Type source, Type dest) {
- Debug.Assert(source != null && dest != null);
-
- // void -> void conversion is handled elsewhere
- // (it's an identity conversion)
- // All other void conversions are disallowed.
- if (source == typeof(void) || dest == typeof(void)) {
- return false;
- }
-
- Type nnSourceType = TypeUtils.GetNonNullableType(source);
- Type nnDestType = TypeUtils.GetNonNullableType(dest);
-
- // Down conversion
- if (nnSourceType.IsAssignableFrom(nnDestType)) {
- return true;
- }
- // Up conversion
- if (nnDestType.IsAssignableFrom(nnSourceType)) {
- return true;
- }
- // Interface conversion
- if (source.IsInterface || dest.IsInterface) {
- return true;
- }
- // Variant delegate conversion
- if (IsLegalExplicitVariantDelegateConversion(source, dest))
- return true;
-
- // Object conversion
- if (source == typeof(object) || dest == typeof(object)) {
- return true;
- }
- return false;
- }
-
- private static bool IsCovariant(Type t)
- {
- Debug.Assert(t != null);
- return 0 != (t.GenericParameterAttributes & GenericParameterAttributes.Covariant);
- }
-
- private static bool IsContravariant(Type t)
- {
- Debug.Assert(t != null);
- return 0 != (t.GenericParameterAttributes & GenericParameterAttributes.Contravariant);
- }
-
- private static bool IsInvariant(Type t)
- {
- Debug.Assert(t != null);
- return 0 == (t.GenericParameterAttributes & GenericParameterAttributes.VarianceMask);
- }
-
- private static bool IsDelegate(Type t)
- {
- Debug.Assert(t != null);
- return t.IsSubclassOf(typeof(System.MulticastDelegate));
- }
-
- internal static bool IsLegalExplicitVariantDelegateConversion(Type source, Type dest)
- {
- Debug.Assert(source != null && dest != null);
-
- // There *might* be a legal conversion from a generic delegate type S to generic delegate type T,
- // provided all of the follow are true:
- // o Both types are constructed generic types of the same generic delegate type, D<X1,... Xk>.
- // That is, S = D<S1...>, T = D<T1...>.
- // o If type parameter Xi is declared to be invariant then Si must be identical to Ti.
- // o If type parameter Xi is declared to be covariant ("out") then Si must be convertible
- // to Ti via an identify conversion, implicit reference conversion, or explicit reference conversion.
- // o If type parameter Xi is declared to be contravariant ("in") then either Si must be identical to Ti,
- // or Si and Ti must both be reference types.
-
- if (!IsDelegate(source) || !IsDelegate(dest) || !source.IsGenericType || !dest.IsGenericType)
- return false;
-
- Type genericDelegate = source.GetGenericTypeDefinition();
-
- if (dest.GetGenericTypeDefinition() != genericDelegate)
- return false;
-
- Type[] genericParameters = genericDelegate.GetGenericArguments();
- Type[] sourceArguments = source.GetGenericArguments();
- Type[] destArguments = dest.GetGenericArguments();
-
- Debug.Assert(genericParameters != null);
- Debug.Assert(sourceArguments != null);
- Debug.Assert(destArguments != null);
- Debug.Assert(genericParameters.Length == sourceArguments.Length);
- Debug.Assert(genericParameters.Length == destArguments.Length);
-
- for (int iParam = 0; iParam < genericParameters.Length; ++iParam)
- {
- Type sourceArgument = sourceArguments[iParam];
- Type destArgument = destArguments[iParam];
-
- Debug.Assert(sourceArgument != null && destArgument != null);
-
- // If the arguments are identical then this one is automatically good, so skip it.
- if (AreEquivalent(sourceArgument, destArgument))
- {
- continue;
- }
-
- Type genericParameter = genericParameters[iParam];
-
- Debug.Assert(genericParameter != null);
-
- if (IsInvariant(genericParameter))
- {
- return false;
- }
-
- if (IsCovariant(genericParameter))
- {
- if (!HasReferenceConversion(sourceArgument, destArgument))
- {
- return false;
- }
- }
- else if (IsContravariant(genericParameter))
- {
- if (sourceArgument.IsValueType || destArgument.IsValueType)
- {
- return false;
- }
- }
- }
- return true;
- }
-
- internal static bool IsConvertible(Type type) {
- type = GetNonNullableType(type);
- if (type.IsEnum) {
- return true;
- }
- switch (Type.GetTypeCode(type)) {
- case TypeCode.Boolean:
- case TypeCode.Byte:
- case TypeCode.SByte:
- case TypeCode.Int16:
- case TypeCode.Int32:
- case TypeCode.Int64:
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- case TypeCode.Single:
- case TypeCode.Double:
- case TypeCode.Char:
- return true;
- default:
- return false;
- }
- }
-
- internal static bool HasReferenceEquality(Type left, Type right) {
- if (left.IsValueType || right.IsValueType) {
- return false;
- }
-
- // If we have an interface and a reference type then we can do
- // reference equality.
-
- // If we have two reference types and one is assignable to the
- // other then we can do reference equality.
-
- return left.IsInterface || right.IsInterface ||
- AreReferenceAssignable(left, right) ||
- AreReferenceAssignable(right, left);
- }
-
- internal static bool HasBuiltInEqualityOperator(Type left, Type right) {
- // If we have an interface and a reference type then we can do
- // reference equality.
- if (left.IsInterface && !right.IsValueType) {
- return true;
- }
- if (right.IsInterface && !left.IsValueType) {
- return true;
- }
- // If we have two reference types and one is assignable to the
- // other then we can do reference equality.
- if (!left.IsValueType && !right.IsValueType) {
- if (AreReferenceAssignable(left, right) || AreReferenceAssignable(right, left)) {
- return true;
- }
- }
- // Otherwise, if the types are not the same then we definitely
- // do not have a built-in equality operator.
- if (!AreEquivalent(left, right)) {
- return false;
- }
- // We have two identical value types, modulo nullability. (If they were both the
- // same reference type then we would have returned true earlier.)
- Debug.Assert(left.IsValueType);
- // Equality between struct types is only defined for numerics, bools, enums,
- // and their nullable equivalents.
- Type nnType = GetNonNullableType(left);
- if (nnType == typeof(bool) || IsNumeric(nnType) || nnType.IsEnum) {
- return true;
- }
- return false;
- }
-
- internal static bool IsImplicitlyConvertible(Type source, Type destination) {
- return AreEquivalent(source, destination) || // identity conversion
- IsImplicitNumericConversion(source, destination) ||
- IsImplicitReferenceConversion(source, destination) ||
- IsImplicitBoxingConversion(source, destination) ||
- IsImplicitNullableConversion(source, destination);
- }
-
-
- internal static MethodInfo GetUserDefinedCoercionMethod(Type convertFrom, Type convertToType, bool implicitOnly) {
- // check for implicit coercions first
- Type nnExprType = TypeUtils.GetNonNullableType(convertFrom);
- Type nnConvType = TypeUtils.GetNonNullableType(convertToType);
- // try exact match on types
- MethodInfo[] eMethods = nnExprType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
- MethodInfo method = FindConversionOperator(eMethods, convertFrom, convertToType, implicitOnly);
- if (method != null) {
- return method;
- }
- MethodInfo[] cMethods = nnConvType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
- method = FindConversionOperator(cMethods, convertFrom, convertToType, implicitOnly);
- if (method != null) {
- return method;
- }
- // try lifted conversion
- if (!TypeUtils.AreEquivalent(nnExprType, convertFrom) ||
- !TypeUtils.AreEquivalent(nnConvType, convertToType)) {
- method = FindConversionOperator(eMethods, nnExprType, nnConvType, implicitOnly);
- if (method == null) {
- method = FindConversionOperator(cMethods, nnExprType, nnConvType, implicitOnly);
- }
- if (method != null) {
- return method;
- }
- }
- return null;
- }
-
- internal static MethodInfo FindConversionOperator(MethodInfo[] methods, Type typeFrom, Type typeTo, bool implicitOnly) {
- foreach (MethodInfo mi in methods) {
- if (mi.Name != "op_Implicit" && (implicitOnly || mi.Name != "op_Explicit")) {
- continue;
- }
- if (!TypeUtils.AreEquivalent(mi.ReturnType, typeTo)) {
- continue;
- }
- ParameterInfo[] pis = mi.GetParametersCached();
- if (!TypeUtils.AreEquivalent(pis[0].ParameterType, typeFrom)) {
- continue;
- }
- return mi;
- }
- return null;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- private static bool IsImplicitNumericConversion(Type source, Type destination) {
- TypeCode tcSource = Type.GetTypeCode(source);
- TypeCode tcDest = Type.GetTypeCode(destination);
-
- switch (tcSource) {
- case TypeCode.SByte:
- switch (tcDest) {
- case TypeCode.Int16:
- case TypeCode.Int32:
- case TypeCode.Int64:
- case TypeCode.Single:
- case TypeCode.Double:
- case TypeCode.Decimal:
- return true;
- }
- return false;
- case TypeCode.Byte:
- switch (tcDest) {
- case TypeCode.Int16:
- case TypeCode.UInt16:
- case TypeCode.Int32:
- case TypeCode.UInt32:
- case TypeCode.Int64:
- case TypeCode.UInt64:
- case TypeCode.Single:
- case TypeCode.Double:
- case TypeCode.Decimal:
- return true;
- }
- return false;
- case TypeCode.Int16:
- switch (tcDest) {
- case TypeCode.Int32:
- case TypeCode.Int64:
- case TypeCode.Single:
- case TypeCode.Double:
- case TypeCode.Decimal:
- return true;
- }
- return false;
- case TypeCode.UInt16:
- switch (tcDest) {
- case TypeCode.Int32:
- case TypeCode.UInt32:
- case TypeCode.Int64:
- case TypeCode.UInt64:
- case TypeCode.Single:
- case TypeCode.Double:
- case TypeCode.Decimal:
- return true;
- }
- return false;
- case TypeCode.Int32:
- switch (tcDest) {
- case TypeCode.Int64:
- case TypeCode.Single:
- case TypeCode.Double:
- case TypeCode.Decimal:
- return true;
- }
- return false;
- case TypeCode.UInt32:
- switch (tcDest) {
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- case TypeCode.Single:
- case TypeCode.Double:
- case TypeCode.Decimal:
- return true;
- }
- return false;
- case TypeCode.Int64:
- case TypeCode.UInt64:
- switch (tcDest) {
- case TypeCode.Single:
- case TypeCode.Double:
- case TypeCode.Decimal:
- return true;
- }
- return false;
- case TypeCode.Char:
- switch (tcDest) {
- case TypeCode.UInt16:
- case TypeCode.Int32:
- case TypeCode.UInt32:
- case TypeCode.Int64:
- case TypeCode.UInt64:
- case TypeCode.Single:
- case TypeCode.Double:
- case TypeCode.Decimal:
- return true;
- }
- return false;
- case TypeCode.Single:
- return (tcDest == TypeCode.Double);
- }
- return false;
- }
-
- private static bool IsImplicitReferenceConversion(Type source, Type destination) {
- return destination.IsAssignableFrom(source);
- }
-
- private static bool IsImplicitBoxingConversion(Type source, Type destination) {
- if (source.IsValueType && (destination == typeof(object) || destination == typeof(System.ValueType)))
- return true;
- if (source.IsEnum && destination == typeof(System.Enum))
- return true;
- return false;
- }
-
- private static bool IsImplicitNullableConversion(Type source, Type destination) {
- if (IsNullableType(destination))
- return IsImplicitlyConvertible(GetNonNullableType(source), GetNonNullableType(destination));
- return false;
- }
-
- internal static bool IsSameOrSubclass(Type type, Type subType) {
- return AreEquivalent(type, subType) || subType.IsSubclassOf(type);
- }
-
- internal static void ValidateType(Type type) {
- if (type.IsGenericTypeDefinition) {
- throw Error.TypeIsGeneric(type);
- }
- if (type.ContainsGenericParameters) {
- throw Error.TypeContainsGenericParameters(type);
- }
- }
-
- //from TypeHelper
- internal static Type FindGenericType(Type definition, Type type) {
- while (type != null && type != typeof(object)) {
- if (type.IsGenericType && AreEquivalent(type.GetGenericTypeDefinition(), definition)) {
- return type;
- }
- if (definition.IsInterface) {
- foreach (Type itype in type.GetInterfaces()) {
- Type found = FindGenericType(definition, itype);
- if (found != null)
- return found;
- }
- }
- type = type.BaseType;
- }
- return null;
- }
-
- internal static bool IsUnsigned(Type type) {
- type = GetNonNullableType(type);
- switch (Type.GetTypeCode(type)) {
- case TypeCode.Byte:
- case TypeCode.UInt16:
- case TypeCode.Char:
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- return true;
- default:
- return false;
- }
- }
-
- internal static bool IsFloatingPoint(Type type) {
- type = GetNonNullableType(type);
- switch (Type.GetTypeCode(type)) {
- case TypeCode.Single:
- case TypeCode.Double:
- return true;
- default:
- return false;
- }
- }
-
- /// <summary>
- /// Searches for an operator method on the type. The method must have
- /// the specified signature, no generic arguments, and have the
- /// SpecialName bit set. Also searches inherited operator methods.
- ///
- /// NOTE: This was designed to satisfy the needs of op_True and
- /// op_False, because we have to do runtime lookup for those. It may
- /// not work right for unary operators in general.
- /// </summary>
- internal static MethodInfo GetBooleanOperator(Type type, string name) {
- do {
- MethodInfo result = type.GetMethodValidated(name, AnyStatic, null, new Type[] { type }, null);
- if (result != null && result.IsSpecialName && !result.ContainsGenericParameters) {
- return result;
- }
- type = type.BaseType;
- } while (type != null);
- return null;
- }
-
- internal static Type GetNonRefType(this Type type) {
- return type.IsByRef ? type.GetElementType() : type;
- }
-
- private static readonly Assembly _mscorlib = typeof(object).Assembly;
- private static readonly Assembly _systemCore = typeof(Expression).Assembly;
-
- /// <summary>
- /// We can cache references to types, as long as they aren't in
- /// collectable assemblies. Unfortunately, we can't really distinguish
- /// between different flavors of assemblies. But, we can at least
- /// create a whitelist for types in mscorlib (so we get the primitives)
- /// and System.Core (so we find Func/Action overloads, etc).
- /// </summary>
- internal static bool CanCache(this Type t) {
- // Note: we don't have to scan base or declaring types here.
- // There's no way for a type in mscorlib to derive from or be
- // contained in a type from another assembly. The only thing we
- // need to look at is the generic arguments, which are the thing
- // that allows mscorlib types to be specialized by types in other
- // assemblies.
-
- var asm = t.Assembly;
- if (asm != _mscorlib && asm != _systemCore) {
- // Not in mscorlib or our assembly
- return false;
- }
-
- if (t.IsGenericType) {
- foreach (Type g in t.GetGenericArguments()) {
- if (!CanCache(g)) {
- return false;
- }
- }
- }
-
- return true;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/UnaryExpression.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/UnaryExpression.cs
deleted file mode 100644
index 8cf3b2a6190..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/UnaryExpression.cs
+++ /dev/null
@@ -1,995 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- /// <summary>
- /// Represents an expression that has a unary operator.
- /// </summary>
- [DebuggerTypeProxy(typeof(Expression.UnaryExpressionProxy))]
- public sealed class UnaryExpression : Expression {
- private readonly Expression _operand;
- private readonly MethodInfo _method;
- private readonly ExpressionType _nodeType;
- private readonly Type _type;
-
- internal UnaryExpression(ExpressionType nodeType, Expression expression, Type type, MethodInfo method) {
- _operand = expression;
- _method = method;
- _nodeType = nodeType;
- _type = type;
- }
-
- /// <summary>
- /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
- /// </summary>
- /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
- public sealed override Type Type {
- get { return _type; }
- }
-
- /// <summary>
- /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
- /// </summary>
- /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
- public sealed override ExpressionType NodeType {
- get { return _nodeType; }
- }
-
- /// <summary>
- /// Gets the operand of the unary operation.
- /// </summary>
- /// <returns> An <see cref="ExpressionType"/> that represents the operand of the unary operation.</returns>
- public Expression Operand {
- get { return _operand; }
- }
-
- /// <summary>
- /// Gets the implementing method for the unary operation.
- /// </summary>
- /// <returns>The <see cref="MethodInfo"/> that represents the implementing method.</returns>
- public MethodInfo Method {
- get { return _method; }
- }
-
- /// <summary>
- /// Gets a value that indicates whether the expression tree node represents a lifted call to an operator.
- /// </summary>
- /// <returns>true if the node represents a lifted call; otherwise, false.</returns>
- public bool IsLifted {
- get {
- if (NodeType == ExpressionType.TypeAs || NodeType == ExpressionType.Quote || NodeType == ExpressionType.Throw) {
- return false;
- }
- bool operandIsNullable = TypeUtils.IsNullableType(_operand.Type);
- bool resultIsNullable = TypeUtils.IsNullableType(this.Type);
- if (_method != null) {
- return (operandIsNullable && !TypeUtils.AreEquivalent(_method.GetParametersCached()[0].ParameterType, _operand.Type)) ||
- (resultIsNullable && !TypeUtils.AreEquivalent(_method.ReturnType, this.Type));
- }
- return operandIsNullable || resultIsNullable;
- }
- }
-
- /// <summary>
- /// Gets a value that indicates whether the expression tree node represents a lifted call to an operator whose return type is lifted to a nullable type.
- /// </summary>
- /// <returns>true if the operator's return type is lifted to a nullable type; otherwise, false.</returns>
- public bool IsLiftedToNull {
- get {
- return IsLifted && TypeUtils.IsNullableType(this.Type);
- }
- }
-
- /// <summary>
- /// Dispatches to the specific visit method for this node type.
- /// </summary>
- protected internal override Expression Accept(ExpressionVisitor visitor) {
- return visitor.VisitUnary(this);
- }
-
- /// <summary>
- /// Gets a value that indicates whether the expression tree node can be reduced.
- /// </summary>
- public override bool CanReduce {
- get {
- switch (_nodeType) {
- case ExpressionType.PreIncrementAssign:
- case ExpressionType.PreDecrementAssign:
- case ExpressionType.PostIncrementAssign:
- case ExpressionType.PostDecrementAssign:
- return true;
- }
- return false;
- }
- }
-
- /// <summary>
- /// Reduces the expression node to a simpler expression.
- /// If CanReduce returns true, this should return a valid expression.
- /// This method is allowed to return another node which itself
- /// must be reduced.
- /// </summary>
- /// <returns>The reduced expression.</returns>
- public override Expression Reduce() {
- if (CanReduce) {
- switch (_operand.NodeType) {
- case ExpressionType.Index:
- return ReduceIndex();
- case ExpressionType.MemberAccess:
- return ReduceMember();
- default:
- return ReduceVariable();
- }
- }
- return this;
- }
-
- private bool IsPrefix {
- get { return _nodeType == ExpressionType.PreIncrementAssign || _nodeType == ExpressionType.PreDecrementAssign; }
- }
-
- private UnaryExpression FunctionalOp(Expression operand) {
- ExpressionType functional;
- if (_nodeType == ExpressionType.PreIncrementAssign || _nodeType == ExpressionType.PostIncrementAssign) {
- functional = ExpressionType.Increment;
- } else {
- functional = ExpressionType.Decrement;
- }
- return new UnaryExpression(functional, operand, operand.Type, _method);
- }
-
- private Expression ReduceVariable() {
- if (IsPrefix) {
- // (op) var
- // ... is reduced into ...
- // var = op(var)
- return Assign(_operand, FunctionalOp(_operand));
- }
- // var (op)
- // ... is reduced into ...
- // temp = var
- // var = op(var)
- // temp
- var temp = Parameter(_operand.Type, null);
- return Block(
- new[] { temp },
- Assign(temp, _operand),
- Assign(_operand, FunctionalOp(temp)),
- temp
- );
- }
-
- private Expression ReduceMember() {
- var member = (MemberExpression)_operand;
- if (member.Expression == null) {
- //static member, reduce the same as variable
- return ReduceVariable();
- } else {
- var temp1 = Parameter(member.Expression.Type, null);
- var initTemp1 = Assign(temp1, member.Expression);
- member = MakeMemberAccess(temp1, member.Member);
-
- if (IsPrefix) {
- // (op) value.member
- // ... is reduced into ...
- // temp1 = value
- // temp1.member = op(temp1.member)
- return Block(
- new[] { temp1 },
- initTemp1,
- Assign(member, FunctionalOp(member))
- );
- }
-
- // value.member (op)
- // ... is reduced into ...
- // temp1 = value
- // temp2 = temp1.member
- // temp1.member = op(temp2)
- // temp2
- var temp2 = Parameter(member.Type, null);
- return Block(
- new[] { temp1, temp2 },
- initTemp1,
- Assign(temp2, member),
- Assign(member, FunctionalOp(temp2)),
- temp2
- );
- }
- }
-
- private Expression ReduceIndex() {
- // left[a0, a1, ... aN] (op)
- //
- // ... is reduced into ...
- //
- // tempObj = left
- // tempArg0 = a0
- // ...
- // tempArgN = aN
- // tempValue = tempObj[tempArg0, ... tempArgN]
- // tempObj[tempArg0, ... tempArgN] = op(tempValue)
- // tempValue
-
- bool prefix = IsPrefix;
- var index = (IndexExpression)_operand;
- int count = index.Arguments.Count;
- var block = new Expression[count + (prefix ? 2 : 4)];
- var temps = new ParameterExpression[count + (prefix ? 1 : 2)];
- var args = new ParameterExpression[count];
-
- int i = 0;
- temps[i] = Parameter(index.Object.Type, null);
- block[i] = Assign(temps[i], index.Object);
- i++;
- while (i <= count) {
- var arg = index.Arguments[i - 1];
- args[i - 1] = temps[i] = Parameter(arg.Type, null);
- block[i] = Assign(temps[i], arg);
- i++;
- }
- index = MakeIndex(temps[0], index.Indexer, new TrueReadOnlyCollection<Expression>(args));
- if (!prefix) {
- var lastTemp = temps[i] = Parameter(index.Type, null);
- block[i] = Assign(temps[i], index);
- i++;
- Debug.Assert(i == temps.Length);
- block[i++] = Assign(index, FunctionalOp(lastTemp));
- block[i++] = lastTemp;
- } else {
- Debug.Assert(i == temps.Length);
- block[i++] = Assign(index, FunctionalOp(index));
- }
- Debug.Assert(i == block.Length);
- return Block(new TrueReadOnlyCollection<ParameterExpression>(temps), new TrueReadOnlyCollection<Expression>(block));
- }
-
- /// <summary>
- /// Creates a new expression that is like this one, but using the
- /// supplied children. If all of the children are the same, it will
- /// return this expression.
- /// </summary>
- /// <param name="operand">The <see cref="Operand" /> property of the result.</param>
- /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
- public UnaryExpression Update(Expression operand) {
- if (operand == Operand) {
- return this;
- }
- return Expression.MakeUnary(NodeType, operand, Type, Method);
- }
- }
-
- public partial class Expression {
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"></see>, given an operand, by calling the appropriate factory method.
- /// </summary>
- /// <param name="unaryType">The <see cref="ExpressionType"></see> that specifies the type of unary operation.</param>
- /// <param name="operand">An <see cref="Expression"></see> that represents the operand.</param>
- /// <param name="type">The <see cref="Type"></see> that specifies the type to be converted to (pass null if not applicable).</param>
- /// <returns>The <see cref="UnaryExpression"></see> that results from calling the appropriate factory method.</returns>
- /// <exception cref="ArgumentException">Thrown when <paramref name="unaryType"/> does not correspond to a unary expression.</exception>
- /// <exception cref="ArgumentNullException">Thrown when <paramref name="operand"/> is null.</exception>
- public static UnaryExpression MakeUnary(ExpressionType unaryType, Expression operand, Type type) {
- return MakeUnary(unaryType, operand, type, null);
- }
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"></see>, given an operand and implementing method, by calling the appropriate factory method.
- /// </summary>
- /// <param name="unaryType">The <see cref="ExpressionType"></see> that specifies the type of unary operation.</param>
- /// <param name="operand">An <see cref="Expression"></see> that represents the operand.</param>
- /// <param name="type">The <see cref="Type"></see> that specifies the type to be converted to (pass null if not applicable).</param>
- /// <param name="method">The <see cref="MethodInfo"></see> that represents the implementing method.</param>
- /// <returns>The <see cref="UnaryExpression"></see> that results from calling the appropriate factory method.</returns>
- /// <exception cref="ArgumentException">Thrown when <paramref name="unaryType"/> does not correspond to a unary expression.</exception>
- /// <exception cref="ArgumentNullException">Thrown when <paramref name="operand"/> is null.</exception>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- public static UnaryExpression MakeUnary(ExpressionType unaryType, Expression operand, Type type, MethodInfo method) {
- switch (unaryType) {
- case ExpressionType.Negate:
- return Negate(operand, method);
- case ExpressionType.NegateChecked:
- return NegateChecked(operand, method);
- case ExpressionType.Not:
- return Not(operand, method);
- case ExpressionType.IsFalse:
- return IsFalse(operand, method);
- case ExpressionType.IsTrue:
- return IsTrue(operand, method);
- case ExpressionType.OnesComplement:
- return OnesComplement(operand, method);
- case ExpressionType.ArrayLength:
- return ArrayLength(operand);
- case ExpressionType.Convert:
- return Convert(operand, type, method);
- case ExpressionType.ConvertChecked:
- return ConvertChecked(operand, type, method);
- case ExpressionType.Throw:
- return Throw(operand, type);
- case ExpressionType.TypeAs:
- return TypeAs(operand, type);
- case ExpressionType.Quote:
- return Quote(operand);
- case ExpressionType.UnaryPlus:
- return UnaryPlus(operand, method);
- case ExpressionType.Unbox:
- return Unbox(operand, type);
- case ExpressionType.Increment:
- return Increment(operand, method);
- case ExpressionType.Decrement:
- return Decrement(operand, method);
- case ExpressionType.PreIncrementAssign:
- return PreIncrementAssign(operand, method);
- case ExpressionType.PostIncrementAssign:
- return PostIncrementAssign(operand, method);
- case ExpressionType.PreDecrementAssign:
- return PreDecrementAssign(operand, method);
- case ExpressionType.PostDecrementAssign:
- return PostDecrementAssign(operand, method);
- default:
- throw Error.UnhandledUnary(unaryType);
- }
- }
-
- private static UnaryExpression GetUserDefinedUnaryOperatorOrThrow(ExpressionType unaryType, string name, Expression operand) {
- UnaryExpression u = GetUserDefinedUnaryOperator(unaryType, name, operand);
- if (u != null) {
- ValidateParamswithOperandsOrThrow(u.Method.GetParametersCached()[0].ParameterType, operand.Type, unaryType, name);
- return u;
- }
- throw Error.UnaryOperatorNotDefined(unaryType, operand.Type);
- }
-
- private static UnaryExpression GetUserDefinedUnaryOperator(ExpressionType unaryType, string name, Expression operand) {
- Type operandType = operand.Type;
- Type[] types = new Type[] { operandType };
- Type nnOperandType = TypeUtils.GetNonNullableType(operandType);
- BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
- MethodInfo method = nnOperandType.GetMethodValidated(name, flags, null, types, null);
- if (method != null) {
- return new UnaryExpression(unaryType, operand, method.ReturnType, method);
- }
- // try lifted call
- if (TypeUtils.IsNullableType(operandType)) {
- types[0] = nnOperandType;
- method = nnOperandType.GetMethodValidated(name, flags, null, types, null);
- if (method != null && method.ReturnType.IsValueType && !TypeUtils.IsNullableType(method.ReturnType)) {
- return new UnaryExpression(unaryType, operand, TypeUtils.GetNullableType(method.ReturnType), method);
- }
- }
- return null;
- }
-
- private static UnaryExpression GetMethodBasedUnaryOperator(ExpressionType unaryType, Expression operand, MethodInfo method) {
- System.Diagnostics.Debug.Assert(method != null);
- ValidateOperator(method);
- ParameterInfo[] pms = method.GetParametersCached();
- if (pms.Length != 1)
- throw Error.IncorrectNumberOfMethodCallArguments(method);
- if (ParameterIsAssignable(pms[0], operand.Type)) {
- ValidateParamswithOperandsOrThrow(pms[0].ParameterType, operand.Type, unaryType, method.Name);
- return new UnaryExpression(unaryType, operand, method.ReturnType, method);
- }
- // check for lifted call
- if (TypeUtils.IsNullableType(operand.Type) &&
- ParameterIsAssignable(pms[0], TypeUtils.GetNonNullableType(operand.Type)) &&
- method.ReturnType.IsValueType && !TypeUtils.IsNullableType(method.ReturnType)) {
- return new UnaryExpression(unaryType, operand, TypeUtils.GetNullableType(method.ReturnType), method);
- }
-
- throw Error.OperandTypesDoNotMatchParameters(unaryType, method.Name);
- }
-
- private static UnaryExpression GetUserDefinedCoercionOrThrow(ExpressionType coercionType, Expression expression, Type convertToType) {
- UnaryExpression u = GetUserDefinedCoercion(coercionType, expression, convertToType);
- if (u != null) {
- return u;
- }
- throw Error.CoercionOperatorNotDefined(expression.Type, convertToType);
- }
-
- private static UnaryExpression GetUserDefinedCoercion(ExpressionType coercionType, Expression expression, Type convertToType) {
- MethodInfo method = TypeUtils.GetUserDefinedCoercionMethod(expression.Type, convertToType, false);
- if (method != null) {
- return new UnaryExpression(coercionType, expression, convertToType, method);
- } else {
- return null;
- }
- }
-
- private static UnaryExpression GetMethodBasedCoercionOperator(ExpressionType unaryType, Expression operand, Type convertToType, MethodInfo method) {
- System.Diagnostics.Debug.Assert(method != null);
- ValidateOperator(method);
- ParameterInfo[] pms = method.GetParametersCached();
- if (pms.Length != 1) {
- throw Error.IncorrectNumberOfMethodCallArguments(method);
- }
- if (ParameterIsAssignable(pms[0], operand.Type) && TypeUtils.AreEquivalent(method.ReturnType, convertToType)) {
- return new UnaryExpression(unaryType, operand, method.ReturnType, method);
- }
- // check for lifted call
- if ((TypeUtils.IsNullableType(operand.Type) || TypeUtils.IsNullableType(convertToType)) &&
- ParameterIsAssignable(pms[0], TypeUtils.GetNonNullableType(operand.Type)) &&
- TypeUtils.AreEquivalent(method.ReturnType, TypeUtils.GetNonNullableType(convertToType))) {
- return new UnaryExpression(unaryType, operand, convertToType, method);
- }
- throw Error.OperandTypesDoNotMatchParameters(unaryType, method.Name);
- }
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"></see> that represents an arithmetic negation operation.
- /// </summary>
- /// <param name="expression">An <see cref="Expression"></see> to set the <see cref="P:UnaryExpression.Operand"></see> property equal to.</param>
- /// <returns>A <see cref="UnaryExpression"></see> that has the <see cref="P:Expression.NodeType"></see> property equal to <see cref="P:ExpressionType.Negate"></see> and the <see cref="P:UnaryExpression.Operand"></see> properties set to the specified value.</returns>
- /// <exception cref="ArgumentNullException">Thrown when <paramref name="expression"/> is null.</exception>
- /// <exception cref="InvalidOperationException">Thrown when the unary minus operator is not defined for <see cref="P:Expression.Type"></see></exception>
- public static UnaryExpression Negate(Expression expression) {
- return Negate(expression, null);
- }
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"></see> that represents an arithmetic negation operation.
- /// </summary>
- /// <param name="expression">An <see cref="Expression"></see> to set the <see cref="P:UnaryExpression.Operand"></see> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"></see> to set the <see cref="P:UnaryExpression.Method"></see> property equal to.</param>
- /// <returns>A <see cref="UnaryExpression"></see> that has the <see cref="P:Expression.NodeType"></see> property equal to <see cref="P:ExpressionType.Negate"></see> and the <see cref="P:UnaryExpression.Operand"></see> and <see cref="P:UnaryExpression.Method"></see> properties set to the specified value.</returns>
- /// <exception cref="ArgumentNullException">Thrown when <paramref name="expression"/> is null.</exception>
- /// <exception cref="ArgumentException">Thrown when <paramref name="method"/> is not null and the method it represents returns void, is not static (Shared in Visual Basic), or does not take exactly one argument.</exception>
- /// <exception cref="InvalidOperationException">Thown when <paramref name="method"/> is null and the unary minus operator is not defined for expression.Type or expression.Type (or its corresponding non-nullable type if it is a nullable value type) is not assignable to the argument type of the method represented by method.</exception>
- public static UnaryExpression Negate(Expression expression, MethodInfo method) {
- RequiresCanRead(expression, "expression");
- if (method == null) {
- if (TypeUtils.IsArithmetic(expression.Type) && !TypeUtils.IsUnsignedInt(expression.Type)) {
- return new UnaryExpression(ExpressionType.Negate, expression, expression.Type, null);
- }
- return GetUserDefinedUnaryOperatorOrThrow(ExpressionType.Negate, "op_UnaryNegation", expression);
- }
- return GetMethodBasedUnaryOperator(ExpressionType.Negate, expression, method);
- }
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"></see> that represents a unary plus operation.
- /// </summary>
- /// <param name="expression">An <see cref="Expression"></see> to set the <see cref="UnaryExpression.Operand"></see> property equal to.</param>
- /// <returns>A <see cref="UnaryExpression"></see> that has the <see cref="Expression.NodeType"></see> property equal to <see cref="ExpressionType.UnaryPlus"></see> and the <see cref="UnaryExpression.Operand"></see> property set to the specified value.</returns>
- /// <exception cref="ArgumentNullException">Thrown when <paramref name="expression"/> is null.</exception>
- /// <exception cref="InvalidOperationException">Thown when the unary minus operator is not defined for expression.Type.</exception>
- public static UnaryExpression UnaryPlus(Expression expression) {
- return UnaryPlus(expression, null);
- }
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"></see> that represents a unary plus operation.
- /// </summary>
- /// <param name="expression">An <see cref="Expression"></see> to set the <see cref="UnaryExpression.Operand"></see> property equal to.</param>
- /// <param name="method">A <see cref="MethodInfo"></see> to set the <see cref="UnaryExpression.Method"></see> property equal to.</param>
- /// <returns>A <see cref="UnaryExpression"></see> that has the <see cref="Expression.NodeType"></see> property equal to <see cref="ExpressionType.UnaryPlus"></see> and the <see cref="UnaryExpression.Operand"></see> and <see cref="UnaryExpression.Method"></see>property set to the specified value.</returns>
- /// <exception cref="ArgumentNullException">Thrown when <paramref name="expression"/> is null.</exception>
- /// <exception cref="ArgumentException">Thrown when <paramref name="method"/> is not null and the method it represents returns void, is not static (Shared in Visual Basic), or does not take exactly one argument.</exception>
- /// <exception cref="InvalidOperationException">Thown when <paramref name="method"/> is null and the unary minus operator is not defined for expression.Type or expression.Type (or its corresponding non-nullable type if it is a nullable value type) is not assignable to the argument type of the method represented by method.</exception>
- public static UnaryExpression UnaryPlus(Expression expression, MethodInfo method) {
- RequiresCanRead(expression, "expression");
- if (method == null) {
- if (TypeUtils.IsArithmetic(expression.Type)) {
- return new UnaryExpression(ExpressionType.UnaryPlus, expression, expression.Type, null);
- }
- return GetUserDefinedUnaryOperatorOrThrow(ExpressionType.UnaryPlus, "op_UnaryPlus", expression);
- }
- return GetMethodBasedUnaryOperator(ExpressionType.UnaryPlus, expression, method);
- }
-
- /// <summary>Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents an arithmetic negation operation that has overflow checking.</summary>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.NegateChecked" /> and the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property set to the specified value.</returns>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property equal to.</param>
- /// <exception cref="T:System.ArgumentNullException">
- /// Thrown when <paramref name="expression" /> is null.</exception>
- /// <exception cref="T:System.InvalidOperationException">Thrown when the unary minus operator is not defined for <paramref name="expression" />.Type.</exception>
- public static UnaryExpression NegateChecked(Expression expression) {
- return NegateChecked(expression, null);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents an arithmetic negation operation that has overflow checking. The implementing method can be specified.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.UnaryExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.NegateChecked" /> and the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> and <see cref="P:System.Linq.Expressions.UnaryExpression.Method" /> properties set to the specified values.</returns>
- ///<param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property equal to.</param>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Method" /> property equal to.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="expression" /> is null.</exception>
- ///<exception cref="T:System.ArgumentException">
- ///<paramref name="method" /> is not null and the method it represents returns void, is not static (Shared in Visual Basic), or does not take exactly one argument.</exception>
- ///<exception cref="T:System.InvalidOperationException">
- ///<paramref name="method" /> is null and the unary minus operator is not defined for <paramref name="expression" />.Type.-or-<paramref name="expression" />.Type (or its corresponding non-nullable type if it is a nullable value type) is not assignable to the argument type of the method represented by <paramref name="method" />.</exception>
- public static UnaryExpression NegateChecked(Expression expression, MethodInfo method) {
- RequiresCanRead(expression, "expression");
- if (method == null) {
- if (TypeUtils.IsArithmetic(expression.Type) && !TypeUtils.IsUnsignedInt(expression.Type)) {
- return new UnaryExpression(ExpressionType.NegateChecked, expression, expression.Type, null);
- }
- return GetUserDefinedUnaryOperatorOrThrow(ExpressionType.NegateChecked, "op_UnaryNegation", expression);
- }
- return GetMethodBasedUnaryOperator(ExpressionType.NegateChecked, expression, method);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents a bitwise complement operation.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.UnaryExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Not" /> and the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property set to the specified value.</returns>
- ///<param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property equal to.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="expression" /> is null.</exception>
- ///<exception cref="T:System.InvalidOperationException">The unary not operator is not defined for <paramref name="expression" />.Type.</exception>
- public static UnaryExpression Not(Expression expression) {
- return Not(expression, null);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents a bitwise complement operation. The implementing method can be specified.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.UnaryExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Not" /> and the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> and <see cref="P:System.Linq.Expressions.UnaryExpression.Method" /> properties set to the specified values.</returns>
- ///<param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property equal to.</param>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Method" /> property equal to.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="expression" /> is null.</exception>
- ///<exception cref="T:System.ArgumentException">
- ///<paramref name="method" /> is not null and the method it represents returns void, is not static (Shared in Visual Basic), or does not take exactly one argument.</exception>
- ///<exception cref="T:System.InvalidOperationException">
- ///<paramref name="method" /> is null and the unary not operator is not defined for <paramref name="expression" />.Type.-or-<paramref name="expression" />.Type (or its corresponding non-nullable type if it is a nullable value type) is not assignable to the argument type of the method represented by <paramref name="method" />.</exception>
- public static UnaryExpression Not(Expression expression, MethodInfo method) {
- RequiresCanRead(expression, "expression");
- if (method == null) {
- if (TypeUtils.IsIntegerOrBool(expression.Type)) {
- return new UnaryExpression(ExpressionType.Not, expression, expression.Type, null);
- }
- UnaryExpression u = GetUserDefinedUnaryOperator(ExpressionType.Not, "op_LogicalNot", expression);
- if (u != null) {
- return u;
- }
- return GetUserDefinedUnaryOperatorOrThrow(ExpressionType.Not, "op_OnesComplement", expression);
- }
- return GetMethodBasedUnaryOperator(ExpressionType.Not, expression, method);
- }
-
- /// <summary>
- /// Returns whether the expression evaluates to false.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to evaluate.</param>
- /// <returns>An instance of <see cref="UnaryExpression"/>.</returns>
- public static UnaryExpression IsFalse(Expression expression) {
- return IsFalse(expression, null);
- }
-
- /// <summary>
- /// Returns whether the expression evaluates to false.
- /// </summary>
- ///<param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to evaluate.</param>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> that represents the implementing method.</param>
- /// <returns>An instance of <see cref="UnaryExpression"/>.</returns>
- public static UnaryExpression IsFalse(Expression expression, MethodInfo method) {
- RequiresCanRead(expression, "expression");
- if (method == null) {
- if (TypeUtils.IsBool(expression.Type)) {
- return new UnaryExpression(ExpressionType.IsFalse, expression, expression.Type, null);
- }
- return GetUserDefinedUnaryOperatorOrThrow(ExpressionType.IsFalse, "op_False", expression);
- }
- return GetMethodBasedUnaryOperator(ExpressionType.IsFalse, expression, method);
- }
-
- /// <summary>
- /// Returns whether the expression evaluates to true.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to evaluate.</param>
- /// <returns>An instance of <see cref="UnaryExpression"/>.</returns>
- public static UnaryExpression IsTrue(Expression expression) {
- return IsTrue(expression, null);
- }
-
- /// <summary>
- /// Returns whether the expression evaluates to true.
- /// </summary>
- ///<param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to evaluate.</param>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> that represents the implementing method.</param>
- /// <returns>An instance of <see cref="UnaryExpression"/>.</returns>
- public static UnaryExpression IsTrue(Expression expression, MethodInfo method) {
- RequiresCanRead(expression, "expression");
- if (method == null) {
- if (TypeUtils.IsBool(expression.Type)) {
- return new UnaryExpression(ExpressionType.IsTrue, expression, expression.Type, null);
- }
- return GetUserDefinedUnaryOperatorOrThrow(ExpressionType.IsTrue, "op_True", expression);
- }
- return GetMethodBasedUnaryOperator(ExpressionType.IsTrue, expression, method);
- }
-
- /// <summary>
- /// Returns the expression representing the ones complement.
- /// </summary>
- ///<param name="expression">An <see cref="T:System.Linq.Expressions.Expression" />.</param>
- /// <returns>An instance of <see cref="UnaryExpression"/>.</returns>
- public static UnaryExpression OnesComplement(Expression expression) {
- return OnesComplement(expression, null);
- }
-
- /// <summary>
- /// Returns the expression representing the ones complement.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression" />.</param>
- /// <param name="method">A <see cref="T:System.Reflection.MethodInfo" /> that represents the implementing method.</param>
- /// <returns>An instance of <see cref="UnaryExpression"/>.</returns>
- public static UnaryExpression OnesComplement(Expression expression, MethodInfo method) {
- RequiresCanRead(expression, "expression");
- if (method == null) {
- if (TypeUtils.IsInteger(expression.Type)) {
- return new UnaryExpression(ExpressionType.OnesComplement, expression, expression.Type, null);
- }
- return GetUserDefinedUnaryOperatorOrThrow(ExpressionType.OnesComplement, "op_OnesComplement", expression);
- }
- return GetMethodBasedUnaryOperator(ExpressionType.OnesComplement, expression, method);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents an explicit reference or boxing conversion where null is supplied if the conversion fails.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.UnaryExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.TypeAs" /> and the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> and <see cref="P:System.Linq.Expressions.Expression.Type" /> properties set to the specified values.</returns>
- ///<param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property equal to.</param>
- ///<param name="type">A <see cref="T:System.Type" /> to set the <see cref="P:System.Linq.Expressions.Expression.Type" /> property equal to.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="expression" /> or <paramref name="type" /> is null.</exception>
- public static UnaryExpression TypeAs(Expression expression, Type type) {
- RequiresCanRead(expression, "expression");
- ContractUtils.RequiresNotNull(type, "type");
- TypeUtils.ValidateType(type);
-
- if (type.IsValueType && !TypeUtils.IsNullableType(type)) {
- throw Error.IncorrectTypeForTypeAs(type);
- }
- return new UnaryExpression(ExpressionType.TypeAs, expression, type, null);
- }
-
- /// <summary>
- /// <summary>Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents an explicit unboxing.</summary>
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to unbox.</param>
- /// <param name="type">The new <see cref="T:System.Type" /> of the expression.</param>
- /// <returns>An instance of <see cref="UnaryExpression"/>.</returns>
- public static UnaryExpression Unbox(Expression expression, Type type) {
- RequiresCanRead(expression, "expression");
- ContractUtils.RequiresNotNull(type, "type");
- if (!expression.Type.IsInterface && expression.Type != typeof(object)) {
- throw Error.InvalidUnboxType();
- }
- if (!type.IsValueType) throw Error.InvalidUnboxType();
- TypeUtils.ValidateType(type);
- return new UnaryExpression(ExpressionType.Unbox, expression, type, null);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents a conversion operation.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.UnaryExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Convert" /> and the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> and <see cref="P:System.Linq.Expressions.Expression.Type" /> properties set to the specified values.</returns>
- ///<param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property equal to.</param>
- ///<param name="type">A <see cref="T:System.Type" /> to set the <see cref="P:System.Linq.Expressions.Expression.Type" /> property equal to.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="expression" /> or <paramref name="type" /> is null.</exception>
- ///<exception cref="T:System.InvalidOperationException">No conversion operator is defined between <paramref name="expression" />.Type and <paramref name="type" />.</exception>
- public static UnaryExpression Convert(Expression expression, Type type) {
- return Convert(expression, type, null);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents a conversion operation for which the implementing method is specified.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.UnaryExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Convert" /> and the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" />, <see cref="P:System.Linq.Expressions.Expression.Type" />, and <see cref="P:System.Linq.Expressions.UnaryExpression.Method" /> properties set to the specified values.</returns>
- ///<param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property equal to.</param>
- ///<param name="type">A <see cref="T:System.Type" /> to set the <see cref="P:System.Linq.Expressions.Expression.Type" /> property equal to.</param>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Method" /> property equal to.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="expression" /> or <paramref name="type" /> is null.</exception>
- ///<exception cref="T:System.ArgumentException">
- ///<paramref name="method" /> is not null and the method it represents returns void, is not static (Shared in Visual Basic), or does not take exactly one argument.</exception>
- ///<exception cref="T:System.Reflection.AmbiguousMatchException">More than one method that matches the <paramref name="method" /> description was found.</exception>
- ///<exception cref="T:System.InvalidOperationException">No conversion operator is defined between <paramref name="expression" />.Type and <paramref name="type" />.-or-<paramref name="expression" />.Type is not assignable to the argument type of the method represented by <paramref name="method" />.-or-The return type of the method represented by <paramref name="method" /> is not assignable to <paramref name="type" />.-or-<paramref name="expression" />.Type or <paramref name="type" /> is a nullable value type and the corresponding non-nullable value type does not equal the argument type or the return type, respectively, of the method represented by <paramref name="method" />.</exception>
- public static UnaryExpression Convert(Expression expression, Type type, MethodInfo method) {
- RequiresCanRead(expression, "expression");
- ContractUtils.RequiresNotNull(type, "type");
- TypeUtils.ValidateType(type);
-
- if (method == null) {
- if (TypeUtils.HasIdentityPrimitiveOrNullableConversion(expression.Type, type) ||
- TypeUtils.HasReferenceConversion(expression.Type, type)) {
- return new UnaryExpression(ExpressionType.Convert, expression, type, null);
- }
- return GetUserDefinedCoercionOrThrow(ExpressionType.Convert, expression, type);
- }
- return GetMethodBasedCoercionOperator(ExpressionType.Convert, expression, type, method);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents a conversion operation that throws an exception if the target type is overflowed.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.UnaryExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.ConvertChecked" /> and the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> and <see cref="P:System.Linq.Expressions.Expression.Type" /> properties set to the specified values.</returns>
- ///<param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property equal to.</param>
- ///<param name="type">A <see cref="T:System.Type" /> to set the <see cref="P:System.Linq.Expressions.Expression.Type" /> property equal to.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="expression" /> or <paramref name="type" /> is null.</exception>
- ///<exception cref="T:System.InvalidOperationException">No conversion operator is defined between <paramref name="expression" />.Type and <paramref name="type" />.</exception>
- public static UnaryExpression ConvertChecked(Expression expression, Type type) {
- return ConvertChecked(expression, type, null);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents a conversion operation that throws an exception if the target type is overflowed and for which the implementing method is specified.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.UnaryExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.ConvertChecked" /> and the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" />, <see cref="P:System.Linq.Expressions.Expression.Type" />, and <see cref="P:System.Linq.Expressions.UnaryExpression.Method" /> properties set to the specified values.</returns>
- ///<param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property equal to.</param>
- ///<param name="type">A <see cref="T:System.Type" /> to set the <see cref="P:System.Linq.Expressions.Expression.Type" /> property equal to.</param>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Method" /> property equal to.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="expression" /> or <paramref name="type" /> is null.</exception>
- ///<exception cref="T:System.ArgumentException">
- ///<paramref name="method" /> is not null and the method it represents returns void, is not static (Shared in Visual Basic), or does not take exactly one argument.</exception>
- ///<exception cref="T:System.Reflection.AmbiguousMatchException">More than one method that matches the <paramref name="method" /> description was found.</exception>
- ///<exception cref="T:System.InvalidOperationException">No conversion operator is defined between <paramref name="expression" />.Type and <paramref name="type" />.-or-<paramref name="expression" />.Type is not assignable to the argument type of the method represented by <paramref name="method" />.-or-The return type of the method represented by <paramref name="method" /> is not assignable to <paramref name="type" />.-or-<paramref name="expression" />.Type or <paramref name="type" /> is a nullable value type and the corresponding non-nullable value type does not equal the argument type or the return type, respectively, of the method represented by <paramref name="method" />.</exception>
- public static UnaryExpression ConvertChecked(Expression expression, Type type, MethodInfo method) {
- RequiresCanRead(expression, "expression");
- ContractUtils.RequiresNotNull(type, "type");
- TypeUtils.ValidateType(type);
-
- if (method == null) {
- if (TypeUtils.HasIdentityPrimitiveOrNullableConversion(expression.Type, type)) {
- return new UnaryExpression(ExpressionType.ConvertChecked, expression, type, null);
- }
- if (TypeUtils.HasReferenceConversion(expression.Type, type)) {
- return new UnaryExpression(ExpressionType.Convert, expression, type, null);
- }
- return GetUserDefinedCoercionOrThrow(ExpressionType.ConvertChecked, expression, type);
- }
- return GetMethodBasedCoercionOperator(ExpressionType.ConvertChecked, expression, type, method);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents getting the length of a one-dimensional array.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.UnaryExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.ArrayLength" /> and the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property equal to <paramref name="array" />.</returns>
- ///<param name="array">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property equal to.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="array" /> is null.</exception>
- ///<exception cref="T:System.ArgumentException">
- ///<paramref name="array" />.Type does not represent an array type.</exception>
- public static UnaryExpression ArrayLength(Expression array) {
- ContractUtils.RequiresNotNull(array, "array");
- if (!array.Type.IsArray || !typeof(Array).IsAssignableFrom(array.Type)) {
- throw Error.ArgumentMustBeArray();
- }
- if (array.Type.GetArrayRank() != 1) {
- throw Error.ArgumentMustBeSingleDimensionalArrayType();
- }
- return new UnaryExpression(ExpressionType.ArrayLength, array, typeof(int), null);
- }
-
- ///<summary>Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents an expression that has a constant value of type <see cref="T:System.Linq.Expressions.Expression" />.</summary>
- ///<returns>A <see cref="T:System.Linq.Expressions.UnaryExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Quote" /> and the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property set to the specified value.</returns>
- ///<param name="expression">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> property equal to.</param>
- ///<exception cref="T:System.ArgumentNullException">
- ///<paramref name="expression" /> is null.</exception>
- public static UnaryExpression Quote(Expression expression) {
- RequiresCanRead(expression, "expression");
- bool validQuote = expression is LambdaExpression;
- if (!validQuote) throw Error.QuotedExpressionMustBeLambda();
- return new UnaryExpression(ExpressionType.Quote, expression, expression.GetType(), null);
- }
-
- /// <summary>
- /// Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents a rethrowing of an exception.
- /// </summary>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents a rethrowing of an exception.</returns>
- public static UnaryExpression Rethrow() {
- return Throw(null);
- }
-
- /// <summary>
- /// Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents a rethrowing of an exception with a given type.
- /// </summary>
- ///<param name="type">The new <see cref="T:System.Type" /> of the expression.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents a rethrowing of an exception.</returns>
- public static UnaryExpression Rethrow(Type type) {
- return Throw(null, type);
- }
-
- /// <summary>
- /// Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents a throwing of an exception.
- /// </summary>
- /// <param name="value">An <see cref="T:System.Linq.Expressions.Expression" />.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the exception.</returns>
- public static UnaryExpression Throw(Expression value) {
- return Throw(value, typeof(void));
- }
-
- /// <summary>
- /// Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents a throwing of a value with a given type.
- /// </summary>
- /// <param name="value">An <see cref="T:System.Linq.Expressions.Expression" />.</param>
- /// <param name="type">The new <see cref="T:System.Type" /> of the expression.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the exception.</returns>
- public static UnaryExpression Throw(Expression value, Type type) {
- ContractUtils.RequiresNotNull(type, "type");
- TypeUtils.ValidateType(type);
-
- if (value != null) {
- RequiresCanRead(value, "value");
- if (value.Type.IsValueType) throw Error.ArgumentMustNotHaveValueType();
- }
- return new UnaryExpression(ExpressionType.Throw, value, type, null);
- }
-
- /// <summary>
- /// Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents the incrementing of the expression by 1.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression"></see> to increment.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the incremented expression.</returns>
- public static UnaryExpression Increment(Expression expression) {
- return Increment(expression, null);
- }
-
- /// <summary>
- /// Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents the incrementing of the expression by 1.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression"></see> to increment.</param>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> that represents the implementing method.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the incremented expression.</returns>
- public static UnaryExpression Increment(Expression expression, MethodInfo method) {
- RequiresCanRead(expression, "expression");
- if (method == null) {
- if (TypeUtils.IsArithmetic(expression.Type)) {
- return new UnaryExpression(ExpressionType.Increment, expression, expression.Type, null);
- }
- return GetUserDefinedUnaryOperatorOrThrow(ExpressionType.Increment, "op_Increment", expression);
- }
- return GetMethodBasedUnaryOperator(ExpressionType.Increment, expression, method);
- }
-
- /// <summary>
- /// Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents the decrementing of the expression by 1.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression"></see> to decrement.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the decremented expression.</returns>
- public static UnaryExpression Decrement(Expression expression) {
- return Decrement(expression, null);
- }
-
- /// <summary>
- /// Creates a <see cref="T:System.Linq.Expressions.UnaryExpression" /> that represents the decrementing of the expression by 1.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression"></see> to decrement.</param>
- ///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> that represents the implementing method.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the decremented expression.</returns>
- public static UnaryExpression Decrement(Expression expression, MethodInfo method) {
- RequiresCanRead(expression, "expression");
- if (method == null) {
- if (TypeUtils.IsArithmetic(expression.Type)) {
- return new UnaryExpression(ExpressionType.Decrement, expression, expression.Type, null);
- }
- return GetUserDefinedUnaryOperatorOrThrow(ExpressionType.Decrement, "op_Decrement", expression);
- }
- return GetMethodBasedUnaryOperator(ExpressionType.Decrement, expression, method);
- }
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"/> that increments the expression by 1
- /// and assigns the result back to the expression.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression"></see> to apply the operations on.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the resultant expression.</returns>
- public static UnaryExpression PreIncrementAssign(Expression expression) {
- return MakeOpAssignUnary(ExpressionType.PreIncrementAssign, expression, null);
-
- }
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"/> that increments the expression by 1
- /// and assigns the result back to the expression.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression"></see> to apply the operations on.</param>
- /// <param name="method">A <see cref="T:System.Reflection.MethodInfo" /> that represents the implementing method.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the resultant expression.</returns>
- public static UnaryExpression PreIncrementAssign(Expression expression, MethodInfo method) {
- return MakeOpAssignUnary(ExpressionType.PreIncrementAssign, expression, method);
- }
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"/> that decrements the expression by 1
- /// and assigns the result back to the expression.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression"></see> to apply the operations on.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the resultant expression.</returns>
- public static UnaryExpression PreDecrementAssign(Expression expression) {
- return MakeOpAssignUnary(ExpressionType.PreDecrementAssign, expression, null);
- }
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"/> that decrements the expression by 1
- /// and assigns the result back to the expression.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression"></see> to apply the operations on.</param>
- /// <param name="method">A <see cref="T:System.Reflection.MethodInfo" /> that represents the implementing method.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the resultant expression.</returns>
- public static UnaryExpression PreDecrementAssign(Expression expression, MethodInfo method) {
- return MakeOpAssignUnary(ExpressionType.PreDecrementAssign, expression, method);
- }
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"/> that represents the assignment of the expression
- /// followed by a subsequent increment by 1 of the original expression.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression"></see> to apply the operations on.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the resultant expression.</returns>
- public static UnaryExpression PostIncrementAssign(Expression expression) {
- return MakeOpAssignUnary(ExpressionType.PostIncrementAssign, expression, null);
- }
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"/> that represents the assignment of the expression
- /// followed by a subsequent increment by 1 of the original expression.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression"></see> to apply the operations on.</param>
- /// <param name="method">A <see cref="T:System.Reflection.MethodInfo" /> that represents the implementing method.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the resultant expression.</returns>
- public static UnaryExpression PostIncrementAssign(Expression expression, MethodInfo method) {
- return MakeOpAssignUnary(ExpressionType.PostIncrementAssign, expression, method);
- }
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"/> that represents the assignment of the expression
- /// followed by a subsequent decrement by 1 of the original expression.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression"></see> to apply the operations on.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the resultant expression.</returns>
- public static UnaryExpression PostDecrementAssign(Expression expression) {
- return MakeOpAssignUnary(ExpressionType.PostDecrementAssign, expression, null);
- }
-
- /// <summary>
- /// Creates a <see cref="UnaryExpression"/> that represents the assignment of the expression
- /// followed by a subsequent decrement by 1 of the original expression.
- /// </summary>
- /// <param name="expression">An <see cref="T:System.Linq.Expressions.Expression"></see> to apply the operations on.</param>
- /// <param name="method">A <see cref="T:System.Reflection.MethodInfo" /> that represents the implementing method.</param>
- /// <returns>A <see cref="T:System.Linq.Expressions.UnaryExpression"/> that represents the resultant expression.</returns>
- public static UnaryExpression PostDecrementAssign(Expression expression, MethodInfo method) {
- return MakeOpAssignUnary(ExpressionType.PostDecrementAssign, expression, method);
- }
-
- private static UnaryExpression MakeOpAssignUnary(ExpressionType kind, Expression expression, MethodInfo method) {
- RequiresCanRead(expression, "expression");
- RequiresCanWrite(expression, "expression");
-
- UnaryExpression result;
- if (method == null) {
- if (TypeUtils.IsArithmetic(expression.Type)) {
- return new UnaryExpression(kind, expression, expression.Type, null);
- }
- string name;
- if (kind == ExpressionType.PreIncrementAssign || kind == ExpressionType.PostIncrementAssign) {
- name = "op_Increment";
- } else {
- name = "op_Decrement";
- }
- result = GetUserDefinedUnaryOperatorOrThrow(kind, name, expression);
- } else {
- result = GetMethodBasedUnaryOperator(kind, expression, method);
- }
- // return type must be assignable back to the operand type
- if (!TypeUtils.AreReferenceAssignable(expression.Type, result.Type)) {
- throw Error.UserDefinedOpMustHaveValidReturnType(kind, method.Name);
- }
- return result;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/AnalyzedTree.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/AnalyzedTree.cs
deleted file mode 100644
index 9afe053f9ac..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/AnalyzedTree.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics.SymbolStore;
-using System.Dynamic.Utils;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- internal sealed class AnalyzedTree {
- internal readonly Dictionary<object, CompilerScope> Scopes = new Dictionary<object, CompilerScope>();
- internal readonly Dictionary<LambdaExpression, BoundConstants> Constants = new Dictionary<LambdaExpression, BoundConstants>();
-
- internal DebugInfoGenerator DebugInfoGenerator { get; set; }
-
- // Created by VariableBinder
- internal AnalyzedTree() {
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/AssemblyGen.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/AssemblyGen.cs
deleted file mode 100644
index 2d436e41c7e..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/AssemblyGen.cs
+++ /dev/null
@@ -1,177 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-#if FEATURE_REFEMIT
-
-using System;
-using System.Collections.Generic;
-using System.Dynamic.Utils;
-using System.IO;
-using System.Reflection;
-using System.Reflection.Emit;
-using System.Security;
-using System.Text;
-using System.Threading;
-
-using Microsoft.Scripting.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- internal sealed class AssemblyGen {
- private static AssemblyGen _assembly;
-
- // Testing options. Only ever set in CLR2 build
- // configurations, see SetSaveAssemblies
-#if !FEATURE_CORE_DLR
- private static string _saveAssembliesPath;
- private static bool _saveAssemblies;
-#endif
-
- private readonly AssemblyBuilder _myAssembly;
- private readonly ModuleBuilder _myModule;
-
-#if !FEATURE_CORE_DLR && !SILVERLIGHT
- private readonly string _outFileName; // can be null iff !SaveAndReloadAssemblies
- private readonly string _outDir; // null means the current directory
-#endif
- private int _index;
-
- private static AssemblyGen Assembly {
- get {
- if (_assembly == null) {
- Interlocked.CompareExchange(ref _assembly, new AssemblyGen(), null);
- }
- return _assembly;
- }
- }
-
- private AssemblyGen() {
- var name = new AssemblyName("Snippets");
-
-#if SILVERLIGHT // AssemblyBuilderAccess.RunAndSave, Environment.CurrentDirectory
- _myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
- _myModule = _myAssembly.DefineDynamicModule(name.Name, false);
-#else
-
- // mark the assembly transparent so that it works in partial trust:
- var attributes = new[] {
- new CustomAttributeBuilder(typeof(SecurityTransparentAttribute).GetConstructor(ReflectionUtils.EmptyTypes), new object[0])
- };
-
-#if !FEATURE_CORE_DLR
- if (_saveAssemblies) {
- string outDir = _saveAssembliesPath ?? Directory.GetCurrentDirectory();
- try {
- outDir = Path.GetFullPath(outDir);
- } catch (Exception) {
- throw Error.InvalidOutputDir();
- }
- try {
- Path.Combine(outDir, name.Name + ".dll");
- } catch (ArgumentException) {
- throw Error.InvalidAsmNameOrExtension();
- }
-
- _outFileName = name.Name + ".dll";
- _outDir = outDir;
- _myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave, outDir,
- null, null, null, null, false, attributes);
-
- _myModule = _myAssembly.DefineDynamicModule(name.Name, _outFileName, false);
- } else
-#endif
- {
- _myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run, attributes);
- _myModule = _myAssembly.DefineDynamicModule(name.Name, false);
- }
-
- _myAssembly.DefineVersionInfoResource();
-#endif
- }
-
- private TypeBuilder DefineType(string name, Type parent, TypeAttributes attr) {
- ContractUtils.RequiresNotNull(name, "name");
- ContractUtils.RequiresNotNull(parent, "parent");
-
- StringBuilder sb = new StringBuilder(name);
-
- int index = Interlocked.Increment(ref _index);
- sb.Append("$");
- sb.Append(index);
-
- // There is a bug in Reflection.Emit that leads to
- // Unhandled Exception: System.Runtime.InteropServices.COMException (0x80131130): Record not found on lookup.
- // if there is any of the characters []*&+,\ in the type name and a method defined on the type is called.
- sb.Replace('+', '_').Replace('[', '_').Replace(']', '_').Replace('*', '_').Replace('&', '_').Replace(',', '_').Replace('\\', '_');
-
- name = sb.ToString();
-
- return _myModule.DefineType(name, attr, parent);
- }
-
- internal static TypeBuilder DefineDelegateType(string name) {
- return Assembly.DefineType(
- name,
- typeof(MulticastDelegate),
- TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass
- );
- }
-
-#if !FEATURE_CORE_DLR
- //Return the location of the saved assembly file.
- //The file location is used by PE verification in Microsoft.Scripting.
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
- internal string SaveAssembly() {
-#if !SILVERLIGHT // AssemblyBuilder.Save
- _myAssembly.Save(_outFileName, PortableExecutableKinds.ILOnly, ImageFileMachine.I386);
- return Path.Combine(_outDir, _outFileName);
-#else
- return null;
-#endif
- }
-
- // NOTE: this method is called through reflection from Microsoft.Scripting
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
- internal static void SetSaveAssemblies(bool enable, string directory) {
- _saveAssemblies = enable;
- _saveAssembliesPath = directory;
- }
-
- // NOTE: this method is called through reflection from Microsoft.Scripting
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
- internal static string[] SaveAssembliesToDisk() {
- if (!_saveAssemblies) {
- return new string[0];
- }
-
- var assemlyLocations = new List<string>();
-
- // first save all assemblies to disk:
- if (_assembly != null) {
- string assemblyLocation = _assembly.SaveAssembly();
- if (assemblyLocation != null) {
- assemlyLocations.Add(assemblyLocation);
- }
- _assembly = null;
- }
-
- return assemlyLocations.ToArray();
- }
-#endif
- }
-}
-#endif
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/BoundConstants.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/BoundConstants.cs
deleted file mode 100644
index e7b604209ca..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/BoundConstants.cs
+++ /dev/null
@@ -1,191 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection.Emit;
-using System.Runtime.CompilerServices;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- /// <summary>
- /// This type tracks "runtime" constants--live objects that appear in
- /// ConstantExpression nodes and must be bound to the delegate.
- /// </summary>
- internal sealed class BoundConstants {
-
- /// <summary>
- /// Constants can emit themselves as different types
- /// For caching purposes, we need to treat each distinct Type as a
- /// seperate thing to cache. (If we have to cast it on the way out, it
- /// ends up using a JIT temp and defeats the purpose of caching the
- /// value in a local)
- /// </summary>
- private struct TypedConstant : IEquatable<TypedConstant> {
- internal readonly object Value;
- internal readonly Type Type;
-
- internal TypedConstant(object value, Type type) {
- Value = value;
- Type = type;
- }
-
- public override int GetHashCode() {
- return ReferenceEqualityComparer<object>.Instance.GetHashCode(Value) ^ Type.GetHashCode();
- }
-
- public bool Equals(TypedConstant other) {
- return object.ReferenceEquals(Value, other.Value) && Type.Equals(other.Type);
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2231:OverloadOperatorEqualsOnOverridingValueTypeEquals")]
- public override bool Equals(object obj) {
- return (obj is TypedConstant) && Equals((TypedConstant)obj);
- }
- }
-
- /// <summary>
- /// The list of constants in the order they appear in the constant array
- /// </summary>
- private readonly List<object> _values = new List<object>();
-
- /// <summary>
- /// The index of each constant in the constant array
- /// </summary>
- private readonly Dictionary<object, int> _indexes = new Dictionary<object, int>(ReferenceEqualityComparer<object>.Instance);
-
- /// <summary>
- /// Each constant referenced within this lambda, and how often it was referenced
- /// </summary>
- private readonly Dictionary<TypedConstant, int> _references = new Dictionary<TypedConstant, int>();
-
- /// <summary>
- /// IL locals for storing frequently used constants
- /// </summary>
- private readonly Dictionary<TypedConstant, LocalBuilder> _cache = new Dictionary<TypedConstant, LocalBuilder>();
-
- internal int Count {
- get { return _values.Count; }
- }
-
- internal object[] ToArray() {
- return _values.ToArray();
- }
-
- /// <summary>
- /// Called by VariableBinder. Adds the constant to the list (if needed)
- /// and increases the reference count by one
- /// </summary>
- internal void AddReference(object value, Type type) {
- if (!_indexes.ContainsKey(value)) {
- _indexes.Add(value, _values.Count);
- _values.Add(value);
- }
- Helpers.IncrementCount(new TypedConstant(value, type), _references);
- }
-
- /// <summary>
- /// Emits a live object as a constant
- /// </summary>
- internal void EmitConstant(LambdaCompiler lc, object value, Type type) {
- Debug.Assert(!ILGen.CanEmitConstant(value, type));
-
- if (!lc.CanEmitBoundConstants) {
- throw Error.CannotCompileConstant(value);
- }
-
- LocalBuilder local;
- if (_cache.TryGetValue(new TypedConstant(value, type), out local)) {
- lc.IL.Emit(OpCodes.Ldloc, local);
- return;
- }
- EmitConstantsArray(lc);
- EmitConstantFromArray(lc, value, type);
- }
-
- /// <summary>
- /// Emit code to cache frequently used constants into IL locals,
- /// instead of pulling them out of the array each time
- /// </summary>
- internal void EmitCacheConstants(LambdaCompiler lc) {
- int count = 0;
- foreach (var reference in _references) {
- if (!lc.CanEmitBoundConstants) {
- throw Error.CannotCompileConstant(reference.Key.Value);
- }
-
- if (ShouldCache(reference.Value)) {
- count++;
- }
- }
- if (count == 0) {
- return;
- }
- EmitConstantsArray(lc);
-
- // The same lambda can be in multiple places in the tree, so we
- // need to clear any locals from last time.
- _cache.Clear();
-
- foreach (var reference in _references) {
- if (ShouldCache(reference.Value)) {
- if (--count > 0) {
- // Dup array to keep it on the stack
- lc.IL.Emit(OpCodes.Dup);
- }
- LocalBuilder local = lc.IL.DeclareLocal(reference.Key.Type);
- EmitConstantFromArray(lc, reference.Key.Value, local.LocalType);
- lc.IL.Emit(OpCodes.Stloc, local);
- _cache.Add(reference.Key, local);
- }
- }
- }
-
- private static bool ShouldCache(int refCount) {
- // This caching is too aggressive in the face of conditionals and
- // switch. Also, it is too conservative for variables used inside
- // of loops.
- return refCount > 2;
- }
-
- private static void EmitConstantsArray(LambdaCompiler lc) {
- Debug.Assert(lc.CanEmitBoundConstants); // this should've been checked already
-
- lc.EmitClosureArgument();
- lc.IL.Emit(OpCodes.Ldfld, typeof(Closure).GetField("Constants"));
- }
-
- private void EmitConstantFromArray(LambdaCompiler lc, object value, Type type) {
- int index;
- if (!_indexes.TryGetValue(value, out index)) {
- _indexes.Add(value, index = _values.Count);
- _values.Add(value);
- }
-
- lc.IL.EmitInt(index);
- lc.IL.Emit(OpCodes.Ldelem_Ref);
- if (type.IsValueType) {
- lc.IL.Emit(OpCodes.Unbox_Any, type);
- } else if (type != typeof(object)) {
- lc.IL.Emit(OpCodes.Castclass, type);
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/Closure.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/Closure.cs
deleted file mode 100644
index 6c8bd4bc3f1..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/Closure.cs
+++ /dev/null
@@ -1,51 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.ComponentModel;
-using System.Diagnostics;
-
-namespace System.Runtime.CompilerServices {
-
- /// <summary>
- /// This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
- /// Represents the runtime state of a dynamically generated method.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never), DebuggerStepThrough]
- public sealed class Closure {
- /// <summary>
- /// Represents the non-trivial constants and locally executable expressions that are referenced by a dynamically generated method.
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
- public readonly object[] Constants;
-
- /// <summary>
- /// Represents the hoisted local variables from the parent context.
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
- public readonly object[] Locals;
-
- /// <summary>
- /// Creates an object to hold state of a dynamically generated method.
- /// </summary>
- /// <param name="constants">The constant values used by the method.</param>
- /// <param name="locals">The hoisted local variables from the parent context.</param>
- public Closure(object[] constants, object[] locals) {
- Constants = constants;
- Locals = locals;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/CompilerScope.Storage.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/CompilerScope.Storage.cs
deleted file mode 100644
index 18e7d5aa882..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/CompilerScope.Storage.cs
+++ /dev/null
@@ -1,186 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Reflection;
-using System.Reflection.Emit;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
-
- internal sealed partial class CompilerScope {
-
- private abstract class Storage {
- internal readonly LambdaCompiler Compiler;
- internal readonly ParameterExpression Variable;
-
- internal Storage(LambdaCompiler compiler, ParameterExpression variable) {
- Compiler = compiler;
- Variable = variable;
- }
-
- internal abstract void EmitLoad();
- internal abstract void EmitAddress();
- internal abstract void EmitStore();
-
- internal virtual void EmitStore(Storage value) {
- value.EmitLoad();
- EmitStore();
- }
-
- internal virtual void FreeLocal() {
- }
- }
-
- private sealed class LocalStorage : Storage {
- private readonly LocalBuilder _local;
-
- internal LocalStorage(LambdaCompiler compiler, ParameterExpression variable)
- : base(compiler, variable) {
- // ByRef variables are supported. This is used internally by
- // the compiler when emitting an inlined lambda invoke, to
- // handle ByRef parameters. BlockExpression prevents this
- // from being exposed to user created trees.
- _local = compiler.GetNamedLocal(variable.IsByRef ? variable.Type.MakeByRefType() : variable.Type, variable);
- }
-
- internal override void EmitLoad() {
- Compiler.IL.Emit(OpCodes.Ldloc, _local);
- }
-
- internal override void EmitStore() {
- Compiler.IL.Emit(OpCodes.Stloc, _local);
- }
-
- internal override void EmitAddress() {
- Compiler.IL.Emit(OpCodes.Ldloca, _local);
- }
- }
-
- private sealed class ArgumentStorage : Storage {
- private readonly int _argument;
-
- internal ArgumentStorage(LambdaCompiler compiler, ParameterExpression p)
- : base(compiler, p) {
- _argument = compiler.GetLambdaArgument(compiler.Parameters.IndexOf(p));
- }
-
- internal override void EmitLoad() {
- Compiler.IL.EmitLoadArg(_argument);
- }
-
- internal override void EmitStore() {
- Compiler.IL.EmitStoreArg(_argument);
- }
-
- internal override void EmitAddress() {
- Compiler.IL.EmitLoadArgAddress(_argument);
- }
- }
-
- private sealed class ElementBoxStorage : Storage {
- private readonly int _index;
- private readonly Storage _array;
- private readonly Type _boxType;
- private readonly FieldInfo _boxValueField;
-
- internal ElementBoxStorage(Storage array, int index, ParameterExpression variable)
- : base(array.Compiler, variable) {
- _array = array;
- _index = index;
- _boxType = typeof(StrongBox<>).MakeGenericType(variable.Type);
- _boxValueField = _boxType.GetField("Value");
- }
-
- internal override void EmitLoad() {
- EmitLoadBox();
- Compiler.IL.Emit(OpCodes.Ldfld, _boxValueField);
- }
-
- internal override void EmitStore() {
- LocalBuilder value = Compiler.GetLocal(Variable.Type);
- Compiler.IL.Emit(OpCodes.Stloc, value);
- EmitLoadBox();
- Compiler.IL.Emit(OpCodes.Ldloc, value);
- Compiler.FreeLocal(value);
- Compiler.IL.Emit(OpCodes.Stfld, _boxValueField);
- }
-
- internal override void EmitStore(Storage value) {
- EmitLoadBox();
- value.EmitLoad();
- Compiler.IL.Emit(OpCodes.Stfld, _boxValueField);
- }
-
- internal override void EmitAddress() {
- EmitLoadBox();
- Compiler.IL.Emit(OpCodes.Ldflda, _boxValueField);
- }
-
- internal void EmitLoadBox() {
- _array.EmitLoad();
- Compiler.IL.EmitInt(_index);
- Compiler.IL.Emit(OpCodes.Ldelem_Ref);
- Compiler.IL.Emit(OpCodes.Castclass, _boxType);
- }
- }
-
- private sealed class LocalBoxStorage : Storage {
- private readonly LocalBuilder _boxLocal;
- private readonly Type _boxType;
- private readonly FieldInfo _boxValueField;
-
- internal LocalBoxStorage(LambdaCompiler compiler, ParameterExpression variable)
- : base(compiler, variable) {
- _boxType = typeof(StrongBox<>).MakeGenericType(variable.Type);
- _boxValueField = _boxType.GetField("Value");
- _boxLocal = compiler.GetNamedLocal(_boxType, variable);
- }
-
- internal override void EmitLoad() {
- Compiler.IL.Emit(OpCodes.Ldloc, _boxLocal);
- Compiler.IL.Emit(OpCodes.Ldfld, _boxValueField);
- }
-
- internal override void EmitAddress() {
- Compiler.IL.Emit(OpCodes.Ldloc, _boxLocal);
- Compiler.IL.Emit(OpCodes.Ldflda, _boxValueField);
- }
-
- internal override void EmitStore() {
- LocalBuilder value = Compiler.GetLocal(Variable.Type);
- Compiler.IL.Emit(OpCodes.Stloc, value);
- Compiler.IL.Emit(OpCodes.Ldloc, _boxLocal);
- Compiler.IL.Emit(OpCodes.Ldloc, value);
- Compiler.FreeLocal(value);
- Compiler.IL.Emit(OpCodes.Stfld, _boxValueField);
- }
-
- internal override void EmitStore(Storage value) {
- Compiler.IL.Emit(OpCodes.Ldloc, _boxLocal);
- value.EmitLoad();
- Compiler.IL.Emit(OpCodes.Stfld, _boxValueField);
- }
-
- internal void EmitStoreBox() {
- Compiler.IL.Emit(OpCodes.Stloc, _boxLocal);
- }
- }
- }
-} \ No newline at end of file
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/CompilerScope.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/CompilerScope.cs
deleted file mode 100644
index 4391c6d6abb..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/CompilerScope.cs
+++ /dev/null
@@ -1,465 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Reflection.Emit;
-using System.Runtime.CompilerServices;
-using System.Dynamic;
-using System.Dynamic.Utils;
-using Microsoft.Scripting.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- internal enum VariableStorageKind {
- Local,
- Hoisted
- }
-
- /// <summary>
- /// CompilerScope is the data structure which the Compiler keeps information
- /// related to compiling scopes. It stores the following information:
- /// 1. Parent relationship (for resolving variables)
- /// 2. Information about hoisted variables
- /// 3. Information for resolving closures
- ///
- /// Instances are produced by VariableBinder, which does a tree walk
- /// looking for scope nodes: LambdaExpression and BlockExpression.
- /// </summary>
- internal sealed partial class CompilerScope {
- /// <summary>
- /// parent scope, if any
- /// </summary>
- private CompilerScope _parent;
-
- /// <summary>
- /// The expression node for this scope
- /// Can be LambdaExpression, BlockExpression, or CatchBlock
- /// </summary>
- internal readonly object Node;
-
- /// <summary>
- /// True if this node corresponds to an IL method.
- /// Can only be true if the Node is a LambdaExpression.
- /// But inlined lambdas will have it set to false.
- /// </summary>
- internal readonly bool IsMethod;
-
- /// <summary>
- /// Does this scope (or any inner scope) close over variables from any
- /// parent scope?
- /// Populated by VariableBinder
- /// </summary>
- internal bool NeedsClosure;
-
- /// <summary>
- /// Variables defined in this scope, and whether they're hoisted or not
- /// Populated by VariableBinder
- /// </summary>
- internal readonly Dictionary<ParameterExpression, VariableStorageKind> Definitions = new Dictionary<ParameterExpression, VariableStorageKind>();
-
- /// <summary>
- /// Each variable referenced within this scope, and how often it was referenced
- /// Populated by VariableBinder
- /// </summary>
- internal Dictionary<ParameterExpression, int> ReferenceCount;
-
- /// <summary>
- /// Scopes whose variables were merged into this one
- ///
- /// Created lazily as we create hundreds of compiler scopes w/o merging scopes when compiling rules.
- /// </summary>
- internal Set<object> MergedScopes;
-
- /// <summary>
- /// The scope's hoisted locals, if any.
- /// Provides storage for variables that are referenced from nested lambdas
- /// </summary>
- private HoistedLocals _hoistedLocals;
-
- /// <summary>
- /// The closed over hoisted locals
- /// </summary>
- private HoistedLocals _closureHoistedLocals;
-
- /// <summary>
- /// Mutable dictionary that maps non-hoisted variables to either local
- /// slots or argument slots
- /// </summary>
- private readonly Dictionary<ParameterExpression, Storage> _locals = new Dictionary<ParameterExpression, Storage>();
-
- internal CompilerScope(object node, bool isMethod) {
- Node = node;
- IsMethod = isMethod;
- var variables = GetVariables(node);
-
- Definitions = new Dictionary<ParameterExpression, VariableStorageKind>(variables.Count);
- foreach (var v in variables) {
- Definitions.Add(v, VariableStorageKind.Local);
- }
- }
-
- /// <summary>
- /// This scope's hoisted locals, or the closed over locals, if any
- /// Equivalent to: _hoistedLocals ?? _closureHoistedLocals
- /// </summary>
- internal HoistedLocals NearestHoistedLocals {
- get { return _hoistedLocals ?? _closureHoistedLocals; }
- }
-
- /// <summary>
- /// Called when entering a lambda/block. Performs all variable allocation
- /// needed, including creating hoisted locals and IL locals for accessing
- /// parent locals
- /// </summary>
- internal CompilerScope Enter(LambdaCompiler lc, CompilerScope parent) {
- SetParent(lc, parent);
-
- AllocateLocals(lc);
-
- if (IsMethod && _closureHoistedLocals != null) {
- EmitClosureAccess(lc, _closureHoistedLocals);
- }
-
- EmitNewHoistedLocals(lc);
-
- if (IsMethod) {
- EmitCachedVariables();
- }
-
- return this;
- }
-
- /// <summary>
- /// Frees unnamed locals, clears state associated with this compiler
- /// </summary>
- internal CompilerScope Exit() {
- // free scope's variables
- if (!IsMethod) {
- foreach (Storage storage in _locals.Values) {
- storage.FreeLocal();
- }
- }
-
- // Clear state that is associated with this parent
- // (because the scope can be reused in another context)
- CompilerScope parent = _parent;
- _parent = null;
- _hoistedLocals = null;
- _closureHoistedLocals = null;
- _locals.Clear();
-
- return parent;
- }
-
- #region LocalScopeExpression support
-
- internal void EmitVariableAccess(LambdaCompiler lc, ReadOnlyCollection<ParameterExpression> vars) {
- if (NearestHoistedLocals != null) {
- // Find what array each variable is on & its index
- var indexes = new List<long>(vars.Count);
-
- foreach (var variable in vars) {
- // For each variable, find what array it's defined on
- ulong parents = 0;
- HoistedLocals locals = NearestHoistedLocals;
- while (!locals.Indexes.ContainsKey(variable)) {
- parents++;
- locals = locals.Parent;
- Debug.Assert(locals != null);
- }
-
- // combine the number of parents we walked, with the
- // real index of variable to get the index to emit.
- ulong index = (parents << 32) | (uint)locals.Indexes[variable];
-
- indexes.Add((long)index);
- }
-
- if (indexes.Count > 0) {
- EmitGet(NearestHoistedLocals.SelfVariable);
- lc.EmitConstantArray(indexes.ToArray());
- lc.IL.Emit(OpCodes.Call, typeof(RuntimeOps).GetMethod("CreateRuntimeVariables", new[] { typeof(object[]), typeof(long[]) }));
- return;
- }
- }
-
- // No visible variables
- lc.IL.Emit(OpCodes.Call, typeof(RuntimeOps).GetMethod("CreateRuntimeVariables", ReflectionUtils.EmptyTypes));
- return;
- }
-
- #endregion
-
- #region Variable access
-
- /// <summary>
- /// Adds a new virtual variable corresponding to an IL local
- /// </summary>
- internal void AddLocal(LambdaCompiler gen, ParameterExpression variable) {
- _locals.Add(variable, new LocalStorage(gen, variable));
- }
-
- internal void EmitGet(ParameterExpression variable) {
- ResolveVariable(variable).EmitLoad();
- }
-
- internal void EmitSet(ParameterExpression variable) {
- ResolveVariable(variable).EmitStore();
- }
-
- internal void EmitAddressOf(ParameterExpression variable) {
- ResolveVariable(variable).EmitAddress();
- }
-
- private Storage ResolveVariable(ParameterExpression variable) {
- return ResolveVariable(variable, NearestHoistedLocals);
- }
-
- /// <summary>
- /// Resolve a local variable in this scope or a closed over scope
- /// Throws if the variable is defined
- /// </summary>
- private Storage ResolveVariable(ParameterExpression variable, HoistedLocals hoistedLocals) {
- // Search IL locals and arguments, but only in this lambda
- for (CompilerScope s = this; s != null; s = s._parent) {
- Storage storage;
- if (s._locals.TryGetValue(variable, out storage)) {
- return storage;
- }
-
- // if this is a lambda, we're done
- if (s.IsMethod) {
- break;
- }
- }
-
- // search hoisted locals
- for (HoistedLocals h = hoistedLocals; h != null; h = h.Parent) {
- int index;
- if (h.Indexes.TryGetValue(variable, out index)) {
- return new ElementBoxStorage(
- ResolveVariable(h.SelfVariable, hoistedLocals),
- index,
- variable
- );
- }
- }
-
- //
- // If this is an unbound variable in the lambda, the error will be
- // thrown from VariableBinder. So an error here is generally caused
- // by an internal error, e.g. a scope was created but it bypassed
- // VariableBinder.
- //
- throw Error.UndefinedVariable(variable.Name, variable.Type, CurrentLambdaName);
- }
-
- #endregion
-
- private void SetParent(LambdaCompiler lc, CompilerScope parent) {
- Debug.Assert(_parent == null && parent != this);
- _parent = parent;
-
- if (NeedsClosure && _parent != null) {
- _closureHoistedLocals = _parent.NearestHoistedLocals;
- }
-
- var hoistedVars = GetVariables().Where(p => Definitions[p] == VariableStorageKind.Hoisted).ToReadOnly();
-
- if (hoistedVars.Count > 0) {
- _hoistedLocals = new HoistedLocals(_closureHoistedLocals, hoistedVars);
- AddLocal(lc, _hoistedLocals.SelfVariable);
- }
- }
-
- // Emits creation of the hoisted local storage
- private void EmitNewHoistedLocals(LambdaCompiler lc) {
- if (_hoistedLocals == null) {
- return;
- }
-
- // create the array
- lc.IL.EmitInt(_hoistedLocals.Variables.Count);
- lc.IL.Emit(OpCodes.Newarr, typeof(object));
-
- // initialize all elements
- int i = 0;
- foreach (ParameterExpression v in _hoistedLocals.Variables) {
- // array[i] = new StrongBox<T>(...);
- lc.IL.Emit(OpCodes.Dup);
- lc.IL.EmitInt(i++);
- Type boxType = typeof(StrongBox<>).MakeGenericType(v.Type);
-
- if (IsMethod && lc.Parameters.Contains(v)) {
- // array[i] = new StrongBox<T>(argument);
- int index = lc.Parameters.IndexOf(v);
- lc.EmitLambdaArgument(index);
- lc.IL.Emit(OpCodes.Newobj, boxType.GetConstructor(new Type[] { v.Type }));
- } else if (v == _hoistedLocals.ParentVariable) {
- // array[i] = new StrongBox<T>(closure.Locals);
- ResolveVariable(v, _closureHoistedLocals).EmitLoad();
- lc.IL.Emit(OpCodes.Newobj, boxType.GetConstructor(new Type[] { v.Type }));
- } else {
-#if !FEATURE_CORE_DLR
- // array[i] = new StrongBox<T>(default(T));
- lc.IL.EmitDefault(v.Type);
- lc.IL.Emit(OpCodes.Newobj, boxType.GetConstructor(new Type[] { v.Type }));
-#else
- // array[i] = new StrongBox<T>();
- lc.IL.Emit(OpCodes.Newobj, boxType.GetConstructor(ReflectionUtils.EmptyTypes));
-#endif
- }
- // if we want to cache this into a local, do it now
- if (ShouldCache(v)) {
- lc.IL.Emit(OpCodes.Dup);
- CacheBoxToLocal(lc, v);
- }
- lc.IL.Emit(OpCodes.Stelem_Ref);
- }
-
- // store it
- EmitSet(_hoistedLocals.SelfVariable);
- }
-
- // If hoisted variables are referenced "enough", we cache the
- // StrongBox<T> in an IL local, which saves an array index and a cast
- // when we go to look it up later
- private void EmitCachedVariables() {
- if (ReferenceCount == null) {
- return;
- }
-
- foreach (var refCount in ReferenceCount) {
- if (ShouldCache(refCount.Key, refCount.Value)) {
- var storage = ResolveVariable(refCount.Key) as ElementBoxStorage;
- if (storage != null) {
- storage.EmitLoadBox();
- CacheBoxToLocal(storage.Compiler, refCount.Key);
- }
- }
- }
- }
-
- private bool ShouldCache(ParameterExpression v, int refCount) {
- // This caching is too aggressive in the face of conditionals and
- // switch. Also, it is too conservative for variables used inside
- // of loops.
- return refCount > 2 && !_locals.ContainsKey(v);
- }
-
- private bool ShouldCache(ParameterExpression v) {
- if (ReferenceCount == null) {
- return false;
- }
-
- int refCount;
- return ReferenceCount.TryGetValue(v, out refCount) && ShouldCache(v, refCount);
- }
-
- private void CacheBoxToLocal(LambdaCompiler lc, ParameterExpression v) {
- Debug.Assert(ShouldCache(v) && !_locals.ContainsKey(v));
- var local = new LocalBoxStorage(lc, v);
- local.EmitStoreBox();
- _locals.Add(v, local);
- }
-
- // Creates IL locals for accessing closures
- private void EmitClosureAccess(LambdaCompiler lc, HoistedLocals locals) {
- if (locals == null) {
- return;
- }
-
- EmitClosureToVariable(lc, locals);
-
- while ((locals = locals.Parent) != null) {
- var v = locals.SelfVariable;
- var local = new LocalStorage(lc, v);
- local.EmitStore(ResolveVariable(v));
- _locals.Add(v, local);
- }
- }
-
- private void EmitClosureToVariable(LambdaCompiler lc, HoistedLocals locals) {
- lc.EmitClosureArgument();
- lc.IL.Emit(OpCodes.Ldfld, typeof(Closure).GetField("Locals"));
- AddLocal(lc, locals.SelfVariable);
- EmitSet(locals.SelfVariable);
- }
-
- // Allocates slots for IL locals or IL arguments
- private void AllocateLocals(LambdaCompiler lc) {
- foreach (ParameterExpression v in GetVariables()) {
- if (Definitions[v] == VariableStorageKind.Local) {
- //
- // If v is in lc.Parameters, it is a parameter.
- // Otherwise, it is a local variable.
- //
- // Also, for inlined lambdas we'll create a local, which
- // is possibly a byref local if the parameter is byref.
- //
- Storage s;
- if (IsMethod && lc.Parameters.Contains(v)) {
- s = new ArgumentStorage(lc, v);
- } else {
- s = new LocalStorage(lc, v);
- }
- _locals.Add(v, s);
- }
- }
- }
-
- private IList<ParameterExpression> GetVariables() {
- var vars = GetVariables(Node);
- if (MergedScopes == null) {
- return vars;
- }
- var list = new List<ParameterExpression>(vars);
- foreach (var scope in MergedScopes) {
- list.AddRange(GetVariables(scope));
- }
- return list;
- }
-
- private static IList<ParameterExpression> GetVariables(object scope) {
- var lambda = scope as LambdaExpression;
- if (lambda != null) {
- return lambda.Parameters;
- }
- var block = scope as BlockExpression;
- if (block != null) {
- return block.Variables;
- }
- return new[] { ((CatchBlock)scope).Variable };
- }
-
- private string CurrentLambdaName {
- get {
- CompilerScope s = this;
- while (true) {
- var lambda = s.Node as LambdaExpression;
- if (lambda != null) {
- return lambda.Name;
- }
- }
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ConstantCheck.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ConstantCheck.cs
deleted file mode 100644
index 11470281c84..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ConstantCheck.cs
+++ /dev/null
@@ -1,106 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- internal enum AnalyzeTypeIsResult {
- KnownFalse,
- KnownTrue,
- KnownAssignable, // need null check only
- Unknown, // need full runtime check
- }
-
- internal static class ConstantCheck {
-
- internal static bool IsNull(Expression e) {
- if (e.NodeType == ExpressionType.Constant) {
- return ((ConstantExpression)e).Value == null;
- }
- return false;
- }
-
-
- /// <summary>
- /// If the result of a TypeBinaryExpression is known statically, this
- /// returns the result, otherwise it returns null, meaning we'll need
- /// to perform the IsInst instruction at runtime.
- ///
- /// The result of this function must be equivalent to IsInst, or
- /// null.
- /// </summary>
- internal static AnalyzeTypeIsResult AnalyzeTypeIs(TypeBinaryExpression typeIs) {
- return AnalyzeTypeIs(typeIs.Expression, typeIs.TypeOperand);
- }
-
- /// <summary>
- /// If the result of an isinst opcode is known statically, this
- /// returns the result, otherwise it returns null, meaning we'll need
- /// to perform the IsInst instruction at runtime.
- ///
- /// The result of this function must be equivalent to IsInst, or
- /// null.
- /// </summary>
- private static AnalyzeTypeIsResult AnalyzeTypeIs(Expression operand, Type testType) {
- Type operandType = operand.Type;
-
- // Oddly, we allow void operands
- // This is LinqV1 behavior of TypeIs
- if (operandType == typeof(void)) {
- return AnalyzeTypeIsResult.KnownFalse;
- }
-
- //
- // Type comparisons treat nullable types as if they were the
- // underlying type. The reason is when you box a nullable it
- // becomes a boxed value of the underlying type, or null.
- //
- Type nnOperandType = operandType.GetNonNullableType();
- Type nnTestType = testType.GetNonNullableType();
-
- //
- // See if we can determine the answer based on the static types
- //
- // Extensive testing showed that Type.IsAssignableFrom,
- // Type.IsInstanceOfType, and the isinst instruction were all
- // equivalent when used against a live object
- //
- if (nnTestType.IsAssignableFrom(nnOperandType)) {
- // If the operand is a value type (other than nullable), we
- // know the result is always true.
- if (operandType.IsValueType && !operandType.IsNullableType()) {
- return AnalyzeTypeIsResult.KnownTrue;
- }
-
- // For reference/nullable types, we need to compare to null at runtime
- return AnalyzeTypeIsResult.KnownAssignable;
- }
-
- // We used to have an if IsSealed, return KnownFalse check here.
- // but that doesn't handle generic types & co/contravariance correctly.
- // So just use IsInst, which we know always gives us the right answer.
-
- // Otherwise we need a full runtime check
- return AnalyzeTypeIsResult.Unknown;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DebugInfoGenerator.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DebugInfoGenerator.cs
deleted file mode 100644
index b87eecde4e0..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DebugInfoGenerator.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-using Microsoft.Scripting.Ast.Compiler;
-#else
-using System.Linq.Expressions;
-using System.Linq.Expressions.Compiler;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-#if FEATURE_REFEMIT
-using System.Reflection.Emit;
-#endif
-using System.Diagnostics;
-using System.Diagnostics.SymbolStore;
-using System.Reflection;
-
-namespace System.Runtime.CompilerServices {
-#if !FEATURE_CORE_DLR || SILVERLIGHT
- using ILGenerator = OffsetTrackingILGenerator;
-#endif
-
- /// <summary>
- /// Generates debug information for lambdas in an expression tree.
- /// </summary>
- public abstract class DebugInfoGenerator {
-#if FEATURE_PDBEMIT
- /// <summary>
- /// Creates PDB symbol generator.
- /// </summary>
- /// <returns>PDB symbol generator.</returns>
- public static DebugInfoGenerator CreatePdbGenerator() {
- return new SymbolDocumentGenerator();
- }
-#else
- public static DebugInfoGenerator CreatePdbGenerator() {
- throw new PlatformNotSupportedException();
- }
-#endif
- /// <summary>
- /// Marks a sequence point.
- /// </summary>
- /// <param name="method">The lambda being generated.</param>
- /// <param name="ilOffset">IL offset where to mark the sequence point.</param>
- /// <param name="sequencePoint">Debug informaton corresponding to the sequence point.</param>
- public abstract void MarkSequencePoint(LambdaExpression method, int ilOffset, DebugInfoExpression sequencePoint);
-
-#if FEATURE_REFEMIT
- internal virtual void MarkSequencePoint(LambdaExpression method, MethodBase methodBase, ILGenerator ilg, DebugInfoExpression sequencePoint) {
- MarkSequencePoint(method, ilg.ILOffset, sequencePoint);
- }
-
- internal virtual void SetLocalName(LocalBuilder localBuilder, string name) {
- // nop
- }
-#endif
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.Generated.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.Generated.cs
deleted file mode 100644
index b2e172ff8fb..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.Generated.cs
+++ /dev/null
@@ -1,293 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic;
-using System.Dynamic.Utils;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
- using Microsoft.Scripting.Utils;
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- internal static partial class DelegateHelpers {
- private static TypeInfo _DelegateCache = new TypeInfo();
-
- #region Generated Maximum Delegate Arity
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_max_delegate_arity from: generate_dynsites.py
-
- private const int MaximumArity = 17;
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- internal class TypeInfo {
- public Type DelegateType;
- public Dictionary<Type, TypeInfo> TypeChain;
-
- public Type MakeDelegateType(Type retType, params Expression[] args) {
- return MakeDelegateType(retType, (IList<Expression>)args);
- }
-
- public Type MakeDelegateType(Type retType, IList<Expression> args) {
- // nope, go ahead and create it and spend the
- // cost of creating the array.
- Type[] paramTypes = new Type[args.Count + 2];
- paramTypes[0] = typeof(CallSite);
- paramTypes[paramTypes.Length - 1] = retType;
- for (int i = 0; i < args.Count; i++) {
- paramTypes[i + 1] = args[i].Type;
- }
-
- return DelegateType = MakeNewDelegate(paramTypes);
- }
- }
-
-
- /// <summary>
- /// Finds a delegate type using the types in the array.
- /// We use the cache to avoid copying the array, and to cache the
- /// created delegate type
- /// </summary>
- internal static Type MakeDelegateType(Type[] types) {
- lock (_DelegateCache) {
- TypeInfo curTypeInfo = _DelegateCache;
-
- // arguments & return type
- for (int i = 0; i < types.Length; i++) {
- curTypeInfo = NextTypeInfo(types[i], curTypeInfo);
- }
-
- // see if we have the delegate already
- if (curTypeInfo.DelegateType == null) {
- // clone because MakeCustomDelegate can hold onto the array.
- curTypeInfo.DelegateType = MakeNewDelegate((Type[])types.Clone());
- }
-
- return curTypeInfo.DelegateType;
- }
- }
-
- /// <summary>
- /// Finds a delegate type for a CallSite using the types in the ReadOnlyCollection of Expression.
- ///
- /// We take the readonly collection of Expression explicitly to avoid allocating memory (an array
- /// of types) on lookup of delegate types.
- /// </summary>
- internal static Type MakeCallSiteDelegate(ReadOnlyCollection<Expression> types, Type returnType) {
- lock (_DelegateCache) {
- TypeInfo curTypeInfo = _DelegateCache;
-
- // CallSite
- curTypeInfo = NextTypeInfo(typeof(CallSite), curTypeInfo);
-
- // arguments
- for (int i = 0; i < types.Count; i++) {
- curTypeInfo = NextTypeInfo(types[i].Type, curTypeInfo);
- }
-
- // return type
- curTypeInfo = NextTypeInfo(returnType, curTypeInfo);
-
- // see if we have the delegate already
- if (curTypeInfo.DelegateType == null) {
- curTypeInfo.MakeDelegateType(returnType, types);
- }
-
- return curTypeInfo.DelegateType;
- }
- }
-
- /// <summary>
- /// Finds a delegate type for a CallSite using the MetaObject array.
- ///
- /// We take the array of MetaObject explicitly to avoid allocating memory (an array of types) on
- /// lookup of delegate types.
- /// </summary>
- internal static Type MakeDeferredSiteDelegate(DynamicMetaObject[] args, Type returnType) {
- lock (_DelegateCache) {
- TypeInfo curTypeInfo = _DelegateCache;
-
- // CallSite
- curTypeInfo = NextTypeInfo(typeof(CallSite), curTypeInfo);
-
- // arguments
- for (int i = 0; i < args.Length; i++) {
- DynamicMetaObject mo = args[i];
- Type paramType = mo.Expression.Type;
- if (IsByRef(mo)) {
- paramType = paramType.MakeByRefType();
- }
- curTypeInfo = NextTypeInfo(paramType, curTypeInfo);
- }
-
- // return type
- curTypeInfo = NextTypeInfo(returnType, curTypeInfo);
-
- // see if we have the delegate already
- if (curTypeInfo.DelegateType == null) {
- // nope, go ahead and create it and spend the
- // cost of creating the array.
- Type[] paramTypes = new Type[args.Length + 2];
- paramTypes[0] = typeof(CallSite);
- paramTypes[paramTypes.Length - 1] = returnType;
- for (int i = 0; i < args.Length; i++) {
- DynamicMetaObject mo = args[i];
- Type paramType = mo.Expression.Type;
- if (IsByRef(mo)) {
- paramType = paramType.MakeByRefType();
- }
- paramTypes[i + 1] = paramType;
- }
-
- curTypeInfo.DelegateType = MakeNewDelegate(paramTypes);
- }
-
- return curTypeInfo.DelegateType;
- }
- }
-
- private static bool IsByRef(DynamicMetaObject mo) {
- ParameterExpression pe = mo.Expression as ParameterExpression;
- return pe != null && pe.IsByRef;
- }
-
- internal static TypeInfo NextTypeInfo(Type initialArg) {
- lock (_DelegateCache) {
- return NextTypeInfo(initialArg, _DelegateCache);
- }
- }
-
- internal static TypeInfo GetNextTypeInfo(Type initialArg, TypeInfo curTypeInfo) {
- lock (_DelegateCache) {
- return NextTypeInfo(initialArg, curTypeInfo);
- }
- }
-
- private static TypeInfo NextTypeInfo(Type initialArg, TypeInfo curTypeInfo) {
- Type lookingUp = initialArg;
- TypeInfo nextTypeInfo;
- if (curTypeInfo.TypeChain == null) {
- curTypeInfo.TypeChain = new Dictionary<Type, TypeInfo>();
- }
-
- if (!curTypeInfo.TypeChain.TryGetValue(lookingUp, out nextTypeInfo)) {
- nextTypeInfo = new TypeInfo();
- if (TypeUtils.CanCache(lookingUp)) {
- curTypeInfo.TypeChain[lookingUp] = nextTypeInfo;
- }
- }
- return nextTypeInfo;
- }
-
- /// <summary>
- /// Creates a new delegate, or uses a func/action
- /// Note: this method does not cache
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- private static Type MakeNewDelegate(Type[] types) {
- Debug.Assert(types != null && types.Length > 0);
-
- // Can only used predefined delegates if we have no byref types and
- // the arity is small enough to fit in Func<...> or Action<...>
- if (types.Length > MaximumArity || types.Any(t => t.IsByRef)) {
- return MakeNewCustomDelegate(types);
- }
-
- Type result;
- if (types[types.Length - 1] == typeof(void)) {
- result = GetActionType(types.RemoveLast());
- } else {
- result = GetFuncType(types);
- }
- Debug.Assert(result != null);
- return result;
- }
-
- internal static Type GetFuncType(Type[] types) {
- switch (types.Length) {
- #region Generated Delegate Func Types
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_delegate_func from: generate_dynsites.py
-
- case 1: return typeof(Func<>).MakeGenericType(types);
- case 2: return typeof(Func<,>).MakeGenericType(types);
- case 3: return typeof(Func<,,>).MakeGenericType(types);
- case 4: return typeof(Func<,,,>).MakeGenericType(types);
- case 5: return typeof(Func<,,,,>).MakeGenericType(types);
- case 6: return typeof(Func<,,,,,>).MakeGenericType(types);
- case 7: return typeof(Func<,,,,,,>).MakeGenericType(types);
- case 8: return typeof(Func<,,,,,,,>).MakeGenericType(types);
- case 9: return typeof(Func<,,,,,,,,>).MakeGenericType(types);
- case 10: return typeof(Func<,,,,,,,,,>).MakeGenericType(types);
- case 11: return typeof(Func<,,,,,,,,,,>).MakeGenericType(types);
- case 12: return typeof(Func<,,,,,,,,,,,>).MakeGenericType(types);
- case 13: return typeof(Func<,,,,,,,,,,,,>).MakeGenericType(types);
- case 14: return typeof(Func<,,,,,,,,,,,,,>).MakeGenericType(types);
- case 15: return typeof(Func<,,,,,,,,,,,,,,>).MakeGenericType(types);
- case 16: return typeof(Func<,,,,,,,,,,,,,,,>).MakeGenericType(types);
- case 17: return typeof(Func<,,,,,,,,,,,,,,,,>).MakeGenericType(types);
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- default: return null;
- }
- }
-
- internal static Type GetActionType(Type[] types) {
- switch (types.Length) {
- case 0: return typeof(Action);
- #region Generated Delegate Action Types
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_delegate_action from: generate_dynsites.py
-
- case 1: return typeof(Action<>).MakeGenericType(types);
- case 2: return typeof(Action<,>).MakeGenericType(types);
- case 3: return typeof(Action<,,>).MakeGenericType(types);
- case 4: return typeof(Action<,,,>).MakeGenericType(types);
- case 5: return typeof(Action<,,,,>).MakeGenericType(types);
- case 6: return typeof(Action<,,,,,>).MakeGenericType(types);
- case 7: return typeof(Action<,,,,,,>).MakeGenericType(types);
- case 8: return typeof(Action<,,,,,,,>).MakeGenericType(types);
- case 9: return typeof(Action<,,,,,,,,>).MakeGenericType(types);
- case 10: return typeof(Action<,,,,,,,,,>).MakeGenericType(types);
- case 11: return typeof(Action<,,,,,,,,,,>).MakeGenericType(types);
- case 12: return typeof(Action<,,,,,,,,,,,>).MakeGenericType(types);
- case 13: return typeof(Action<,,,,,,,,,,,,>).MakeGenericType(types);
- case 14: return typeof(Action<,,,,,,,,,,,,,>).MakeGenericType(types);
- case 15: return typeof(Action<,,,,,,,,,,,,,,>).MakeGenericType(types);
- case 16: return typeof(Action<,,,,,,,,,,,,,,,>).MakeGenericType(types);
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- default: return null;
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.cs
deleted file mode 100644
index 3489ee15514..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Dynamic.Utils;
-using System.Reflection;
-#if FEATURE_REFEMIT
-using System.Reflection.Emit;
-#endif
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- internal static partial class DelegateHelpers {
- private const MethodAttributes CtorAttributes = MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public;
- private const MethodImplAttributes ImplAttributes = MethodImplAttributes.Runtime | MethodImplAttributes.Managed;
- private const MethodAttributes InvokeAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual;
-#if FEATURE_REFEMIT
- private static readonly Type[] _DelegateCtorSignature = new Type[] { typeof(object), typeof(IntPtr) };
-#endif
-
- private static Type MakeNewCustomDelegate(Type[] types) {
-#if FEATURE_REFEMIT
- Type returnType = types[types.Length - 1];
- Type[] parameters = types.RemoveLast();
-
- TypeBuilder builder = AssemblyGen.DefineDelegateType("Delegate" + types.Length);
- builder.DefineConstructor(CtorAttributes, CallingConventions.Standard, _DelegateCtorSignature).SetImplementationFlags(ImplAttributes);
- builder.DefineMethod("Invoke", InvokeAttributes, returnType, parameters).SetImplementationFlags(ImplAttributes);
- return builder.CreateType();
-#else
- throw new NotSupportedException("Method signature not supported on this platform");
-#endif
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ExpressionQuoter.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ExpressionQuoter.cs
deleted file mode 100644
index b26a8266d18..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ExpressionQuoter.cs
+++ /dev/null
@@ -1,247 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-using Microsoft.Scripting.Ast.Compiler;
-#else
-using System.Linq.Expressions;
-using System.Linq.Expressions.Compiler;
-#endif
-
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-namespace System.Runtime.CompilerServices {
- public partial class RuntimeOps {
- /// <summary>
- /// Quotes the provided expression tree.
- /// </summary>
- /// <param name="expression">The expression to quote.</param>
- /// <param name="hoistedLocals">The hoisted local state provided by the compiler.</param>
- /// <param name="locals">The actual hoisted local values.</param>
- /// <returns>The quoted expression.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static Expression Quote(Expression expression, object hoistedLocals, object[] locals) {
- Debug.Assert(hoistedLocals != null && locals != null);
- var quoter = new ExpressionQuoter((HoistedLocals)hoistedLocals, locals);
- return quoter.Visit(expression);
- }
-
- /// <summary>
- /// Combines two runtime variable lists and returns a new list.
- /// </summary>
- /// <param name="first">The first list.</param>
- /// <param name="second">The second list.</param>
- /// <param name="indexes">The index array indicating which list to get variables from.</param>
- /// <returns>The merged runtime variables.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static IRuntimeVariables MergeRuntimeVariables(IRuntimeVariables first, IRuntimeVariables second, int[] indexes) {
- return new MergedRuntimeVariables(first, second, indexes);
- }
-
- // Modifies a quoted Expression instance by changing hoisted variables and
- // parameters into hoisted local references. The variable's StrongBox is
- // burned as a constant, and all hoisted variables/parameters are rewritten
- // as indexing expressions.
- //
- // The behavior of Quote is indended to be like C# and VB expression quoting
- private sealed class ExpressionQuoter : ExpressionVisitor {
- private readonly HoistedLocals _scope;
- private readonly object[] _locals;
-
- // A stack of variables that are defined in nested scopes. We search
- // this first when resolving a variable in case a nested scope shadows
- // one of our variable instances.
- private readonly Stack<Set<ParameterExpression>> _shadowedVars = new Stack<Set<ParameterExpression>>();
-
- internal ExpressionQuoter(HoistedLocals scope, object[] locals) {
- _scope = scope;
- _locals = locals;
- }
-
- protected internal override Expression VisitLambda<T>(Expression<T> node) {
- _shadowedVars.Push(new Set<ParameterExpression>(node.Parameters));
- Expression b = Visit(node.Body);
- _shadowedVars.Pop();
- if (b == node.Body) {
- return node;
- }
- return Expression.Lambda<T>(b, node.Name, node.TailCall, node.Parameters);
- }
-
- protected internal override Expression VisitBlock(BlockExpression node) {
- if (node.Variables.Count > 0) {
- _shadowedVars.Push(new Set<ParameterExpression>(node.Variables));
- }
- var b = Visit(node.Expressions);
- if (node.Variables.Count > 0) {
- _shadowedVars.Pop();
- }
- if (b == node.Expressions) {
- return node;
- }
- return Expression.Block(node.Variables, b);
- }
-
- protected override CatchBlock VisitCatchBlock(CatchBlock node) {
- if (node.Variable != null) {
- _shadowedVars.Push(new Set<ParameterExpression>(new[] { node.Variable }));
- }
- Expression b = Visit(node.Body);
- Expression f = Visit(node.Filter);
- if (node.Variable != null) {
- _shadowedVars.Pop();
- }
- if (b == node.Body && f == node.Filter) {
- return node;
- }
- return Expression.MakeCatchBlock(node.Test, node.Variable, b, f);
- }
-
- protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) {
- int count = node.Variables.Count;
- var boxes = new List<IStrongBox>();
- var vars = new List<ParameterExpression>();
- var indexes = new int[count];
- for (int i = 0; i < count; i++) {
- IStrongBox box = GetBox(node.Variables[i]);
- if (box == null) {
- indexes[i] = vars.Count;
- vars.Add(node.Variables[i]);
- } else {
- indexes[i] = -1 - boxes.Count;
- boxes.Add(box);
- }
- }
-
- // No variables were rewritten. Just return the original node
- if (boxes.Count == 0) {
- return node;
- }
-
- var boxesConst = Expression.Constant(new RuntimeVariables(boxes.ToArray()), typeof(IRuntimeVariables));
- // All of them were rewritten. Just return the array as a constant
- if (vars.Count == 0) {
- return boxesConst;
- }
-
- // Otherwise, we need to return an object that merges them
- return Expression.Call(
- typeof(RuntimeOps).GetMethod("MergeRuntimeVariables"),
- Expression.RuntimeVariables(new TrueReadOnlyCollection<ParameterExpression>(vars.ToArray())),
- boxesConst,
- Expression.Constant(indexes)
- );
- }
-
- protected internal override Expression VisitParameter(ParameterExpression node) {
- IStrongBox box = GetBox(node);
- if (box == null) {
- return node;
- }
- return Expression.Field(Expression.Constant(box), "Value");
- }
-
- private IStrongBox GetBox(ParameterExpression variable) {
- // Skip variables that are shadowed by a nested scope/lambda
- foreach (Set<ParameterExpression> hidden in _shadowedVars) {
- if (hidden.Contains(variable)) {
- return null;
- }
- }
-
- HoistedLocals scope = _scope;
- object[] locals = _locals;
- while (true) {
- int hoistIndex;
- if (scope.Indexes.TryGetValue(variable, out hoistIndex)) {
- return (IStrongBox)locals[hoistIndex];
- }
- scope = scope.Parent;
- if (scope == null) {
- break;
- }
- locals = HoistedLocals.GetParent(locals);
- }
-
- // Unbound variable: an error should've been thrown already
- // from VariableBinder
- throw ContractUtils.Unreachable;
- }
- }
-
- private sealed class RuntimeVariables : IRuntimeVariables {
- private readonly IStrongBox[] _boxes;
-
- internal RuntimeVariables(IStrongBox[] boxes) {
- _boxes = boxes;
- }
-
- int IRuntimeVariables.Count {
- get { return _boxes.Length; }
- }
-
- object IRuntimeVariables.this[int index] {
- get {
- return _boxes[index].Value;
- }
- set {
- _boxes[index].Value = value;
- }
- }
- }
-
- /// <summary>
- /// Provides a list of variables, supporing read/write of the values
- /// Exposed via RuntimeVariablesExpression
- /// </summary>
- private sealed class MergedRuntimeVariables : IRuntimeVariables {
- private readonly IRuntimeVariables _first;
- private readonly IRuntimeVariables _second;
-
- // For reach item, the index into the first or second list
- // Positive values mean the first array, negative means the second
- private readonly int[] _indexes;
-
- internal MergedRuntimeVariables(IRuntimeVariables first, IRuntimeVariables second, int[] indexes) {
- _first = first;
- _second = second;
- _indexes = indexes;
- }
-
- public int Count {
- get { return _indexes.Length; }
- }
-
- public object this[int index] {
- get {
- index = _indexes[index];
- return (index >= 0) ? _first[index] : _second[-1 - index];
- }
- set {
- index = _indexes[index];
- if (index >= 0) {
- _first[index] = value;
- } else {
- _second[-1 - index] = value;
- }
- }
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/HoistedLocals.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/HoistedLocals.cs
deleted file mode 100644
index ddb304be986..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/HoistedLocals.cs
+++ /dev/null
@@ -1,101 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Runtime.CompilerServices;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
-
- // Suppose we have something like:
- //
- // (string s)=>()=>s.
- //
- // We wish to generate the outer as:
- //
- // Func<string> OuterMethod(Closure closure, string s)
- // {
- // object[] locals = new object[1];
- // locals[0] = new StrongBox<string>();
- // ((StrongBox<string>)locals[0]).Value = s;
- // return ((DynamicMethod)closure.Constants[0]).CreateDelegate(typeof(Func<string>), new Closure(null, locals));
- // }
- //
- // ... and the inner as:
- //
- // string InnerMethod(Closure closure)
- // {
- // object[] locals = closure.Locals;
- // return ((StrongBox<string>)locals[0]).Value;
- // }
- //
- // This class tracks that "s" was hoisted into a closure, as the 0th
- // element in the array
- //
- /// <summary>
- /// Stores information about locals and arguments that are hoisted into
- /// the closure array because they're referenced in an inner lambda.
- ///
- /// This class is sometimes emitted as a runtime constant for internal
- /// use to hoist variables/parameters in quoted expressions
- ///
- /// Invariant: this class stores no mutable state
- /// </summary>
- internal sealed class HoistedLocals {
-
- // The parent locals, if any
- internal readonly HoistedLocals Parent;
-
- // A mapping of hoisted variables to their indexes in the array
- internal readonly System.Dynamic.Utils.ReadOnlyDictionary<Expression, int> Indexes;
-
- // The variables, in the order they appear in the array
- internal readonly ReadOnlyCollection<ParameterExpression> Variables;
-
- // A virtual variable for accessing this locals array
- internal readonly ParameterExpression SelfVariable;
-
- internal HoistedLocals(HoistedLocals parent, ReadOnlyCollection<ParameterExpression> vars) {
-
- if (parent != null) {
- // Add the parent locals array as the 0th element in the array
- vars = new TrueReadOnlyCollection<ParameterExpression>(vars.AddFirst(parent.SelfVariable));
- }
-
- Dictionary<Expression, int> indexes = new Dictionary<Expression, int>(vars.Count);
- for (int i = 0; i < vars.Count; i++) {
- indexes.Add(vars[i], i);
- }
-
- SelfVariable = Expression.Variable(typeof(object[]), null);
- Parent = parent;
- Variables = vars;
- Indexes = new System.Dynamic.Utils.ReadOnlyDictionary<Expression, int>(indexes);
- }
-
- internal ParameterExpression ParentVariable {
- get { return Parent != null ? Parent.SelfVariable : null; }
- }
-
- internal static object[] GetParent(object[] locals) {
- return ((StrongBox<object[]>)locals[0]).Value;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ILGen.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ILGen.cs
deleted file mode 100644
index 5577d656495..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ILGen.cs
+++ /dev/null
@@ -1,1051 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Reflection.Emit;
-using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
-#if !FEATURE_CORE_DLR || SILVERLIGHT
- using ILGenerator = OffsetTrackingILGenerator;
-#endif
-
- internal static class ILGen {
-
- internal static void Emit(this ILGenerator il, OpCode opcode, MethodBase methodBase) {
- Debug.Assert(methodBase is MethodInfo || methodBase is ConstructorInfo);
-
- if (methodBase.MemberType == MemberTypes.Constructor) {
- il.Emit(opcode, (ConstructorInfo)methodBase);
- } else {
- il.Emit(opcode, (MethodInfo)methodBase);
- }
- }
-
- #region Instruction helpers
-
- internal static void EmitLoadArg(this ILGenerator il, int index) {
- Debug.Assert(index >= 0);
-
- switch (index) {
- case 0:
- il.Emit(OpCodes.Ldarg_0);
- break;
- case 1:
- il.Emit(OpCodes.Ldarg_1);
- break;
- case 2:
- il.Emit(OpCodes.Ldarg_2);
- break;
- case 3:
- il.Emit(OpCodes.Ldarg_3);
- break;
- default:
- if (index <= Byte.MaxValue) {
- il.Emit(OpCodes.Ldarg_S, (byte)index);
- } else {
- il.Emit(OpCodes.Ldarg, index);
- }
- break;
- }
- }
-
- internal static void EmitLoadArgAddress(this ILGenerator il, int index) {
- Debug.Assert(index >= 0);
-
- if (index <= Byte.MaxValue) {
- il.Emit(OpCodes.Ldarga_S, (byte)index);
- } else {
- il.Emit(OpCodes.Ldarga, index);
- }
- }
-
- internal static void EmitStoreArg(this ILGenerator il, int index) {
- Debug.Assert(index >= 0);
-
- if (index <= Byte.MaxValue) {
- il.Emit(OpCodes.Starg_S, (byte)index);
- } else {
- il.Emit(OpCodes.Starg, index);
- }
- }
-
- /// <summary>
- /// Emits a Ldind* instruction for the appropriate type
- /// </summary>
- internal static void EmitLoadValueIndirect(this ILGenerator il, Type type) {
- ContractUtils.RequiresNotNull(type, "type");
-
- if (type.IsValueType) {
- if (type == typeof(int)) {
- il.Emit(OpCodes.Ldind_I4);
- } else if (type == typeof(uint)) {
- il.Emit(OpCodes.Ldind_U4);
- } else if (type == typeof(short)) {
- il.Emit(OpCodes.Ldind_I2);
- } else if (type == typeof(ushort)) {
- il.Emit(OpCodes.Ldind_U2);
- } else if (type == typeof(long) || type == typeof(ulong)) {
- il.Emit(OpCodes.Ldind_I8);
- } else if (type == typeof(char)) {
- il.Emit(OpCodes.Ldind_I2);
- } else if (type == typeof(bool)) {
- il.Emit(OpCodes.Ldind_I1);
- } else if (type == typeof(float)) {
- il.Emit(OpCodes.Ldind_R4);
- } else if (type == typeof(double)) {
- il.Emit(OpCodes.Ldind_R8);
- } else {
- il.Emit(OpCodes.Ldobj, type);
- }
- } else {
- il.Emit(OpCodes.Ldind_Ref);
- }
- }
-
-
- /// <summary>
- /// Emits a Stind* instruction for the appropriate type.
- /// </summary>
- internal static void EmitStoreValueIndirect(this ILGenerator il, Type type) {
- ContractUtils.RequiresNotNull(type, "type");
-
- if (type.IsValueType) {
- if (type == typeof(int)) {
- il.Emit(OpCodes.Stind_I4);
- } else if (type == typeof(short)) {
- il.Emit(OpCodes.Stind_I2);
- } else if (type == typeof(long) || type == typeof(ulong)) {
- il.Emit(OpCodes.Stind_I8);
- } else if (type == typeof(char)) {
- il.Emit(OpCodes.Stind_I2);
- } else if (type == typeof(bool)) {
- il.Emit(OpCodes.Stind_I1);
- } else if (type == typeof(float)) {
- il.Emit(OpCodes.Stind_R4);
- } else if (type == typeof(double)) {
- il.Emit(OpCodes.Stind_R8);
- } else {
- il.Emit(OpCodes.Stobj, type);
- }
- } else {
- il.Emit(OpCodes.Stind_Ref);
- }
- }
-
- // Emits the Ldelem* instruction for the appropriate type
-
- internal static void EmitLoadElement(this ILGenerator il, Type type) {
- ContractUtils.RequiresNotNull(type, "type");
-
- if (!type.IsValueType) {
- il.Emit(OpCodes.Ldelem_Ref);
- } else if (type.IsEnum) {
- il.Emit(OpCodes.Ldelem, type);
- } else {
- switch (Type.GetTypeCode(type)) {
- case TypeCode.Boolean:
- case TypeCode.SByte:
- il.Emit(OpCodes.Ldelem_I1);
- break;
- case TypeCode.Byte:
- il.Emit(OpCodes.Ldelem_U1);
- break;
- case TypeCode.Int16:
- il.Emit(OpCodes.Ldelem_I2);
- break;
- case TypeCode.Char:
- case TypeCode.UInt16:
- il.Emit(OpCodes.Ldelem_U2);
- break;
- case TypeCode.Int32:
- il.Emit(OpCodes.Ldelem_I4);
- break;
- case TypeCode.UInt32:
- il.Emit(OpCodes.Ldelem_U4);
- break;
- case TypeCode.Int64:
- case TypeCode.UInt64:
- il.Emit(OpCodes.Ldelem_I8);
- break;
- case TypeCode.Single:
- il.Emit(OpCodes.Ldelem_R4);
- break;
- case TypeCode.Double:
- il.Emit(OpCodes.Ldelem_R8);
- break;
- default:
- il.Emit(OpCodes.Ldelem, type);
- break;
- }
- }
- }
-
- /// <summary>
- /// Emits a Stelem* instruction for the appropriate type.
- /// </summary>
- internal static void EmitStoreElement(this ILGenerator il, Type type) {
- ContractUtils.RequiresNotNull(type, "type");
-
- if (type.IsEnum) {
- il.Emit(OpCodes.Stelem, type);
- return;
- }
- switch (Type.GetTypeCode(type)) {
- case TypeCode.Boolean:
- case TypeCode.SByte:
- case TypeCode.Byte:
- il.Emit(OpCodes.Stelem_I1);
- break;
- case TypeCode.Char:
- case TypeCode.Int16:
- case TypeCode.UInt16:
- il.Emit(OpCodes.Stelem_I2);
- break;
- case TypeCode.Int32:
- case TypeCode.UInt32:
- il.Emit(OpCodes.Stelem_I4);
- break;
- case TypeCode.Int64:
- case TypeCode.UInt64:
- il.Emit(OpCodes.Stelem_I8);
- break;
- case TypeCode.Single:
- il.Emit(OpCodes.Stelem_R4);
- break;
- case TypeCode.Double:
- il.Emit(OpCodes.Stelem_R8);
- break;
- default:
- if (type.IsValueType) {
- il.Emit(OpCodes.Stelem, type);
- } else {
- il.Emit(OpCodes.Stelem_Ref);
- }
- break;
- }
- }
-
- internal static void EmitType(this ILGenerator il, Type type) {
- ContractUtils.RequiresNotNull(type, "type");
-
- il.Emit(OpCodes.Ldtoken, type);
- il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"));
- }
-
- #endregion
-
- #region Fields, properties and methods
-
- internal static void EmitFieldAddress(this ILGenerator il, FieldInfo fi) {
- ContractUtils.RequiresNotNull(fi, "fi");
-
- if (fi.IsStatic) {
- il.Emit(OpCodes.Ldsflda, fi);
- } else {
- il.Emit(OpCodes.Ldflda, fi);
- }
- }
-
- internal static void EmitFieldGet(this ILGenerator il, FieldInfo fi) {
- ContractUtils.RequiresNotNull(fi, "fi");
-
- if (fi.IsStatic) {
- il.Emit(OpCodes.Ldsfld, fi);
- } else {
- il.Emit(OpCodes.Ldfld, fi);
- }
- }
-
- internal static void EmitFieldSet(this ILGenerator il, FieldInfo fi) {
- ContractUtils.RequiresNotNull(fi, "fi");
-
- if (fi.IsStatic) {
- il.Emit(OpCodes.Stsfld, fi);
- } else {
- il.Emit(OpCodes.Stfld, fi);
- }
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
- internal static void EmitNew(this ILGenerator il, ConstructorInfo ci) {
- ContractUtils.RequiresNotNull(ci, "ci");
-
- if (ci.DeclaringType.ContainsGenericParameters) {
- throw Error.IllegalNewGenericParams(ci.DeclaringType);
- }
-
- il.Emit(OpCodes.Newobj, ci);
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
- internal static void EmitNew(this ILGenerator il, Type type, Type[] paramTypes) {
- ContractUtils.RequiresNotNull(type, "type");
- ContractUtils.RequiresNotNull(paramTypes, "paramTypes");
-
- ConstructorInfo ci = type.GetConstructor(paramTypes);
- if (ci == null) throw Error.TypeDoesNotHaveConstructorForTheSignature();
- il.EmitNew(ci);
- }
-
- #endregion
-
- #region Constants
-
- internal static void EmitNull(this ILGenerator il) {
- il.Emit(OpCodes.Ldnull);
- }
-
- internal static void EmitString(this ILGenerator il, string value) {
- ContractUtils.RequiresNotNull(value, "value");
- il.Emit(OpCodes.Ldstr, value);
- }
-
- internal static void EmitBoolean(this ILGenerator il, bool value) {
- if (value) {
- il.Emit(OpCodes.Ldc_I4_1);
- } else {
- il.Emit(OpCodes.Ldc_I4_0);
- }
- }
-
- internal static void EmitChar(this ILGenerator il, char value) {
- il.EmitInt(value);
- il.Emit(OpCodes.Conv_U2);
- }
-
- internal static void EmitByte(this ILGenerator il, byte value) {
- il.EmitInt(value);
- il.Emit(OpCodes.Conv_U1);
- }
-
- internal static void EmitSByte(this ILGenerator il, sbyte value) {
- il.EmitInt(value);
- il.Emit(OpCodes.Conv_I1);
- }
-
- internal static void EmitShort(this ILGenerator il, short value) {
- il.EmitInt(value);
- il.Emit(OpCodes.Conv_I2);
- }
-
- internal static void EmitUShort(this ILGenerator il, ushort value) {
- il.EmitInt(value);
- il.Emit(OpCodes.Conv_U2);
- }
-
- internal static void EmitInt(this ILGenerator il, int value) {
- OpCode c;
- switch (value) {
- case -1:
- c = OpCodes.Ldc_I4_M1;
- break;
- case 0:
- c = OpCodes.Ldc_I4_0;
- break;
- case 1:
- c = OpCodes.Ldc_I4_1;
- break;
- case 2:
- c = OpCodes.Ldc_I4_2;
- break;
- case 3:
- c = OpCodes.Ldc_I4_3;
- break;
- case 4:
- c = OpCodes.Ldc_I4_4;
- break;
- case 5:
- c = OpCodes.Ldc_I4_5;
- break;
- case 6:
- c = OpCodes.Ldc_I4_6;
- break;
- case 7:
- c = OpCodes.Ldc_I4_7;
- break;
- case 8:
- c = OpCodes.Ldc_I4_8;
- break;
- default:
- if (value >= -128 && value <= 127) {
- il.Emit(OpCodes.Ldc_I4_S, (sbyte)value);
- } else {
- il.Emit(OpCodes.Ldc_I4, value);
- }
- return;
- }
- il.Emit(c);
- }
-
- internal static void EmitUInt(this ILGenerator il, uint value) {
- il.EmitInt((int)value);
- il.Emit(OpCodes.Conv_U4);
- }
-
- internal static void EmitLong(this ILGenerator il, long value) {
- il.Emit(OpCodes.Ldc_I8, value);
-
- //
- // Now, emit convert to give the constant type information.
- //
- // Otherwise, it is treated as unsigned and overflow is not
- // detected if it's used in checked ops.
- //
- il.Emit(OpCodes.Conv_I8);
- }
-
- internal static void EmitULong(this ILGenerator il, ulong value) {
- il.Emit(OpCodes.Ldc_I8, (long)value);
- il.Emit(OpCodes.Conv_U8);
- }
-
- internal static void EmitDouble(this ILGenerator il, double value) {
- il.Emit(OpCodes.Ldc_R8, value);
- }
-
- internal static void EmitSingle(this ILGenerator il, float value) {
- il.Emit(OpCodes.Ldc_R4, value);
- }
-
- // matches TryEmitConstant
- internal static bool CanEmitConstant(object value, Type type) {
- if (value == null || CanEmitILConstant(type)) {
- return true;
- }
-
- Type t = value as Type;
- if (t != null && ShouldLdtoken(t)) {
- return true;
- }
-
- MethodBase mb = value as MethodBase;
- if (mb != null && ShouldLdtoken(mb)) {
- return true;
- }
-
- return false;
- }
-
- // matches TryEmitILConstant
- private static bool CanEmitILConstant(Type type) {
- switch (Type.GetTypeCode(type)) {
- case TypeCode.Boolean:
- case TypeCode.SByte:
- case TypeCode.Int16:
- case TypeCode.Int32:
- case TypeCode.Int64:
- case TypeCode.Single:
- case TypeCode.Double:
- case TypeCode.Char:
- case TypeCode.Byte:
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.UInt64:
- case TypeCode.Decimal:
- case TypeCode.String:
- return true;
- }
- return false;
- }
-
- internal static void EmitConstant(this ILGenerator il, object value) {
- Debug.Assert(value != null);
- EmitConstant(il, value, value.GetType());
- }
-
-
- //
- // Note: we support emitting more things as IL constants than
- // Linq does
- internal static void EmitConstant(this ILGenerator il, object value, Type type) {
- if (value == null) {
- // Smarter than the Linq implementation which uses the initobj
- // pattern for all value types (works, but requires a local and
- // more IL)
- il.EmitDefault(type);
- return;
- }
-
- // Handle the easy cases
- if (il.TryEmitILConstant(value, type)) {
- return;
- }
-
- // Check for a few more types that we support emitting as constants
- Type t = value as Type;
- if (t != null && ShouldLdtoken(t)) {
- il.EmitType(t);
- if (type != typeof(Type)) {
- il.Emit(OpCodes.Castclass, type);
- }
- return;
- }
-
- MethodBase mb = value as MethodBase;
- if (mb != null && ShouldLdtoken(mb)) {
- il.Emit(OpCodes.Ldtoken, mb);
- Type dt = mb.DeclaringType;
- if (dt != null && dt.IsGenericType) {
- il.Emit(OpCodes.Ldtoken, dt);
- il.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", new Type[] { typeof(RuntimeMethodHandle), typeof(RuntimeTypeHandle) }));
- } else {
- il.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", new Type[] { typeof(RuntimeMethodHandle) }));
- }
- if (type != typeof(MethodBase)) {
- il.Emit(OpCodes.Castclass, type);
- }
- return;
- }
-
- throw ContractUtils.Unreachable;
- }
-
- internal static bool ShouldLdtoken(Type t) {
-#if FEATURE_REFEMIT
- if (t is TypeBuilder) {
- return true;
- }
-#endif
- return t.IsGenericParameter || t.IsVisible;
- }
-
- internal static bool ShouldLdtoken(MethodBase mb) {
- // Can't ldtoken on a DynamicMethod
- if (mb is DynamicMethod) {
- return false;
- }
-
- Type dt = mb.DeclaringType;
- return dt == null || ShouldLdtoken(dt);
- }
-
-
- private static bool TryEmitILConstant(this ILGenerator il, object value, Type type) {
- switch (Type.GetTypeCode(type)) {
- case TypeCode.Boolean:
- il.EmitBoolean((bool)value);
- return true;
- case TypeCode.SByte:
- il.EmitSByte((sbyte)value);
- return true;
- case TypeCode.Int16:
- il.EmitShort((short)value);
- return true;
- case TypeCode.Int32:
- il.EmitInt((int)value);
- return true;
- case TypeCode.Int64:
- il.EmitLong((long)value);
- return true;
- case TypeCode.Single:
- il.EmitSingle((float)value);
- return true;
- case TypeCode.Double:
- il.EmitDouble((double)value);
- return true;
- case TypeCode.Char:
- il.EmitChar((char)value);
- return true;
- case TypeCode.Byte:
- il.EmitByte((byte)value);
- return true;
- case TypeCode.UInt16:
- il.EmitUShort((ushort)value);
- return true;
- case TypeCode.UInt32:
- il.EmitUInt((uint)value);
- return true;
- case TypeCode.UInt64:
- il.EmitULong((ulong)value);
- return true;
- case TypeCode.Decimal:
- il.EmitDecimal((decimal)value);
- return true;
- case TypeCode.String:
- il.EmitString((string)value);
- return true;
- default:
- return false;
- }
- }
-
- #endregion
-
- #region Linq Conversions
-
- internal static void EmitConvertToType(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) {
- if (TypeUtils.AreEquivalent(typeFrom, typeTo)) {
- return;
- }
-
- if (typeFrom == typeof(void) || typeTo == typeof(void)) {
- throw ContractUtils.Unreachable;
- }
-
- bool isTypeFromNullable = TypeUtils.IsNullableType(typeFrom);
- bool isTypeToNullable = TypeUtils.IsNullableType(typeTo);
-
- Type nnExprType = TypeUtils.GetNonNullableType(typeFrom);
- Type nnType = TypeUtils.GetNonNullableType(typeTo);
-
- if (typeFrom.IsInterface || // interface cast
- typeTo.IsInterface ||
- typeFrom == typeof(object) || // boxing cast
- typeTo == typeof(object) ||
- typeFrom == typeof(System.Enum) ||
- typeFrom == typeof(System.ValueType) ||
- TypeUtils.IsLegalExplicitVariantDelegateConversion(typeFrom, typeTo))
- {
- il.EmitCastToType(typeFrom, typeTo);
- } else if (isTypeFromNullable || isTypeToNullable) {
- il.EmitNullableConversion(typeFrom, typeTo, isChecked);
- } else if (!(TypeUtils.IsConvertible(typeFrom) && TypeUtils.IsConvertible(typeTo)) // primitive runtime conversion
- &&
- (nnExprType.IsAssignableFrom(nnType) || // down cast
- nnType.IsAssignableFrom(nnExprType))) // up cast
- {
- il.EmitCastToType(typeFrom, typeTo);
- } else if (typeFrom.IsArray && typeTo.IsArray) {
- // See DevDiv Bugs #94657.
- il.EmitCastToType(typeFrom, typeTo);
- } else {
- il.EmitNumericConversion(typeFrom, typeTo, isChecked);
- }
- }
-
-
- private static void EmitCastToType(this ILGenerator il, Type typeFrom, Type typeTo) {
- if (!typeFrom.IsValueType && typeTo.IsValueType) {
- il.Emit(OpCodes.Unbox_Any, typeTo);
- } else if (typeFrom.IsValueType && !typeTo.IsValueType) {
- il.Emit(OpCodes.Box, typeFrom);
- if (typeTo != typeof(object)) {
- il.Emit(OpCodes.Castclass, typeTo);
- }
- } else if (!typeFrom.IsValueType && !typeTo.IsValueType) {
- il.Emit(OpCodes.Castclass, typeTo);
- } else {
- throw Error.InvalidCast(typeFrom, typeTo);
- }
- }
-
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- private static void EmitNumericConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) {
- bool isFromUnsigned = TypeUtils.IsUnsigned(typeFrom);
- bool isFromFloatingPoint = TypeUtils.IsFloatingPoint(typeFrom);
- if (typeTo == typeof(Single)) {
- if (isFromUnsigned)
- il.Emit(OpCodes.Conv_R_Un);
- il.Emit(OpCodes.Conv_R4);
- } else if (typeTo == typeof(Double)) {
- if (isFromUnsigned)
- il.Emit(OpCodes.Conv_R_Un);
- il.Emit(OpCodes.Conv_R8);
- } else {
- TypeCode tc = Type.GetTypeCode(typeTo);
- if (isChecked) {
- // Overflow checking needs to know if the source value on the IL stack is unsigned or not.
- if (isFromUnsigned) {
- switch (tc) {
- case TypeCode.SByte:
- il.Emit(OpCodes.Conv_Ovf_I1_Un);
- break;
- case TypeCode.Int16:
- il.Emit(OpCodes.Conv_Ovf_I2_Un);
- break;
- case TypeCode.Int32:
- il.Emit(OpCodes.Conv_Ovf_I4_Un);
- break;
- case TypeCode.Int64:
- il.Emit(OpCodes.Conv_Ovf_I8_Un);
- break;
- case TypeCode.Byte:
- il.Emit(OpCodes.Conv_Ovf_U1_Un);
- break;
- case TypeCode.UInt16:
- case TypeCode.Char:
- il.Emit(OpCodes.Conv_Ovf_U2_Un);
- break;
- case TypeCode.UInt32:
- il.Emit(OpCodes.Conv_Ovf_U4_Un);
- break;
- case TypeCode.UInt64:
- il.Emit(OpCodes.Conv_Ovf_U8_Un);
- break;
- default:
- throw Error.UnhandledConvert(typeTo);
- }
- } else {
- switch (tc) {
- case TypeCode.SByte:
- il.Emit(OpCodes.Conv_Ovf_I1);
- break;
- case TypeCode.Int16:
- il.Emit(OpCodes.Conv_Ovf_I2);
- break;
- case TypeCode.Int32:
- il.Emit(OpCodes.Conv_Ovf_I4);
- break;
- case TypeCode.Int64:
- il.Emit(OpCodes.Conv_Ovf_I8);
- break;
- case TypeCode.Byte:
- il.Emit(OpCodes.Conv_Ovf_U1);
- break;
- case TypeCode.UInt16:
- case TypeCode.Char:
- il.Emit(OpCodes.Conv_Ovf_U2);
- break;
- case TypeCode.UInt32:
- il.Emit(OpCodes.Conv_Ovf_U4);
- break;
- case TypeCode.UInt64:
- il.Emit(OpCodes.Conv_Ovf_U8);
- break;
- default:
- throw Error.UnhandledConvert(typeTo);
- }
- }
- } else {
- switch (tc) {
- case TypeCode.SByte:
- il.Emit(OpCodes.Conv_I1);
- break;
- case TypeCode.Byte:
- il.Emit(OpCodes.Conv_U1);
- break;
- case TypeCode.Int16:
- il.Emit(OpCodes.Conv_I2);
- break;
- case TypeCode.UInt16:
- case TypeCode.Char:
- il.Emit(OpCodes.Conv_U2);
- break;
- case TypeCode.Int32:
- il.Emit(OpCodes.Conv_I4);
- break;
- case TypeCode.UInt32:
- il.Emit(OpCodes.Conv_U4);
- break;
- case TypeCode.Int64:
- if (isFromUnsigned) {
- il.Emit(OpCodes.Conv_U8);
- } else {
- il.Emit(OpCodes.Conv_I8);
- }
- break;
- case TypeCode.UInt64:
- if (isFromUnsigned || isFromFloatingPoint) {
- il.Emit(OpCodes.Conv_U8);
- } else {
- il.Emit(OpCodes.Conv_I8);
- }
- break;
- default:
- throw Error.UnhandledConvert(typeTo);
- }
- }
- }
- }
-
- private static void EmitNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) {
- Debug.Assert(TypeUtils.IsNullableType(typeFrom));
- Debug.Assert(TypeUtils.IsNullableType(typeTo));
- Label labIfNull = default(Label);
- Label labEnd = default(Label);
- LocalBuilder locFrom = null;
- LocalBuilder locTo = null;
- locFrom = il.DeclareLocal(typeFrom);
- il.Emit(OpCodes.Stloc, locFrom);
- locTo = il.DeclareLocal(typeTo);
- // test for null
- il.Emit(OpCodes.Ldloca, locFrom);
- il.EmitHasValue(typeFrom);
- labIfNull = il.DefineLabel();
- il.Emit(OpCodes.Brfalse_S, labIfNull);
- il.Emit(OpCodes.Ldloca, locFrom);
- il.EmitGetValueOrDefault(typeFrom);
- Type nnTypeFrom = TypeUtils.GetNonNullableType(typeFrom);
- Type nnTypeTo = TypeUtils.GetNonNullableType(typeTo);
- il.EmitConvertToType(nnTypeFrom, nnTypeTo, isChecked);
- // construct result type
- ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo });
- il.Emit(OpCodes.Newobj, ci);
- il.Emit(OpCodes.Stloc, locTo);
- labEnd = il.DefineLabel();
- il.Emit(OpCodes.Br_S, labEnd);
- // if null then create a default one
- il.MarkLabel(labIfNull);
- il.Emit(OpCodes.Ldloca, locTo);
- il.Emit(OpCodes.Initobj, typeTo);
- il.MarkLabel(labEnd);
- il.Emit(OpCodes.Ldloc, locTo);
- }
-
-
- private static void EmitNonNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) {
- Debug.Assert(!TypeUtils.IsNullableType(typeFrom));
- Debug.Assert(TypeUtils.IsNullableType(typeTo));
- LocalBuilder locTo = null;
- locTo = il.DeclareLocal(typeTo);
- Type nnTypeTo = TypeUtils.GetNonNullableType(typeTo);
- il.EmitConvertToType(typeFrom, nnTypeTo, isChecked);
- ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo });
- il.Emit(OpCodes.Newobj, ci);
- il.Emit(OpCodes.Stloc, locTo);
- il.Emit(OpCodes.Ldloc, locTo);
- }
-
-
- private static void EmitNullableToNonNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) {
- Debug.Assert(TypeUtils.IsNullableType(typeFrom));
- Debug.Assert(!TypeUtils.IsNullableType(typeTo));
- if (typeTo.IsValueType)
- il.EmitNullableToNonNullableStructConversion(typeFrom, typeTo, isChecked);
- else
- il.EmitNullableToReferenceConversion(typeFrom);
- }
-
-
- private static void EmitNullableToNonNullableStructConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) {
- Debug.Assert(TypeUtils.IsNullableType(typeFrom));
- Debug.Assert(!TypeUtils.IsNullableType(typeTo));
- Debug.Assert(typeTo.IsValueType);
- LocalBuilder locFrom = null;
- locFrom = il.DeclareLocal(typeFrom);
- il.Emit(OpCodes.Stloc, locFrom);
- il.Emit(OpCodes.Ldloca, locFrom);
- il.EmitGetValue(typeFrom);
- Type nnTypeFrom = TypeUtils.GetNonNullableType(typeFrom);
- il.EmitConvertToType(nnTypeFrom, typeTo, isChecked);
- }
-
-
- private static void EmitNullableToReferenceConversion(this ILGenerator il, Type typeFrom) {
- Debug.Assert(TypeUtils.IsNullableType(typeFrom));
- // We've got a conversion from nullable to Object, ValueType, Enum, etc. Just box it so that
- // we get the nullable semantics.
- il.Emit(OpCodes.Box, typeFrom);
- }
-
-
- private static void EmitNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) {
- bool isTypeFromNullable = TypeUtils.IsNullableType(typeFrom);
- bool isTypeToNullable = TypeUtils.IsNullableType(typeTo);
- Debug.Assert(isTypeFromNullable || isTypeToNullable);
- if (isTypeFromNullable && isTypeToNullable)
- il.EmitNullableToNullableConversion(typeFrom, typeTo, isChecked);
- else if (isTypeFromNullable)
- il.EmitNullableToNonNullableConversion(typeFrom, typeTo, isChecked);
- else
- il.EmitNonNullableToNullableConversion(typeFrom, typeTo, isChecked);
- }
-
-
- internal static void EmitHasValue(this ILGenerator il, Type nullableType) {
- MethodInfo mi = nullableType.GetMethod("get_HasValue", BindingFlags.Instance | BindingFlags.Public);
- Debug.Assert(nullableType.IsValueType);
- il.Emit(OpCodes.Call, mi);
- }
-
-
- internal static void EmitGetValue(this ILGenerator il, Type nullableType) {
- MethodInfo mi = nullableType.GetMethod("get_Value", BindingFlags.Instance | BindingFlags.Public);
- Debug.Assert(nullableType.IsValueType);
- il.Emit(OpCodes.Call, mi);
- }
-
-
- internal static void EmitGetValueOrDefault(this ILGenerator il, Type nullableType) {
- MethodInfo mi = nullableType.GetMethod("GetValueOrDefault", ReflectionUtils.EmptyTypes);
- Debug.Assert(nullableType.IsValueType);
- il.Emit(OpCodes.Call, mi);
- }
-
- #endregion
-
- #region Arrays
-
- /// <summary>
- /// Emits an array of constant values provided in the given list.
- /// The array is strongly typed.
- /// </summary>
- internal static void EmitArray<T>(this ILGenerator il, IList<T> items) {
- ContractUtils.RequiresNotNull(items, "items");
-
- il.EmitInt(items.Count);
- il.Emit(OpCodes.Newarr, typeof(T));
- for (int i = 0; i < items.Count; i++) {
- il.Emit(OpCodes.Dup);
- il.EmitInt(i);
- il.EmitConstant(items[i], typeof(T));
- il.EmitStoreElement(typeof(T));
- }
- }
-
- /// <summary>
- /// Emits an array of values of count size. The items are emitted via the callback
- /// which is provided with the current item index to emit.
- /// </summary>
- internal static void EmitArray(this ILGenerator il, Type elementType, int count, Action<int> emit) {
- ContractUtils.RequiresNotNull(elementType, "elementType");
- ContractUtils.RequiresNotNull(emit, "emit");
- if (count < 0) throw Error.CountCannotBeNegative();
-
- il.EmitInt(count);
- il.Emit(OpCodes.Newarr, elementType);
- for (int i = 0; i < count; i++) {
- il.Emit(OpCodes.Dup);
- il.EmitInt(i);
-
- emit(i);
-
- il.EmitStoreElement(elementType);
- }
- }
-
- /// <summary>
- /// Emits an array construction code.
- /// The code assumes that bounds for all dimensions
- /// are already emitted.
- /// </summary>
- internal static void EmitArray(this ILGenerator il, Type arrayType) {
- ContractUtils.RequiresNotNull(arrayType, "arrayType");
- if (!arrayType.IsArray) throw Error.ArrayTypeMustBeArray();
-
- int rank = arrayType.GetArrayRank();
- if (rank == 1) {
- il.Emit(OpCodes.Newarr, arrayType.GetElementType());
- } else {
- Type[] types = new Type[rank];
- for (int i = 0; i < rank; i++) {
- types[i] = typeof(int);
- }
- il.EmitNew(arrayType, types);
- }
- }
-
- #endregion
-
- #region Support for emitting constants
-
- internal static void EmitDecimal(this ILGenerator il, decimal value) {
- if (Decimal.Truncate(value) == value) {
- if (Int32.MinValue <= value && value <= Int32.MaxValue) {
- int intValue = Decimal.ToInt32(value);
- il.EmitInt(intValue);
- il.EmitNew(typeof(Decimal).GetConstructor(new Type[] { typeof(int) }));
- } else if (Int64.MinValue <= value && value <= Int64.MaxValue) {
- long longValue = Decimal.ToInt64(value);
- il.EmitLong(longValue);
- il.EmitNew(typeof(Decimal).GetConstructor(new Type[] { typeof(long) }));
- } else {
- il.EmitDecimalBits(value);
- }
- } else {
- il.EmitDecimalBits(value);
- }
- }
-
- private static void EmitDecimalBits(this ILGenerator il, decimal value) {
- int[] bits = Decimal.GetBits(value);
- il.EmitInt(bits[0]);
- il.EmitInt(bits[1]);
- il.EmitInt(bits[2]);
- il.EmitBoolean((bits[3] & 0x80000000) != 0);
- il.EmitByte((byte)(bits[3] >> 16));
- il.EmitNew(typeof(decimal).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) }));
- }
-
- /// <summary>
- /// Emits default(T)
- /// Semantics match C# compiler behavior
- /// </summary>
- internal static void EmitDefault(this ILGenerator il, Type type) {
- switch (Type.GetTypeCode(type)) {
- case TypeCode.Object:
- case TypeCode.DateTime:
- if (type.IsValueType) {
- // Type.GetTypeCode on an enum returns the underlying
- // integer TypeCode, so we won't get here.
- Debug.Assert(!type.IsEnum);
-
- // This is the IL for default(T) if T is a generic type
- // parameter, so it should work for any type. It's also
- // the standard pattern for structs.
- LocalBuilder lb = il.DeclareLocal(type);
- il.Emit(OpCodes.Ldloca, lb);
- il.Emit(OpCodes.Initobj, type);
- il.Emit(OpCodes.Ldloc, lb);
- } else {
- il.Emit(OpCodes.Ldnull);
- }
- break;
-
- case TypeCode.Empty:
- case TypeCode.String:
- case TypeCode.DBNull:
- il.Emit(OpCodes.Ldnull);
- break;
-
- case TypeCode.Boolean:
- case TypeCode.Char:
- case TypeCode.SByte:
- case TypeCode.Byte:
- case TypeCode.Int16:
- case TypeCode.UInt16:
- case TypeCode.Int32:
- case TypeCode.UInt32:
- il.Emit(OpCodes.Ldc_I4_0);
- break;
-
- case TypeCode.Int64:
- case TypeCode.UInt64:
- il.Emit(OpCodes.Ldc_I4_0);
- il.Emit(OpCodes.Conv_I8);
- break;
-
- case TypeCode.Single:
- il.Emit(OpCodes.Ldc_R4, default(Single));
- break;
-
- case TypeCode.Double:
- il.Emit(OpCodes.Ldc_R8, default(Double));
- break;
-
- case TypeCode.Decimal:
- il.Emit(OpCodes.Ldc_I4_0);
- il.Emit(OpCodes.Newobj, typeof(Decimal).GetConstructor(new Type[] { typeof(int) }));
- break;
-
- default:
- throw ContractUtils.Unreachable;
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/KeyedQueue.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/KeyedQueue.cs
deleted file mode 100644
index cdca6446351..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/KeyedQueue.cs
+++ /dev/null
@@ -1,88 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Collections.Generic;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
-
- /// <summary>
- /// A simple dictionary of queues, keyed off a particular type
- /// This is useful for storing free lists of variables
- /// </summary>
- internal sealed class KeyedQueue<K, V> {
- private readonly Dictionary<K, Queue<V>> _data;
-
- internal KeyedQueue() {
- _data = new Dictionary<K, Queue<V>>();
- }
-
- internal void Enqueue(K key, V value) {
- Queue<V> queue;
- if (!_data.TryGetValue(key, out queue)) {
- _data.Add(key, queue = new Queue<V>());
- }
- queue.Enqueue(value);
- }
-
- internal V Dequeue(K key) {
- Queue<V> queue;
- if (!_data.TryGetValue(key, out queue)) {
- throw Error.QueueEmpty();
- }
- V result = queue.Dequeue();
- if (queue.Count == 0) {
- _data.Remove(key);
- }
- return result;
- }
-
- internal bool TryDequeue(K key, out V value) {
- Queue<V> queue;
- if (_data.TryGetValue(key, out queue) && queue.Count > 0) {
- value = queue.Dequeue();
- if (queue.Count == 0) {
- _data.Remove(key);
- }
- return true;
- }
- value = default(V);
- return false;
- }
-
- internal V Peek(K key) {
- Queue<V> queue;
- if (!_data.TryGetValue(key, out queue)) {
- throw Error.QueueEmpty();
- }
- return queue.Peek();
- }
-
- internal int GetCount(K key) {
- Queue<V> queue;
- if (!_data.TryGetValue(key, out queue)) {
- return 0;
- }
- return queue.Count;
- }
-
- internal void Clear() {
- _data.Clear();
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LabelInfo.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LabelInfo.cs
deleted file mode 100644
index 74e05ff3090..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LabelInfo.cs
+++ /dev/null
@@ -1,357 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection.Emit;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
-#if !FEATURE_CORE_DLR || SILVERLIGHT
- using ILGenerator = OffsetTrackingILGenerator;
-#endif
-
- /// <summary>
- /// Contains compiler state corresponding to a LabelTarget
- /// See also LabelScopeInfo.
- /// </summary>
- internal sealed class LabelInfo {
- // The tree node representing this label
- private readonly LabelTarget _node;
-
- // The IL label, will be mutated if Node is redefined
- private Label _label;
- private bool _labelDefined;
-
- internal Label Label {
- get {
- EnsureLabelAndValue();
- return _label;
- }
- }
-
- // The local that carries the label's value, if any
- private LocalBuilder _value;
-
- // The blocks where this label is defined. If it has more than one item,
- // the blocks can't be jumped to except from a child block
- private readonly Set<LabelScopeInfo> _definitions = new Set<LabelScopeInfo>();
-
- // Blocks that jump to this block
- private readonly List<LabelScopeInfo> _references = new List<LabelScopeInfo>();
-
- // True if this label is the last thing in this block
- // (meaning we can emit a direct return)
- private readonly bool _canReturn;
-
- // True if at least one jump is across blocks
- // If we have any jump across blocks to this label, then the
- // LabelTarget can only be defined in one place
- private bool _acrossBlockJump;
-
- // Until we have more information, default to a leave instruction,
- // which always works. Note: leave spills the stack, so we need to
- // ensure that StackSpiller has guarenteed us an empty stack at this
- // point. Otherwise Leave and Branch are not equivalent
- private OpCode _opCode = OpCodes.Leave;
-
- private readonly ILGenerator _ilg;
-
- internal LabelInfo(ILGenerator il, LabelTarget node, bool canReturn) {
- _ilg = il;
- _node = node;
- _canReturn = canReturn;
- }
-
- internal bool CanReturn {
- get { return _canReturn; }
- }
-
- /// <summary>
- /// Indicates if it is legal to emit a "branch" instruction based on
- /// currently available information. Call the Reference method before
- /// using this property.
- /// </summary>
- internal bool CanBranch {
- get { return _opCode != OpCodes.Leave; }
- }
-
- internal void Reference(LabelScopeInfo block) {
- _references.Add(block);
- if (_definitions.Count > 0) {
- ValidateJump(block);
- }
- }
-
- // Returns true if the label was successfully defined
- // or false if the label is now ambiguous
- internal void Define(LabelScopeInfo block) {
- // Prevent the label from being shadowed, which enforces cleaner
- // trees. Also we depend on this for simplicity (keeping only one
- // active IL Label per LabelInfo)
- for (LabelScopeInfo j = block; j != null; j = j.Parent) {
- if (j.ContainsTarget(_node)) {
- throw Error.LabelTargetAlreadyDefined(_node.Name);
- }
- }
-
- _definitions.Add(block);
- block.AddLabelInfo(_node, this);
-
- // Once defined, validate all jumps
- if (_definitions.Count == 1) {
- foreach (var r in _references) {
- ValidateJump(r);
- }
- } else {
- // Was just redefined, if we had any across block jumps, they're
- // now invalid
- if (_acrossBlockJump) {
- throw Error.AmbiguousJump(_node.Name);
- }
- // For local jumps, we need a new IL label
- // This is okay because:
- // 1. no across block jumps have been made or will be made
- // 2. we don't allow the label to be shadowed
- _labelDefined = false;
- }
- }
-
- private void ValidateJump(LabelScopeInfo reference) {
- // Assume we can do a ret/branch
- _opCode = _canReturn ? OpCodes.Ret : OpCodes.Br;
-
- // look for a simple jump out
- for (LabelScopeInfo j = reference; j != null; j = j.Parent) {
- if (_definitions.Contains(j)) {
- // found it, jump is valid!
- return;
- }
- if (j.Kind == LabelScopeKind.Finally ||
- j.Kind == LabelScopeKind.Filter) {
- break;
- }
- if (j.Kind == LabelScopeKind.Try ||
- j.Kind == LabelScopeKind.Catch) {
- _opCode = OpCodes.Leave;
- }
- }
-
- _acrossBlockJump = true;
- if (_node != null && _node.Type != typeof(void)) {
- throw Error.NonLocalJumpWithValue(_node.Name);
- }
-
- if (_definitions.Count > 1) {
- throw Error.AmbiguousJump(_node.Name);
- }
-
- // We didn't find an outward jump. Look for a jump across blocks
- LabelScopeInfo def = _definitions.First();
- LabelScopeInfo common = Helpers.CommonNode(def, reference, b => b.Parent);
-
- // Assume we can do a ret/branch
- _opCode = _canReturn ? OpCodes.Ret : OpCodes.Br;
-
- // Validate that we aren't jumping across a finally
- for (LabelScopeInfo j = reference; j != common; j = j.Parent) {
- if (j.Kind == LabelScopeKind.Finally) {
- throw Error.ControlCannotLeaveFinally();
- }
- if (j.Kind == LabelScopeKind.Filter) {
- throw Error.ControlCannotLeaveFilterTest();
- }
- if (j.Kind == LabelScopeKind.Try ||
- j.Kind == LabelScopeKind.Catch) {
- _opCode = OpCodes.Leave;
- }
- }
-
- // Valdiate that we aren't jumping into a catch or an expression
- for (LabelScopeInfo j = def; j != common; j = j.Parent) {
- if (!j.CanJumpInto) {
- if (j.Kind == LabelScopeKind.Expression) {
- throw Error.ControlCannotEnterExpression();
- } else {
- throw Error.ControlCannotEnterTry();
- }
- }
- }
- }
-
- internal void ValidateFinish() {
- // Make sure that if this label was jumped to, it is also defined
- if (_references.Count > 0 && _definitions.Count == 0) {
- throw Error.LabelTargetUndefined(_node.Name);
- }
- }
-
- internal void EmitJump() {
- // Return directly if we can
- if (_opCode == OpCodes.Ret) {
- _ilg.Emit(OpCodes.Ret);
- } else {
- StoreValue();
- _ilg.Emit(_opCode, Label);
- }
- }
-
- private void StoreValue() {
- EnsureLabelAndValue();
- if (_value != null) {
- _ilg.Emit(OpCodes.Stloc, _value);
- }
- }
-
- internal void Mark() {
- if (_canReturn) {
- // Don't mark return labels unless they were actually jumped to
- // (returns are last so we know for sure if anyone jumped to it)
- if (!_labelDefined) {
- // We don't even need to emit the "ret" because
- // LambdaCompiler does that for us.
- return;
- }
-
- // Otherwise, emit something like:
- // ret
- // <marked label>:
- // ldloc <value>
- _ilg.Emit(OpCodes.Ret);
- } else {
-
- // For the normal case, we emit:
- // stloc <value>
- // <marked label>:
- // ldloc <value>
- StoreValue();
- }
- MarkWithEmptyStack();
- }
-
- // Like Mark, but assumes the stack is empty
- internal void MarkWithEmptyStack() {
- _ilg.MarkLabel(Label);
- if (_value != null) {
- // We always read the value from a local, because we don't know
- // if there will be a "leave" instruction targeting it ("branch"
- // preserves its stack, but "leave" empties the stack)
- _ilg.Emit(OpCodes.Ldloc, _value);
- }
- }
-
- private void EnsureLabelAndValue() {
- if (!_labelDefined) {
- _labelDefined = true;
- _label = _ilg.DefineLabel();
- if (_node != null && _node.Type != typeof(void)) {
- _value = _ilg.DeclareLocal(_node.Type);
- }
- }
- }
- }
-
- internal enum LabelScopeKind {
- // any "statement like" node that can be jumped into
- Statement,
-
- // these correspond to the node of the same name
- Block,
- Switch,
- Lambda,
- Try,
-
- // these correspond to the part of the try block we're in
- Catch,
- Finally,
- Filter,
-
- // the catch-all value for any other expression type
- // (means we can't jump into it)
- Expression,
- }
-
- //
- // Tracks scoping information for LabelTargets. Logically corresponds to a
- // "label scope". Even though we have arbitrary goto support, we still need
- // to track what kinds of nodes that gotos are jumping through, both to
- // emit property IL ("leave" out of a try block), and for validation, and
- // to allow labels to be duplicated in the tree, as long as the jumps are
- // considered "up only" jumps.
- //
- // We create one of these for every Expression that can be jumped into, as
- // well as creating them for the first expression we can't jump into. The
- // "Kind" property indicates what kind of scope this is.
- //
- internal sealed class LabelScopeInfo {
- private Dictionary<LabelTarget, LabelInfo> Labels; // lazily allocated, we typically use this only once every 6th-7th block
- internal readonly LabelScopeKind Kind;
- internal readonly LabelScopeInfo Parent;
-
- internal LabelScopeInfo(LabelScopeInfo parent, LabelScopeKind kind) {
- Parent = parent;
- Kind = kind;
- }
-
- /// <summary>
- /// Returns true if we can jump into this node
- /// </summary>
- internal bool CanJumpInto {
- get {
- switch (Kind) {
- case LabelScopeKind.Block:
- case LabelScopeKind.Statement:
- case LabelScopeKind.Switch:
- case LabelScopeKind.Lambda:
- return true;
- }
- return false;
- }
- }
-
-
- internal bool ContainsTarget(LabelTarget target) {
- if (Labels == null) {
- return false;
- }
-
- return Labels.ContainsKey(target);
- }
-
- internal bool TryGetLabelInfo(LabelTarget target, out LabelInfo info) {
- if (Labels == null) {
- info = null;
- return false;
- }
-
- return Labels.TryGetValue(target, out info);
- }
-
- internal void AddLabelInfo(LabelTarget target, LabelInfo info) {
- Debug.Assert(CanJumpInto);
-
- if (Labels == null) {
- Labels = new Dictionary<LabelTarget, LabelInfo>();
- }
-
- Labels.Add(target, info);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Address.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Address.cs
deleted file mode 100644
index 5b34dd25aed..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Address.cs
+++ /dev/null
@@ -1,334 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Reflection.Emit;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- partial class LambdaCompiler {
- private void EmitAddress(Expression node, Type type) {
- EmitAddress(node, type, CompilationFlags.EmitExpressionStart);
- }
-
- // We don't want "ref" parameters to modify values of expressions
- // except where it would in IL: locals, args, fields, and array elements
- // (Unbox is an exception, it's intended to emit a ref to the orignal
- // boxed value)
- private void EmitAddress(Expression node, Type type, CompilationFlags flags) {
- Debug.Assert(node != null);
- bool emitStart = (flags & CompilationFlags.EmitExpressionStartMask) == CompilationFlags.EmitExpressionStart;
- CompilationFlags startEmitted = emitStart ? EmitExpressionStart(node) : CompilationFlags.EmitNoExpressionStart;
-
- switch (node.NodeType) {
- default:
- EmitExpressionAddress(node, type);
- break;
-
- case ExpressionType.ArrayIndex:
- AddressOf((BinaryExpression)node, type);
- break;
-
- case ExpressionType.Parameter:
- AddressOf((ParameterExpression)node, type);
- break;
-
- case ExpressionType.MemberAccess:
- AddressOf((MemberExpression)node, type);
- break;
-
- case ExpressionType.Unbox:
- AddressOf((UnaryExpression)node, type);
- break;
-
- case ExpressionType.Call:
- AddressOf((MethodCallExpression)node, type);
- break;
-
- case ExpressionType.Index:
- AddressOf((IndexExpression)node, type);
- break;
- }
-
- if (emitStart) {
- EmitExpressionEnd(startEmitted);
- }
- }
-
-
- private void AddressOf(BinaryExpression node, Type type) {
- Debug.Assert(node.NodeType == ExpressionType.ArrayIndex && node.Method == null);
-
- if (TypeUtils.AreEquivalent(type, node.Type)) {
- EmitExpression(node.Left);
- EmitExpression(node.Right);
- Type rightType = node.Right.Type;
- if (TypeUtils.IsNullableType(rightType)) {
- LocalBuilder loc = GetLocal(rightType);
- _ilg.Emit(OpCodes.Stloc, loc);
- _ilg.Emit(OpCodes.Ldloca, loc);
- _ilg.EmitGetValue(rightType);
- FreeLocal(loc);
- }
- Type indexType = TypeUtils.GetNonNullableType(rightType);
- if (indexType != typeof(int)) {
- _ilg.EmitConvertToType(indexType, typeof(int), true);
- }
- _ilg.Emit(OpCodes.Ldelema, node.Type);
- } else {
- EmitExpressionAddress(node, type);
- }
- }
-
- private void AddressOf(ParameterExpression node, Type type) {
- if (TypeUtils.AreEquivalent(type, node.Type)) {
- if (node.IsByRef) {
- _scope.EmitGet(node);
- } else {
- _scope.EmitAddressOf(node);
- }
- } else {
- EmitExpressionAddress(node, type);
- }
- }
-
-
- private void AddressOf(MemberExpression node, Type type) {
- if (TypeUtils.AreEquivalent(type, node.Type)) {
- // emit "this", if any
- Type objectType = null;
- if (node.Expression != null) {
- EmitInstance(node.Expression, objectType = node.Expression.Type);
- }
- EmitMemberAddress(node.Member, objectType);
- } else {
- EmitExpressionAddress(node, type);
- }
- }
-
- // assumes the instance is already on the stack
- private void EmitMemberAddress(MemberInfo member, Type objectType) {
- if (member.MemberType == MemberTypes.Field) {
- FieldInfo field = (FieldInfo)member;
-
- // Verifiable code may not take the address of an init-only field.
- // If we are asked to do so then get the value out of the field, stuff it
- // into a local of the same type, and then take the address of the local.
- // Typically this is what we want to do anyway; if we are saying
- // Foo.bar.ToString() for a static value-typed field bar then we don't need
- // the address of field bar to do the call. The address of a local which
- // has the same value as bar is sufficient.
-
- // CONSIDER:
- // The C# compiler will not compile a lambda expression tree
- // which writes to the address of an init-only field. But one could
- // probably use the expression tree API to build such an expression.
- // (When compiled, such an expression would fail silently.) It might
- // be worth it to add checking to the expression tree API to ensure
- // that it is illegal to attempt to write to an init-only field,
- // the same way that it is illegal to write to a read-only property.
- // The same goes for literal fields.
- if (!field.IsLiteral && !field.IsInitOnly) {
- _ilg.EmitFieldAddress(field);
- return;
- }
- }
-
- EmitMemberGet(member, objectType);
- LocalBuilder temp = GetLocal(GetMemberType(member));
- _ilg.Emit(OpCodes.Stloc, temp);
- _ilg.Emit(OpCodes.Ldloca, temp);
- }
-
-
- private void AddressOf(MethodCallExpression node, Type type) {
- // An array index of a multi-dimensional array is represented by a call to Array.Get,
- // rather than having its own array-access node. This means that when we are trying to
- // get the address of a member of a multi-dimensional array, we'll be trying to
- // get the address of a Get method, and it will fail to do so. Instead, detect
- // this situation and replace it with a call to the Address method.
- if (!node.Method.IsStatic &&
- node.Object.Type.IsArray &&
- node.Method == node.Object.Type.GetMethod("Get", BindingFlags.Public | BindingFlags.Instance)) {
-
- MethodInfo mi = node.Object.Type.GetMethod("Address", BindingFlags.Public | BindingFlags.Instance);
-
- EmitMethodCall(node.Object, mi, node);
- } else {
- EmitExpressionAddress(node, type);
- }
- }
-
- private void AddressOf(IndexExpression node, Type type) {
- if (!TypeUtils.AreEquivalent(type, node.Type) || node.Indexer != null) {
- EmitExpressionAddress(node, type);
- return;
- }
-
- if (node.Arguments.Count == 1) {
- EmitExpression(node.Object);
- EmitExpression(node.Arguments[0]);
- _ilg.Emit(OpCodes.Ldelema, node.Type);
- } else {
- var address = node.Object.Type.GetMethod("Address", BindingFlags.Public | BindingFlags.Instance);
- EmitMethodCall(node.Object, address, node);
- }
- }
-
- private void AddressOf(UnaryExpression node, Type type) {
- Debug.Assert(node.NodeType == ExpressionType.Unbox);
- Debug.Assert(type.IsValueType && !TypeUtils.IsNullableType(type));
-
- // Unbox leaves a pointer to the boxed value on the stack
- EmitExpression(node.Operand);
- _ilg.Emit(OpCodes.Unbox, type);
- }
-
- private void EmitExpressionAddress(Expression node, Type type) {
- Debug.Assert(TypeUtils.AreReferenceAssignable(type, node.Type));
-
- EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart);
- LocalBuilder tmp = GetLocal(type);
- _ilg.Emit(OpCodes.Stloc, tmp);
- _ilg.Emit(OpCodes.Ldloca, tmp);
- }
-
-
- // Emits the address of the expression, returning the write back if necessary
- //
- // For properties, we want to write back into the property if it's
- // passed byref.
- private WriteBack EmitAddressWriteBack(Expression node, Type type) {
- CompilationFlags startEmitted = EmitExpressionStart(node);
-
- WriteBack result = null;
- if (TypeUtils.AreEquivalent(type, node.Type)) {
- switch (node.NodeType) {
- case ExpressionType.MemberAccess:
- result = AddressOfWriteBack((MemberExpression)node);
- break;
- case ExpressionType.Index:
- result = AddressOfWriteBack((IndexExpression)node);
- break;
- }
- }
- if (result == null) {
- EmitAddress(node, type, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart);
- }
-
- EmitExpressionEnd(startEmitted);
-
- return result;
- }
-
- private WriteBack AddressOfWriteBack(MemberExpression node) {
- if (node.Member.MemberType != MemberTypes.Property || !((PropertyInfo)node.Member).CanWrite) {
- return null;
- }
-
- // emit instance, if any
- LocalBuilder instanceLocal = null;
- Type instanceType = null;
- if (node.Expression != null) {
- EmitInstance(node.Expression, instanceType = node.Expression.Type);
- // store in local
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Stloc, instanceLocal = GetLocal(instanceType));
- }
-
- PropertyInfo pi = (PropertyInfo)node.Member;
-
- // emit the get
- EmitCall(instanceType, pi.GetGetMethod(true));
-
- // emit the address of the value
- var valueLocal = GetLocal(node.Type);
- _ilg.Emit(OpCodes.Stloc, valueLocal);
- _ilg.Emit(OpCodes.Ldloca, valueLocal);
-
- // Set the property after the method call
- // don't re-evaluate anything
- return delegate() {
- if (instanceLocal != null) {
- _ilg.Emit(OpCodes.Ldloc, instanceLocal);
- FreeLocal(instanceLocal);
- }
- _ilg.Emit(OpCodes.Ldloc, valueLocal);
- FreeLocal(valueLocal);
- EmitCall(instanceType, pi.GetSetMethod(true));
- };
- }
-
- private WriteBack AddressOfWriteBack(IndexExpression node) {
- if (node.Indexer == null || !node.Indexer.CanWrite) {
- return null;
- }
-
- // emit instance, if any
- LocalBuilder instanceLocal = null;
- Type instanceType = null;
- if (node.Object != null) {
- EmitInstance(node.Object, instanceType = node.Object.Type);
-
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Stloc, instanceLocal = GetLocal(instanceType));
- }
-
- // Emit indexes. We don't allow byref args, so no need to worry
- // about writebacks or EmitAddress
- List<LocalBuilder> args = new List<LocalBuilder>();
- foreach (var arg in node.Arguments) {
- EmitExpression(arg);
-
- var argLocal = GetLocal(arg.Type);
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Stloc, argLocal);
- args.Add(argLocal);
- }
-
- // emit the get
- EmitGetIndexCall(node, instanceType);
-
- // emit the address of the value
- var valueLocal = GetLocal(node.Type);
- _ilg.Emit(OpCodes.Stloc, valueLocal);
- _ilg.Emit(OpCodes.Ldloca, valueLocal);
-
- // Set the property after the method call
- // don't re-evaluate anything
- return delegate() {
- if (instanceLocal != null) {
- _ilg.Emit(OpCodes.Ldloc, instanceLocal);
- FreeLocal(instanceLocal);
- }
- foreach (var arg in args) {
- _ilg.Emit(OpCodes.Ldloc, arg);
- FreeLocal(arg);
- }
- _ilg.Emit(OpCodes.Ldloc, valueLocal);
- FreeLocal(valueLocal);
-
- EmitSetIndexCall(node, instanceType);
- };
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Binary.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Binary.cs
deleted file mode 100644
index 3c9ec62326e..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Binary.cs
+++ /dev/null
@@ -1,707 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Reflection.Emit;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- partial class LambdaCompiler {
-
- private void EmitBinaryExpression(Expression expr) {
- EmitBinaryExpression(expr, CompilationFlags.EmitAsNoTail);
- }
-
- private void EmitBinaryExpression(Expression expr, CompilationFlags flags) {
- BinaryExpression b = (BinaryExpression)expr;
-
- Debug.Assert(b.NodeType != ExpressionType.AndAlso && b.NodeType != ExpressionType.OrElse && b.NodeType != ExpressionType.Coalesce);
-
- if (b.Method != null) {
- EmitBinaryMethod(b, flags);
- return;
- }
-
- // For EQ and NE, if there is a user-specified method, use it.
- // Otherwise implement the C# semantics that allow equality
- // comparisons on non-primitive nullable structs that don't
- // overload "=="
- if ((b.NodeType == ExpressionType.Equal || b.NodeType == ExpressionType.NotEqual) &&
- (b.Type == typeof(bool) || b.Type == typeof(bool?))) {
-
- // If we have x==null, x!=null, null==x or null!=x where x is
- // nullable but not null, then generate a call to x.HasValue.
- Debug.Assert(!b.IsLiftedToNull || b.Type == typeof(bool?));
- if (ConstantCheck.IsNull(b.Left) && !ConstantCheck.IsNull(b.Right) && TypeUtils.IsNullableType(b.Right.Type)) {
- EmitNullEquality(b.NodeType, b.Right, b.IsLiftedToNull);
- return;
- }
- if (ConstantCheck.IsNull(b.Right) && !ConstantCheck.IsNull(b.Left) && TypeUtils.IsNullableType(b.Left.Type)) {
- EmitNullEquality(b.NodeType, b.Left, b.IsLiftedToNull);
- return;
- }
-
- // For EQ and NE, we can avoid some conversions if we're
- // ultimately just comparing two managed pointers.
- EmitExpression(GetEqualityOperand(b.Left));
- EmitExpression(GetEqualityOperand(b.Right));
- } else {
- // Otherwise generate it normally
- EmitExpression(b.Left);
- EmitExpression(b.Right);
- }
-
- EmitBinaryOperator(b.NodeType, b.Left.Type, b.Right.Type, b.Type, b.IsLiftedToNull);
- }
-
-
- private void EmitNullEquality(ExpressionType op, Expression e, bool isLiftedToNull) {
- Debug.Assert(TypeUtils.IsNullableType(e.Type));
- Debug.Assert(op == ExpressionType.Equal || op == ExpressionType.NotEqual);
- // If we are lifted to null then just evaluate the expression for its side effects, discard,
- // and generate null. If we are not lifted to null then generate a call to HasValue.
- if (isLiftedToNull) {
- EmitExpressionAsVoid(e);
- _ilg.EmitDefault(typeof(bool?));
- } else {
- EmitAddress(e, e.Type);
- _ilg.EmitHasValue(e.Type);
- if (op == ExpressionType.Equal) {
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- }
- }
- }
-
-
- private void EmitBinaryMethod(BinaryExpression b, CompilationFlags flags) {
- if (b.IsLifted) {
- ParameterExpression p1 = Expression.Variable(TypeUtils.GetNonNullableType(b.Left.Type), null);
- ParameterExpression p2 = Expression.Variable(TypeUtils.GetNonNullableType(b.Right.Type), null);
- MethodCallExpression mc = Expression.Call(null, b.Method, p1, p2);
- Type resultType = null;
- if (b.IsLiftedToNull) {
- resultType = TypeUtils.GetNullableType(mc.Type);
- } else {
- switch (b.NodeType) {
- case ExpressionType.Equal:
- case ExpressionType.NotEqual:
- case ExpressionType.LessThan:
- case ExpressionType.LessThanOrEqual:
- case ExpressionType.GreaterThan:
- case ExpressionType.GreaterThanOrEqual:
- if (mc.Type != typeof(bool)) {
- throw Error.ArgumentMustBeBoolean();
- }
- resultType = typeof(bool);
- break;
- default:
- resultType = TypeUtils.GetNullableType(mc.Type);
- break;
- }
- }
- var variables = new ParameterExpression[] { p1, p2 };
- var arguments = new Expression[] { b.Left, b.Right };
- ValidateLift(variables, arguments);
- EmitLift(b.NodeType, resultType, mc, variables, arguments);
- } else {
- EmitMethodCallExpression(Expression.Call(null, b.Method, b.Left, b.Right), flags);
- }
- }
-
-
- private void EmitBinaryOperator(ExpressionType op, Type leftType, Type rightType, Type resultType, bool liftedToNull) {
- bool leftIsNullable = TypeUtils.IsNullableType(leftType);
- bool rightIsNullable = TypeUtils.IsNullableType(rightType);
-
- switch (op) {
- case ExpressionType.ArrayIndex:
- if (rightType != typeof(int)) {
- throw ContractUtils.Unreachable;
- }
- _ilg.EmitLoadElement(leftType.GetElementType());
- return;
- case ExpressionType.Coalesce:
- throw Error.UnexpectedCoalesceOperator();
- }
-
- if (leftIsNullable || rightIsNullable) {
- EmitLiftedBinaryOp(op, leftType, rightType, resultType, liftedToNull);
- } else {
- EmitUnliftedBinaryOp(op, leftType, rightType);
- EmitConvertArithmeticResult(op, resultType);
- }
- }
-
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- private void EmitUnliftedBinaryOp(ExpressionType op, Type leftType, Type rightType) {
- Debug.Assert(!TypeUtils.IsNullableType(leftType));
- Debug.Assert(!TypeUtils.IsNullableType(rightType));
-
- if (op == ExpressionType.Equal || op == ExpressionType.NotEqual) {
- EmitUnliftedEquality(op, leftType);
- return;
- }
- if (!leftType.IsPrimitive) {
- throw Error.OperatorNotImplementedForType(op, leftType);
- }
- switch (op) {
- case ExpressionType.Add:
- _ilg.Emit(OpCodes.Add);
- break;
- case ExpressionType.AddChecked:
- if (TypeUtils.IsFloatingPoint(leftType)) {
- _ilg.Emit(OpCodes.Add);
- } else if (TypeUtils.IsUnsigned(leftType)) {
- _ilg.Emit(OpCodes.Add_Ovf_Un);
- } else {
- _ilg.Emit(OpCodes.Add_Ovf);
- }
- break;
- case ExpressionType.Subtract:
- _ilg.Emit(OpCodes.Sub);
- break;
- case ExpressionType.SubtractChecked:
- if (TypeUtils.IsFloatingPoint(leftType)) {
- _ilg.Emit(OpCodes.Sub);
- } else if (TypeUtils.IsUnsigned(leftType)) {
- _ilg.Emit(OpCodes.Sub_Ovf_Un);
- } else {
- _ilg.Emit(OpCodes.Sub_Ovf);
- }
- break;
- case ExpressionType.Multiply:
- _ilg.Emit(OpCodes.Mul);
- break;
- case ExpressionType.MultiplyChecked:
- if (TypeUtils.IsFloatingPoint(leftType)) {
- _ilg.Emit(OpCodes.Mul);
- } else if (TypeUtils.IsUnsigned(leftType)) {
- _ilg.Emit(OpCodes.Mul_Ovf_Un);
- } else {
- _ilg.Emit(OpCodes.Mul_Ovf);
- }
- break;
- case ExpressionType.Divide:
- if (TypeUtils.IsUnsigned(leftType)) {
- _ilg.Emit(OpCodes.Div_Un);
- } else {
- _ilg.Emit(OpCodes.Div);
- }
- break;
- case ExpressionType.Modulo:
- if (TypeUtils.IsUnsigned(leftType)) {
- _ilg.Emit(OpCodes.Rem_Un);
- } else {
- _ilg.Emit(OpCodes.Rem);
- }
- break;
- case ExpressionType.And:
- case ExpressionType.AndAlso:
- _ilg.Emit(OpCodes.And);
- break;
- case ExpressionType.Or:
- case ExpressionType.OrElse:
- _ilg.Emit(OpCodes.Or);
- break;
- case ExpressionType.LessThan:
- if (TypeUtils.IsUnsigned(leftType)) {
- _ilg.Emit(OpCodes.Clt_Un);
- } else {
- _ilg.Emit(OpCodes.Clt);
- }
- break;
- case ExpressionType.LessThanOrEqual: {
- Label labFalse = _ilg.DefineLabel();
- Label labEnd = _ilg.DefineLabel();
- if (TypeUtils.IsUnsigned(leftType)) {
- _ilg.Emit(OpCodes.Ble_Un_S, labFalse);
- } else {
- _ilg.Emit(OpCodes.Ble_S, labFalse);
- }
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Br_S, labEnd);
- _ilg.MarkLabel(labFalse);
- _ilg.Emit(OpCodes.Ldc_I4_1);
- _ilg.MarkLabel(labEnd);
- }
- break;
- case ExpressionType.GreaterThan:
- if (TypeUtils.IsUnsigned(leftType)) {
- _ilg.Emit(OpCodes.Cgt_Un);
- } else {
- _ilg.Emit(OpCodes.Cgt);
- }
- break;
- case ExpressionType.GreaterThanOrEqual: {
- Label labFalse = _ilg.DefineLabel();
- Label labEnd = _ilg.DefineLabel();
- if (TypeUtils.IsUnsigned(leftType)) {
- _ilg.Emit(OpCodes.Bge_Un_S, labFalse);
- } else {
- _ilg.Emit(OpCodes.Bge_S, labFalse);
- }
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Br_S, labEnd);
- _ilg.MarkLabel(labFalse);
- _ilg.Emit(OpCodes.Ldc_I4_1);
- _ilg.MarkLabel(labEnd);
- }
- break;
- case ExpressionType.ExclusiveOr:
- _ilg.Emit(OpCodes.Xor);
- break;
- case ExpressionType.LeftShift:
- if (rightType != typeof(int)) {
- throw ContractUtils.Unreachable;
- }
- // Note: If this code is made to handle unsigned
- // rightType types, emit the following when rightType:
- // is unsigned
- //_ilg.EmitInt(0x3f);
- _ilg.EmitInt(0x1f);
- _ilg.Emit(OpCodes.And);
- _ilg.Emit(OpCodes.Shl);
- break;
- case ExpressionType.RightShift:
- if (rightType != typeof(int)) {
- throw ContractUtils.Unreachable;
- }
- if (TypeUtils.IsUnsigned(leftType)) {
- _ilg.Emit(OpCodes.Shr_Un);
- } else {
- _ilg.Emit(OpCodes.Shr);
- }
- break;
- default:
- throw Error.UnhandledBinary(op);
- }
- }
-
- // Binary/unary operations on 8 and 16 bit operand types will leave a
- // 32-bit value on the stack, because that's how IL works. For these
- // cases, we need to cast it back to the resultType, possibly using a
- // checked conversion if the original operator was convert
- private void EmitConvertArithmeticResult(ExpressionType op, Type resultType) {
- Debug.Assert(!resultType.IsNullableType());
-
- switch (Type.GetTypeCode(resultType)) {
- case TypeCode.Byte:
- _ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_U1 : OpCodes.Conv_U1);
- break;
- case TypeCode.SByte:
- _ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_I1 : OpCodes.Conv_I1);
- break;
- case TypeCode.UInt16:
- _ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_U2 : OpCodes.Conv_U2);
- break;
- case TypeCode.Int16:
- _ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_I2 : OpCodes.Conv_I2);
- break;
- }
- }
-
- private void EmitUnliftedEquality(ExpressionType op, Type type) {
- Debug.Assert(op == ExpressionType.Equal || op == ExpressionType.NotEqual);
- if (!type.IsPrimitive && type.IsValueType && !type.IsEnum) {
- throw Error.OperatorNotImplementedForType(op, type);
- }
- _ilg.Emit(OpCodes.Ceq);
- if (op == ExpressionType.NotEqual) {
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- }
- }
-
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- private void EmitLiftedBinaryOp(ExpressionType op, Type leftType, Type rightType, Type resultType, bool liftedToNull) {
- Debug.Assert(TypeUtils.IsNullableType(leftType) || TypeUtils.IsNullableType(rightType));
- switch (op) {
- case ExpressionType.And:
- if (leftType == typeof(bool?)) {
- EmitLiftedBooleanAnd();
- } else {
- EmitLiftedBinaryArithmetic(op, leftType, rightType, resultType);
- }
- break;
- case ExpressionType.Or:
- if (leftType == typeof(bool?)) {
- EmitLiftedBooleanOr();
- } else {
- EmitLiftedBinaryArithmetic(op, leftType, rightType, resultType);
- }
- break;
- case ExpressionType.ExclusiveOr:
- case ExpressionType.Add:
- case ExpressionType.AddChecked:
- case ExpressionType.Subtract:
- case ExpressionType.SubtractChecked:
- case ExpressionType.Multiply:
- case ExpressionType.MultiplyChecked:
- case ExpressionType.Divide:
- case ExpressionType.Modulo:
- case ExpressionType.LeftShift:
- case ExpressionType.RightShift:
- EmitLiftedBinaryArithmetic(op, leftType, rightType, resultType);
- break;
- case ExpressionType.LessThan:
- case ExpressionType.LessThanOrEqual:
- case ExpressionType.GreaterThan:
- case ExpressionType.GreaterThanOrEqual:
- case ExpressionType.Equal:
- case ExpressionType.NotEqual:
- EmitLiftedRelational(op, leftType, rightType, resultType, liftedToNull);
- break;
- case ExpressionType.AndAlso:
- case ExpressionType.OrElse:
- default:
- throw ContractUtils.Unreachable;
- }
- }
-
-
- private void EmitLiftedRelational(ExpressionType op, Type leftType, Type rightType, Type resultType, bool liftedToNull) {
- Debug.Assert(TypeUtils.IsNullableType(leftType));
-
- Label shortCircuit = _ilg.DefineLabel();
- LocalBuilder locLeft = GetLocal(leftType);
- LocalBuilder locRight = GetLocal(rightType);
-
- // store values (reverse order since they are already on the stack)
- _ilg.Emit(OpCodes.Stloc, locRight);
- _ilg.Emit(OpCodes.Stloc, locLeft);
-
- if (op == ExpressionType.Equal) {
- // test for both null -> true
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(leftType);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitHasValue(rightType);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.And);
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Brtrue_S, shortCircuit);
- _ilg.Emit(OpCodes.Pop);
-
- // test for either is null -> false
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(leftType);
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitHasValue(rightType);
- _ilg.Emit(OpCodes.And);
-
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Brfalse_S, shortCircuit);
- _ilg.Emit(OpCodes.Pop);
- } else if (op == ExpressionType.NotEqual) {
- // test for both null -> false
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(leftType);
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitHasValue(rightType);
- _ilg.Emit(OpCodes.Or);
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Brfalse_S, shortCircuit);
- _ilg.Emit(OpCodes.Pop);
-
- // test for either is null -> true
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(leftType);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitHasValue(rightType);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Or);
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Brtrue_S, shortCircuit);
- _ilg.Emit(OpCodes.Pop);
- } else {
- // test for either is null -> false
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(leftType);
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitHasValue(rightType);
- _ilg.Emit(OpCodes.And);
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Brfalse_S, shortCircuit);
- _ilg.Emit(OpCodes.Pop);
- }
-
- // do op on values
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitGetValueOrDefault(leftType);
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitGetValueOrDefault(rightType);
-
- //RELEASING locLeft locRight
- FreeLocal(locLeft);
- FreeLocal(locRight);
-
- EmitBinaryOperator(
- op,
- TypeUtils.GetNonNullableType(leftType),
- TypeUtils.GetNonNullableType(rightType),
- TypeUtils.GetNonNullableType(resultType),
- false
- );
-
- if (!liftedToNull) {
- _ilg.MarkLabel(shortCircuit);
- }
-
- if (!TypeUtils.AreEquivalent(resultType, TypeUtils.GetNonNullableType(resultType))) {
- _ilg.EmitConvertToType(TypeUtils.GetNonNullableType(resultType), resultType, true);
- }
-
- if (liftedToNull) {
- Label labEnd = _ilg.DefineLabel();
- _ilg.Emit(OpCodes.Br, labEnd);
- _ilg.MarkLabel(shortCircuit);
- _ilg.Emit(OpCodes.Pop);
- _ilg.Emit(OpCodes.Ldnull);
- _ilg.Emit(OpCodes.Unbox_Any, resultType);
- _ilg.MarkLabel(labEnd);
- }
- }
-
-
- private void EmitLiftedBinaryArithmetic(ExpressionType op, Type leftType, Type rightType, Type resultType) {
- bool leftIsNullable = TypeUtils.IsNullableType(leftType);
- bool rightIsNullable = TypeUtils.IsNullableType(rightType);
-
- Debug.Assert(leftIsNullable || rightIsNullable);
-
- Label labIfNull = _ilg.DefineLabel();
- Label labEnd = _ilg.DefineLabel();
- LocalBuilder locLeft = GetLocal(leftType);
- LocalBuilder locRight = GetLocal(rightType);
- LocalBuilder locResult = GetLocal(resultType);
-
- // store values (reverse order since they are already on the stack)
- _ilg.Emit(OpCodes.Stloc, locRight);
- _ilg.Emit(OpCodes.Stloc, locLeft);
-
- // test for null
- // use short circuiting
- if (leftIsNullable) {
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(leftType);
- _ilg.Emit(OpCodes.Brfalse_S, labIfNull);
- }
- if (rightIsNullable) {
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitHasValue(rightType);
- _ilg.Emit(OpCodes.Brfalse_S, labIfNull);
- }
-
- // do op on values
- if (leftIsNullable) {
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitGetValueOrDefault(leftType);
- } else {
- _ilg.Emit(OpCodes.Ldloc, locLeft);
- }
-
- if (rightIsNullable) {
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitGetValueOrDefault(rightType);
- } else {
- _ilg.Emit(OpCodes.Ldloc, locRight);
- }
-
- //RELEASING locLeft locRight
- FreeLocal(locLeft);
- FreeLocal(locRight);
-
- EmitBinaryOperator(op, TypeUtils.GetNonNullableType(leftType), TypeUtils.GetNonNullableType(rightType), TypeUtils.GetNonNullableType(resultType), false);
-
- // construct result type
- ConstructorInfo ci = resultType.GetConstructor(new Type[] { TypeUtils.GetNonNullableType(resultType) });
- _ilg.Emit(OpCodes.Newobj, ci);
- _ilg.Emit(OpCodes.Stloc, locResult);
- _ilg.Emit(OpCodes.Br_S, labEnd);
-
- // if null then create a default one
- _ilg.MarkLabel(labIfNull);
- _ilg.Emit(OpCodes.Ldloca, locResult);
- _ilg.Emit(OpCodes.Initobj, resultType);
-
- _ilg.MarkLabel(labEnd);
-
- _ilg.Emit(OpCodes.Ldloc, locResult);
-
- //RELEASING locResult
- FreeLocal(locResult);
- }
-
-
- private void EmitLiftedBooleanAnd() {
- Type type = typeof(bool?);
- Label labComputeRight = _ilg.DefineLabel();
- Label labReturnFalse = _ilg.DefineLabel();
- Label labReturnNull = _ilg.DefineLabel();
- Label labReturnValue = _ilg.DefineLabel();
- Label labExit = _ilg.DefineLabel();
-
- // store values (reverse order since they are already on the stack)
- LocalBuilder locLeft = GetLocal(type);
- LocalBuilder locRight = GetLocal(type);
- _ilg.Emit(OpCodes.Stloc, locRight);
- _ilg.Emit(OpCodes.Stloc, locLeft);
-
- // compute left
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(type);
- _ilg.Emit(OpCodes.Brfalse, labComputeRight);
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitGetValueOrDefault(type);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Brtrue, labReturnFalse);
-
- // compute right
- _ilg.MarkLabel(labComputeRight);
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitHasValue(type);
- _ilg.Emit(OpCodes.Brfalse_S, labReturnNull);
- _ilg.Emit(OpCodes.Ldloca, locRight);
-
- //RELEASING locRight
- FreeLocal(locRight);
-
- _ilg.EmitGetValueOrDefault(type);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Brtrue_S, labReturnFalse);
-
- // check left for null again
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(type);
- _ilg.Emit(OpCodes.Brfalse, labReturnNull);
-
- // return true
- _ilg.Emit(OpCodes.Ldc_I4_1);
- _ilg.Emit(OpCodes.Br_S, labReturnValue);
-
- // return false
- _ilg.MarkLabel(labReturnFalse);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Br_S, labReturnValue);
-
- _ilg.MarkLabel(labReturnValue);
- ConstructorInfo ci = type.GetConstructor(new Type[] { typeof(bool) });
- _ilg.Emit(OpCodes.Newobj, ci);
- _ilg.Emit(OpCodes.Stloc, locLeft);
- _ilg.Emit(OpCodes.Br, labExit);
-
- // return null
- _ilg.MarkLabel(labReturnNull);
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.Emit(OpCodes.Initobj, type);
-
- _ilg.MarkLabel(labExit);
- _ilg.Emit(OpCodes.Ldloc, locLeft);
-
- //RELEASING locLeft
- FreeLocal(locLeft);
- }
-
-
- private void EmitLiftedBooleanOr() {
- Type type = typeof(bool?);
- Label labComputeRight = _ilg.DefineLabel();
- Label labReturnTrue = _ilg.DefineLabel();
- Label labReturnNull = _ilg.DefineLabel();
- Label labReturnValue = _ilg.DefineLabel();
- Label labExit = _ilg.DefineLabel();
-
- // store values (reverse order since they are already on the stack)
- LocalBuilder locLeft = GetLocal(type);
- LocalBuilder locRight = GetLocal(type);
- _ilg.Emit(OpCodes.Stloc, locRight);
- _ilg.Emit(OpCodes.Stloc, locLeft);
-
- // compute left
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(type);
- _ilg.Emit(OpCodes.Brfalse, labComputeRight);
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitGetValueOrDefault(type);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Brfalse, labReturnTrue);
-
- // compute right
- _ilg.MarkLabel(labComputeRight);
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitHasValue(type);
- _ilg.Emit(OpCodes.Brfalse_S, labReturnNull);
- _ilg.Emit(OpCodes.Ldloca, locRight);
-
- //RELEASING locRight
- FreeLocal(locRight);
-
- _ilg.EmitGetValueOrDefault(type);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Brfalse_S, labReturnTrue);
-
- // check left for null again
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(type);
- _ilg.Emit(OpCodes.Brfalse, labReturnNull);
-
- // return false
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Br_S, labReturnValue);
-
- // return true
- _ilg.MarkLabel(labReturnTrue);
- _ilg.Emit(OpCodes.Ldc_I4_1);
- _ilg.Emit(OpCodes.Br_S, labReturnValue);
-
- _ilg.MarkLabel(labReturnValue);
- ConstructorInfo ci = type.GetConstructor(new Type[] { typeof(bool) });
- _ilg.Emit(OpCodes.Newobj, ci);
- _ilg.Emit(OpCodes.Stloc, locLeft);
- _ilg.Emit(OpCodes.Br, labExit);
-
- // return null
- _ilg.MarkLabel(labReturnNull);
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.Emit(OpCodes.Initobj, type);
-
- _ilg.MarkLabel(labExit);
- _ilg.Emit(OpCodes.Ldloc, locLeft);
-
- //RELEASING locLeft
- FreeLocal(locLeft);
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.ControlFlow.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.ControlFlow.cs
deleted file mode 100644
index 2e8cede7064..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.ControlFlow.cs
+++ /dev/null
@@ -1,257 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
-
- // The part of the LambdaCompiler dealing with low level control flow
- // break, contiue, return, exceptions, etc
- partial class LambdaCompiler {
-
- private LabelInfo EnsureLabel(LabelTarget node) {
- LabelInfo result;
- if (!_labelInfo.TryGetValue(node, out result)) {
- _labelInfo.Add(node, result = new LabelInfo(_ilg, node, false));
- }
- return result;
- }
-
- private LabelInfo ReferenceLabel(LabelTarget node) {
- LabelInfo result = EnsureLabel(node);
- result.Reference(_labelBlock);
- return result;
- }
-
- private LabelInfo DefineLabel(LabelTarget node) {
- if (node == null) {
- return new LabelInfo(_ilg, null, false);
- }
- LabelInfo result = EnsureLabel(node);
- result.Define(_labelBlock);
- return result;
- }
-
- private void PushLabelBlock(LabelScopeKind type) {
- _labelBlock = new LabelScopeInfo(_labelBlock, type);
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")]
- private void PopLabelBlock(LabelScopeKind kind) {
- Debug.Assert(_labelBlock != null && _labelBlock.Kind == kind);
- _labelBlock = _labelBlock.Parent;
- }
-
- private void EmitLabelExpression(Expression expr, CompilationFlags flags) {
- var node = (LabelExpression)expr;
- Debug.Assert(node.Target != null);
-
- // If we're an immediate child of a block, our label will already
- // be defined. If not, we need to define our own block so this
- // label isn't exposed except to its own child expression.
- LabelInfo label = null;
-
- if (_labelBlock.Kind == LabelScopeKind.Block) {
- _labelBlock.TryGetLabelInfo(node.Target, out label);
-
- // We're in a block but didn't find our label, try switch
- if (label == null && _labelBlock.Parent.Kind == LabelScopeKind.Switch) {
- _labelBlock.Parent.TryGetLabelInfo(node.Target, out label);
- }
-
- // if we're in a switch or block, we should've found the label
- Debug.Assert(label != null);
- }
-
- if (label == null) {
- label = DefineLabel(node.Target);
- }
-
- if (node.DefaultValue != null) {
- if (node.Target.Type == typeof(void)) {
- EmitExpressionAsVoid(node.DefaultValue, flags);
- } else {
- flags = UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart);
- EmitExpression(node.DefaultValue, flags);
- }
- }
-
- label.Mark();
- }
-
- private void EmitGotoExpression(Expression expr, CompilationFlags flags) {
- var node = (GotoExpression)expr;
- var labelInfo = ReferenceLabel(node.Target);
-
- var tailCall = flags & CompilationFlags.EmitAsTailCallMask;
- if (tailCall != CompilationFlags.EmitAsNoTail) {
- // Since tail call flags are not passed into EmitTryExpression, CanReturn
- // means the goto will be emitted as Ret. Therefore we can emit the goto's
- // default value with tail call. This can be improved by detecting if the
- // target label is equivalent to the return label.
- tailCall = labelInfo.CanReturn ? CompilationFlags.EmitAsTail : CompilationFlags.EmitAsNoTail;
- flags = UpdateEmitAsTailCallFlag(flags, tailCall);
- }
-
- if (node.Value != null) {
- if (node.Target.Type == typeof(void)) {
- EmitExpressionAsVoid(node.Value, flags);
- } else {
- flags = UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart);
- EmitExpression(node.Value, flags);
- }
- }
-
- labelInfo.EmitJump();
-
- EmitUnreachable(node, flags);
- }
-
- // We need to push default(T), unless we're emitting ourselves as
- // void. Even though the code is unreachable, we still have to
- // generate correct IL. We can get rid of this once we have better
- // reachability analysis.
- private void EmitUnreachable(Expression node, CompilationFlags flags) {
- if (node.Type != typeof(void) && (flags & CompilationFlags.EmitAsVoidType) == 0) {
- _ilg.EmitDefault(node.Type);
- }
- }
-
- private bool TryPushLabelBlock(Expression node) {
- // Anything that is "statement-like" -- e.g. has no associated
- // stack state can be jumped into, with the exception of try-blocks
- // We indicate this by a "Block"
- //
- // Otherwise, we push an "Expression" to indicate that it can't be
- // jumped into
- switch (node.NodeType) {
- default:
- if (_labelBlock.Kind != LabelScopeKind.Expression) {
- PushLabelBlock(LabelScopeKind.Expression);
- return true;
- }
- return false;
- case ExpressionType.Label:
- // LabelExpression is a bit special, if it's directly in a
- // block it becomes associate with the block's scope. Same
- // thing if it's in a switch case body.
- if (_labelBlock.Kind == LabelScopeKind.Block) {
- var label = ((LabelExpression)node).Target;
- if (_labelBlock.ContainsTarget(label)) {
- return false;
- }
- if (_labelBlock.Parent.Kind == LabelScopeKind.Switch &&
- _labelBlock.Parent.ContainsTarget(label)) {
- return false;
- }
- }
- PushLabelBlock(LabelScopeKind.Statement);
- return true;
- case ExpressionType.Block:
- if (node is SpilledExpressionBlock) {
- // treat it as an expression
- goto default;
- }
-
- PushLabelBlock(LabelScopeKind.Block);
- // Labels defined immediately in the block are valid for
- // the whole block.
- if (_labelBlock.Parent.Kind != LabelScopeKind.Switch) {
- DefineBlockLabels(node);
- }
- return true;
- case ExpressionType.Switch:
- PushLabelBlock(LabelScopeKind.Switch);
- // Define labels inside of the switch cases so theyare in
- // scope for the whole switch. This allows "goto case" and
- // "goto default" to be considered as local jumps.
- var @switch = (SwitchExpression)node;
- foreach (SwitchCase c in @switch.Cases) {
- DefineBlockLabels(c.Body);
- }
- DefineBlockLabels(@switch.DefaultBody);
- return true;
-
- // Remove this when Convert(Void) goes away.
- case ExpressionType.Convert:
- if (node.Type != typeof(void)) {
- // treat it as an expression
- goto default;
- }
- PushLabelBlock(LabelScopeKind.Statement);
- return true;
-
- case ExpressionType.Conditional:
- case ExpressionType.Loop:
- case ExpressionType.Goto:
- PushLabelBlock(LabelScopeKind.Statement);
- return true;
- }
- }
-
- private void DefineBlockLabels(Expression node) {
- var block = node as BlockExpression;
- if (block == null || block is SpilledExpressionBlock) {
- return;
- }
- for (int i = 0, n = block.ExpressionCount; i < n; i++) {
- Expression e = block.GetExpression(i);
-
- var label = e as LabelExpression;
- if (label != null) {
- DefineLabel(label.Target);
- }
- }
- }
-
- // See if this lambda has a return label
- // If so, we'll create it now and mark it as allowing the "ret" opcode
- // This allows us to generate better IL
- private void AddReturnLabel(LambdaExpression lambda) {
- var expression = lambda.Body;
-
- while (true) {
- switch (expression.NodeType) {
- default:
- // Didn't find return label
- return;
- case ExpressionType.Label:
- // Found the label. We can directly return from this place
- // only if the label type is reference assignable to the lambda return type.
- var label = ((LabelExpression)expression).Target;
- _labelInfo.Add(label, new LabelInfo(_ilg, label, TypeUtils.AreReferenceAssignable(lambda.ReturnType, label.Type)));
- return;
- case ExpressionType.Block:
- // Look in the last significant expression of a block
- var body = (BlockExpression)expression;
- // omit empty and debuginfo at the end of the block since they
- // are not going to emit any IL
- for (int i = body.ExpressionCount - 1; i >= 0; i--) {
- expression = body.GetExpression(i);
- if (Significant(expression)) {
- break;
- }
- }
- continue;
- }
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Expressions.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Expressions.cs
deleted file mode 100644
index 10abcd4ef62..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Expressions.cs
+++ /dev/null
@@ -1,1085 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Reflection.Emit;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- partial class LambdaCompiler {
- [Flags]
- internal enum CompilationFlags {
- EmitExpressionStart = 0x0001,
- EmitNoExpressionStart = 0x0002,
- EmitAsDefaultType = 0x0010,
- EmitAsVoidType = 0x0020,
- EmitAsTail = 0x0100, // at the tail position of a lambda, tail call can be safely emitted
- EmitAsMiddle = 0x0200, // in the middle of a lambda, tail call can be emitted if it is in a return
- EmitAsNoTail = 0x0400, // neither at the tail or in a return, or tail call is not turned on, no tail call is emitted
-
- EmitExpressionStartMask = 0x000f,
- EmitAsTypeMask = 0x00f0,
- EmitAsTailCallMask = 0x0f00
- }
-
- /// <summary>
- /// Update the flag with a new EmitAsTailCall flag
- /// </summary>
- private static CompilationFlags UpdateEmitAsTailCallFlag(CompilationFlags flags, CompilationFlags newValue) {
- Debug.Assert(newValue == CompilationFlags.EmitAsTail || newValue == CompilationFlags.EmitAsMiddle || newValue == CompilationFlags.EmitAsNoTail);
- var oldValue = flags & CompilationFlags.EmitAsTailCallMask;
- return flags ^ oldValue | newValue;
- }
-
- /// <summary>
- /// Update the flag with a new EmitExpressionStart flag
- /// </summary>
- private static CompilationFlags UpdateEmitExpressionStartFlag(CompilationFlags flags, CompilationFlags newValue) {
- Debug.Assert(newValue == CompilationFlags.EmitExpressionStart || newValue == CompilationFlags.EmitNoExpressionStart);
- var oldValue = flags & CompilationFlags.EmitExpressionStartMask;
- return flags ^ oldValue | newValue;
- }
-
- /// <summary>
- /// Update the flag with a new EmitAsType flag
- /// </summary>
- private static CompilationFlags UpdateEmitAsTypeFlag(CompilationFlags flags, CompilationFlags newValue) {
- Debug.Assert(newValue == CompilationFlags.EmitAsDefaultType || newValue == CompilationFlags.EmitAsVoidType);
- var oldValue = flags & CompilationFlags.EmitAsTypeMask;
- return flags ^ oldValue | newValue;
- }
-
- /// <summary>
- /// Generates code for this expression in a value position.
- /// This method will leave the value of the expression
- /// on the top of the stack typed as Type.
- /// </summary>
- internal void EmitExpression(Expression node) {
- EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitExpressionStart);
- }
-
- /// <summary>
- /// Emits an expression and discards the result. For some nodes this emits
- /// more optimial code then EmitExpression/Pop
- /// </summary>
- private void EmitExpressionAsVoid(Expression node) {
- EmitExpressionAsVoid(node, CompilationFlags.EmitAsNoTail);
- }
-
- private void EmitExpressionAsVoid(Expression node, CompilationFlags flags) {
- Debug.Assert(node != null);
-
- CompilationFlags startEmitted = EmitExpressionStart(node);
-
- switch (node.NodeType) {
- case ExpressionType.Assign:
- EmitAssign((BinaryExpression)node, CompilationFlags.EmitAsVoidType);
- break;
- case ExpressionType.Block:
- Emit((BlockExpression)node, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsVoidType));
- break;
- case ExpressionType.Throw:
- EmitThrow((UnaryExpression)node, CompilationFlags.EmitAsVoidType);
- break;
- case ExpressionType.Goto:
- EmitGotoExpression(node, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsVoidType));
- break;
- case ExpressionType.Constant:
- case ExpressionType.Default:
- case ExpressionType.Parameter:
- // no-op
- break;
- default:
- if (node.Type == typeof(void)) {
- EmitExpression(node, UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitNoExpressionStart));
- } else {
- EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart);
- _ilg.Emit(OpCodes.Pop);
- }
- break;
- }
- EmitExpressionEnd(startEmitted);
- }
-
- private void EmitExpressionAsType(Expression node, Type type, CompilationFlags flags) {
-
- if (type == typeof(void)) {
- EmitExpressionAsVoid(node, flags);
- } else {
- // if the node is emitted as a different type, CastClass IL is emitted at the end,
- // should not emit with tail calls.
- if (!TypeUtils.AreEquivalent(node.Type, type)) {
- EmitExpression(node);
- Debug.Assert(TypeUtils.AreReferenceAssignable(type, node.Type));
- _ilg.Emit(OpCodes.Castclass, type);
- } else {
- // emit the with the flags and emit emit expression start
- EmitExpression(node, UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart));
- }
- }
- }
-
- #region label block tracking
-
- private CompilationFlags EmitExpressionStart(Expression node) {
- if (TryPushLabelBlock(node)) {
- return CompilationFlags.EmitExpressionStart;
- }
- return CompilationFlags.EmitNoExpressionStart;
- }
-
- private void EmitExpressionEnd(CompilationFlags flags) {
- if ((flags & CompilationFlags.EmitExpressionStartMask) == CompilationFlags.EmitExpressionStart) {
- PopLabelBlock(_labelBlock.Kind);
- }
- }
-
- #endregion
-
- #region InvocationExpression
-
- private void EmitInvocationExpression(Expression expr, CompilationFlags flags) {
- InvocationExpression node = (InvocationExpression)expr;
-
- // Optimization: inline code for literal lambda's directly
- //
- // This is worth it because otherwise we end up with a extra call
- // to DynamicMethod.CreateDelegate, which is expensive.
- //
- if (node.LambdaOperand != null) {
- EmitInlinedInvoke(node, flags);
- return;
- }
-
- expr = node.Expression;
- if (typeof(LambdaExpression).IsAssignableFrom(expr.Type)) {
- // if the invoke target is a lambda expression tree, first compile it into a delegate
- expr = Expression.Call(expr, expr.Type.GetMethod("Compile", new Type[0]));
- }
- expr = Expression.Call(expr, expr.Type.GetMethod("Invoke"), node.Arguments);
-
- EmitExpression(expr);
- }
-
- private void EmitInlinedInvoke(InvocationExpression invoke, CompilationFlags flags) {
- var lambda = invoke.LambdaOperand;
-
- // This is tricky: we need to emit the arguments outside of the
- // scope, but set them inside the scope. Fortunately, using the IL
- // stack it is entirely doable.
-
- // 1. Emit invoke arguments
- List<WriteBack> wb = EmitArguments(lambda.Type.GetMethod("Invoke"), invoke);
-
- // 2. Create the nested LambdaCompiler
- var inner = new LambdaCompiler(this, lambda);
-
- // 3. Emit the body
- // if the inlined lambda is the last expression of the whole lambda,
- // tail call can be applied.
- if (wb.Count != 0) {
- flags = UpdateEmitAsTailCallFlag(flags, CompilationFlags.EmitAsNoTail);
- }
- inner.EmitLambdaBody(_scope, true, flags);
-
- // 4. Emit writebacks if needed
- EmitWriteBack(wb);
- }
-
- #endregion
-
- #region IndexExpression
-
- private void EmitIndexExpression(Expression expr) {
- var node = (IndexExpression)expr;
-
- // Emit instance, if calling an instance method
- Type objectType = null;
- if (node.Object != null) {
- EmitInstance(node.Object, objectType = node.Object.Type);
- }
-
- // Emit indexes. We don't allow byref args, so no need to worry
- // about writebacks or EmitAddress
- foreach (var arg in node.Arguments) {
- EmitExpression(arg);
- }
-
- EmitGetIndexCall(node, objectType);
- }
-
- private void EmitIndexAssignment(BinaryExpression node, CompilationFlags flags) {
- var index = (IndexExpression)node.Left;
-
- var emitAs = flags & CompilationFlags.EmitAsTypeMask;
-
- // Emit instance, if calling an instance method
- Type objectType = null;
- if (index.Object != null) {
- EmitInstance(index.Object, objectType = index.Object.Type);
- }
-
- // Emit indexes. We don't allow byref args, so no need to worry
- // about writebacks or EmitAddress
- foreach (var arg in index.Arguments) {
- EmitExpression(arg);
- }
-
- // Emit value
- EmitExpression(node.Right);
-
- // Save the expression value, if needed
- LocalBuilder temp = null;
- if (emitAs != CompilationFlags.EmitAsVoidType) {
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Stloc, temp = GetLocal(node.Type));
- }
-
- EmitSetIndexCall(index, objectType);
-
- // Restore the value
- if (emitAs != CompilationFlags.EmitAsVoidType) {
- _ilg.Emit(OpCodes.Ldloc, temp);
- FreeLocal(temp);
- }
- }
-
- private void EmitGetIndexCall(IndexExpression node, Type objectType) {
- if (node.Indexer != null) {
- // For indexed properties, just call the getter
- var method = node.Indexer.GetGetMethod(true);
- EmitCall(objectType, method);
- } else if (node.Arguments.Count != 1) {
- // Multidimensional arrays, call get
- _ilg.Emit(OpCodes.Call, node.Object.Type.GetMethod("Get", BindingFlags.Public | BindingFlags.Instance));
- } else {
- // For one dimensional arrays, emit load
- _ilg.EmitLoadElement(node.Type);
- }
- }
-
- private void EmitSetIndexCall(IndexExpression node, Type objectType) {
- if (node.Indexer != null) {
- // For indexed properties, just call the setter
- var method = node.Indexer.GetSetMethod(true);
- EmitCall(objectType, method);
- } else if (node.Arguments.Count != 1) {
- // Multidimensional arrays, call set
- _ilg.Emit(OpCodes.Call, node.Object.Type.GetMethod("Set", BindingFlags.Public | BindingFlags.Instance));
- } else {
- // For one dimensional arrays, emit store
- _ilg.EmitStoreElement(node.Type);
- }
- }
-
- #endregion
-
- #region MethodCallExpression
-
- private void EmitMethodCallExpression(Expression expr, CompilationFlags flags) {
- MethodCallExpression node = (MethodCallExpression)expr;
-
- EmitMethodCall(node.Object, node.Method, node, flags);
- }
-
- private void EmitMethodCallExpression(Expression expr) {
- EmitMethodCallExpression(expr, CompilationFlags.EmitAsNoTail);
- }
-
- private void EmitMethodCall(Expression obj, MethodInfo method, IArgumentProvider methodCallExpr) {
- EmitMethodCall(obj, method, methodCallExpr, CompilationFlags.EmitAsNoTail);
- }
-
- private void EmitMethodCall(Expression obj, MethodInfo method, IArgumentProvider methodCallExpr, CompilationFlags flags) {
- // Emit instance, if calling an instance method
- Type objectType = null;
- if (!method.IsStatic) {
- EmitInstance(obj, objectType = obj.Type);
- }
- // if the obj has a value type, its address is passed to the method call so we cannot destroy the
- // stack by emitting a tail call
- if (obj != null && obj.Type.IsValueType) {
- EmitMethodCall(method, methodCallExpr, objectType);
- } else {
- EmitMethodCall(method, methodCallExpr, objectType, flags);
- }
- }
-
- // assumes 'object' of non-static call is already on stack
- private void EmitMethodCall(MethodInfo mi, IArgumentProvider args, Type objectType) {
- EmitMethodCall(mi, args, objectType, CompilationFlags.EmitAsNoTail);
- }
-
- // assumes 'object' of non-static call is already on stack
- private void EmitMethodCall(MethodInfo mi, IArgumentProvider args, Type objectType, CompilationFlags flags) {
-
- // Emit arguments
- List<WriteBack> wb = EmitArguments(mi, args);
-
- // Emit the actual call
- OpCode callOp = UseVirtual(mi) ? OpCodes.Callvirt : OpCodes.Call;
- if (callOp == OpCodes.Callvirt && objectType.IsValueType) {
- // This automatically boxes value types if necessary.
- _ilg.Emit(OpCodes.Constrained, objectType);
- }
- // The method call can be a tail call if
- // 1) the method call is the last instruction before Ret
- // 2) the method does not have any ByRef parameters, refer to ECMA-335 Partition III Section 2.4.
- // "Verification requires that no managed pointers are passed to the method being called, since
- // it does not track pointers into the current frame."
- if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail && !MethodHasByRefParameter(mi)) {
- _ilg.Emit(OpCodes.Tailcall);
- }
- if (mi.CallingConvention == CallingConventions.VarArgs) {
- _ilg.EmitCall(callOp, mi, args.Map(a => a.Type));
- } else {
- _ilg.Emit(callOp, mi);
- }
-
- // Emit writebacks for properties passed as "ref" arguments
- EmitWriteBack(wb);
- }
-
- private static bool MethodHasByRefParameter(MethodInfo mi) {
- foreach (var pi in mi.GetParametersCached()) {
- if (pi.IsByRefParameter()) {
- return true;
- }
- }
- return false;
- }
-
- private void EmitCall(Type objectType, MethodInfo method) {
- if (method.CallingConvention == CallingConventions.VarArgs) {
- throw Error.UnexpectedVarArgsCall(method);
- }
-
- OpCode callOp = UseVirtual(method) ? OpCodes.Callvirt : OpCodes.Call;
- if (callOp == OpCodes.Callvirt && objectType.IsValueType) {
- _ilg.Emit(OpCodes.Constrained, objectType);
- }
- _ilg.Emit(callOp, method);
- }
-
- private static bool UseVirtual(MethodInfo mi) {
- // There are two factors: is the method static, virtual or non-virtual instance?
- // And is the object ref or value?
- // The cases are:
- //
- // static, ref: call
- // static, value: call
- // virtual, ref: callvirt
- // virtual, value: call -- eg, double.ToString must be a non-virtual call to be verifiable.
- // instance, ref: callvirt -- this looks wrong, but is verifiable and gives us a free null check.
- // instance, value: call
- //
- // We never need to generate a nonvirtual call to a virtual method on a reference type because
- // expression trees do not support "base.Foo()" style calling.
- //
- // We could do an optimization here for the case where we know that the object is a non-null
- // reference type and the method is a non-virtual instance method. For example, if we had
- // (new Foo()).Bar() for instance method Bar we don't need the null check so we could do a
- // call rather than a callvirt. However that seems like it would not be a very big win for
- // most dynamically generated code scenarios, so let's not do that for now.
-
- if (mi.IsStatic) {
- return false;
- }
- if (mi.DeclaringType.IsValueType) {
- return false;
- }
- return true;
- }
-
- /// <summary>
- /// Emits arguments to a call, and returns an array of writebacks that
- /// should happen after the call.
- /// </summary>
- private List<WriteBack> EmitArguments(MethodBase method, IArgumentProvider args) {
- return EmitArguments(method, args, 0);
- }
-
- /// <summary>
- /// Emits arguments to a call, and returns an array of writebacks that
- /// should happen after the call. For emitting dynamic expressions, we
- /// need to skip the first parameter of the method (the call site).
- /// </summary>
- private List<WriteBack> EmitArguments(MethodBase method, IArgumentProvider args, int skipParameters) {
- ParameterInfo[] pis = method.GetParametersCached();
- Debug.Assert(args.ArgumentCount + skipParameters == pis.Length);
-
- var writeBacks = new List<WriteBack>();
- for (int i = skipParameters, n = pis.Length; i < n; i++) {
- ParameterInfo parameter = pis[i];
- Expression argument = args.GetArgument(i - skipParameters);
- Type type = parameter.ParameterType;
-
- if (type.IsByRef) {
- type = type.GetElementType();
-
- WriteBack wb = EmitAddressWriteBack(argument, type);
- if (wb != null) {
- writeBacks.Add(wb);
- }
- } else {
- EmitExpression(argument);
- }
- }
- return writeBacks;
- }
-
- private static void EmitWriteBack(IList<WriteBack> writeBacks) {
- foreach (WriteBack wb in writeBacks) {
- wb();
- }
- }
-
- #endregion
-
- private void EmitConstantExpression(Expression expr) {
- ConstantExpression node = (ConstantExpression)expr;
-
- EmitConstant(node.Value, node.Type);
- }
-
- private void EmitConstant(object value, Type type) {
- // Try to emit the constant directly into IL
- if (ILGen.CanEmitConstant(value, type)) {
- _ilg.EmitConstant(value, type);
- return;
- }
-
- _boundConstants.EmitConstant(this, value, type);
- }
-
- private void EmitDynamicExpression(Expression expr) {
- if (!(_method is DynamicMethod)) {
- throw Error.CannotCompileDynamic();
- }
-
- var node = (DynamicExpression)expr;
-
- var site = CallSite.Create(node.DelegateType, node.Binder);
- Type siteType = site.GetType();
-
- var invoke = node.DelegateType.GetMethod("Invoke");
-
- // site.Target.Invoke(site, args)
- EmitConstant(site, siteType);
-
- // Emit the temp as type CallSite so we get more reuse
- _ilg.Emit(OpCodes.Dup);
-#if !FEATURE_CORE_DLR
- // For 3.5, emit the temp as CallSite<T> to work around a Jit32
- // verifier issue (fixed in 3.5 sp1)
- var siteTemp = GetLocal(siteType);
-#else
- var siteTemp = GetLocal(typeof(CallSite));
-#endif
- _ilg.Emit(OpCodes.Stloc, siteTemp);
- _ilg.Emit(OpCodes.Ldfld, siteType.GetField("Target"));
- _ilg.Emit(OpCodes.Ldloc, siteTemp);
- FreeLocal(siteTemp);
-
- List<WriteBack> wb = EmitArguments(invoke, node, 1);
- _ilg.Emit(OpCodes.Callvirt, invoke);
- EmitWriteBack(wb);
- }
-
- private void EmitNewExpression(Expression expr) {
- NewExpression node = (NewExpression)expr;
-
- if (node.Constructor != null) {
- List<WriteBack> wb = EmitArguments(node.Constructor, node);
- _ilg.Emit(OpCodes.Newobj, node.Constructor);
- EmitWriteBack(wb);
- } else {
- Debug.Assert(node.Arguments.Count == 0, "Node with arguments must have a constructor.");
- Debug.Assert(node.Type.IsValueType, "Only value type may have constructor not set.");
- LocalBuilder temp = GetLocal(node.Type);
- _ilg.Emit(OpCodes.Ldloca, temp);
- _ilg.Emit(OpCodes.Initobj, node.Type);
- _ilg.Emit(OpCodes.Ldloc, temp);
- FreeLocal(temp);
- }
- }
-
- private void EmitTypeBinaryExpression(Expression expr) {
- TypeBinaryExpression node = (TypeBinaryExpression)expr;
-
- if (node.NodeType == ExpressionType.TypeEqual) {
- EmitExpression(node.ReduceTypeEqual());
- return;
- }
-
- Type type = node.Expression.Type;
-
- // Try to determine the result statically
- AnalyzeTypeIsResult result = ConstantCheck.AnalyzeTypeIs(node);
-
- if (result == AnalyzeTypeIsResult.KnownTrue ||
- result == AnalyzeTypeIsResult.KnownFalse) {
- // Result is known statically, so just emit the expression for
- // its side effects and return the result
- EmitExpressionAsVoid(node.Expression);
- _ilg.EmitBoolean(result == AnalyzeTypeIsResult.KnownTrue);
- return;
- }
-
- if (result == AnalyzeTypeIsResult.KnownAssignable) {
- // We know the type can be assigned, but still need to check
- // for null at runtime
- if (type.IsNullableType()) {
- EmitAddress(node.Expression, type);
- _ilg.EmitHasValue(type);
- return;
- }
-
- Debug.Assert(!type.IsValueType);
- EmitExpression(node.Expression);
- _ilg.Emit(OpCodes.Ldnull);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- return;
- }
-
- Debug.Assert(result == AnalyzeTypeIsResult.Unknown);
-
- // Emit a full runtime "isinst" check
- EmitExpression(node.Expression);
- if (type.IsValueType) {
- _ilg.Emit(OpCodes.Box, type);
- }
- _ilg.Emit(OpCodes.Isinst, node.TypeOperand);
- _ilg.Emit(OpCodes.Ldnull);
- _ilg.Emit(OpCodes.Cgt_Un);
- }
-
- private void EmitVariableAssignment(BinaryExpression node, CompilationFlags flags) {
- var variable = (ParameterExpression)node.Left;
- var emitAs = flags & CompilationFlags.EmitAsTypeMask;
-
- EmitExpression(node.Right);
- if (emitAs != CompilationFlags.EmitAsVoidType) {
- _ilg.Emit(OpCodes.Dup);
- }
-
- if (variable.IsByRef) {
- // Note: the stloc/ldloc pattern is a bit suboptimal, but it
- // saves us from having to spill stack when assigning to a
- // byref parameter. We already make this same tradeoff for
- // hoisted variables, see ElementStorage.EmitStore
-
- LocalBuilder value = GetLocal(variable.Type);
- _ilg.Emit(OpCodes.Stloc, value);
- _scope.EmitGet(variable);
- _ilg.Emit(OpCodes.Ldloc, value);
- FreeLocal(value);
- _ilg.EmitStoreValueIndirect(variable.Type);
- } else {
- _scope.EmitSet(variable);
- }
- }
-
- private void EmitAssignBinaryExpression(Expression expr) {
- EmitAssign((BinaryExpression)expr, CompilationFlags.EmitAsDefaultType);
- }
-
- private void EmitAssign(BinaryExpression node, CompilationFlags emitAs) {
- switch (node.Left.NodeType) {
- case ExpressionType.Index:
- EmitIndexAssignment(node, emitAs);
- return;
- case ExpressionType.MemberAccess:
- EmitMemberAssignment(node, emitAs);
- return;
- case ExpressionType.Parameter:
- EmitVariableAssignment(node, emitAs);
- return;
- default:
- throw Error.InvalidLvalue(node.Left.NodeType);
- }
- }
-
- private void EmitParameterExpression(Expression expr) {
- ParameterExpression node = (ParameterExpression)expr;
- _scope.EmitGet(node);
- if (node.IsByRef) {
- _ilg.EmitLoadValueIndirect(node.Type);
- }
- }
-
- private void EmitLambdaExpression(Expression expr) {
- LambdaExpression node = (LambdaExpression)expr;
- EmitDelegateConstruction(node);
- }
-
- private void EmitRuntimeVariablesExpression(Expression expr) {
- RuntimeVariablesExpression node = (RuntimeVariablesExpression)expr;
- _scope.EmitVariableAccess(this, node.Variables);
- }
-
- private void EmitMemberAssignment(BinaryExpression node, CompilationFlags flags) {
- MemberExpression lvalue = (MemberExpression)node.Left;
- MemberInfo member = lvalue.Member;
-
- // emit "this", if any
- Type objectType = null;
- if (lvalue.Expression != null) {
- EmitInstance(lvalue.Expression, objectType = lvalue.Expression.Type);
- }
-
- // emit value
- EmitExpression(node.Right);
-
- LocalBuilder temp = null;
- var emitAs = flags & CompilationFlags.EmitAsTypeMask;
- if (emitAs != CompilationFlags.EmitAsVoidType) {
- // save the value so we can return it
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Stloc, temp = GetLocal(node.Type));
- }
-
- switch (member.MemberType) {
- case MemberTypes.Field:
- _ilg.EmitFieldSet((FieldInfo)member);
- break;
- case MemberTypes.Property:
- EmitCall(objectType, ((PropertyInfo)member).GetSetMethod(true));
- break;
- default:
- throw Error.InvalidMemberType(member.MemberType);
- }
-
- if (emitAs != CompilationFlags.EmitAsVoidType) {
- _ilg.Emit(OpCodes.Ldloc, temp);
- FreeLocal(temp);
- }
- }
-
- private void EmitMemberExpression(Expression expr) {
- MemberExpression node = (MemberExpression)expr;
-
- // emit "this", if any
- Type instanceType = null;
- if (node.Expression != null) {
- EmitInstance(node.Expression, instanceType = node.Expression.Type);
- }
-
- EmitMemberGet(node.Member, instanceType);
- }
-
- // assumes instance is already on the stack
- private void EmitMemberGet(MemberInfo member, Type objectType) {
- switch (member.MemberType) {
- case MemberTypes.Field:
- FieldInfo fi = (FieldInfo)member;
- if (fi.IsLiteral) {
- EmitConstant(fi.GetRawConstantValue(), fi.FieldType);
- } else {
- _ilg.EmitFieldGet(fi);
- }
- break;
- case MemberTypes.Property:
- EmitCall(objectType, ((PropertyInfo)member).GetGetMethod(true));
- break;
- default:
- throw ContractUtils.Unreachable;
- }
- }
-
- private void EmitInstance(Expression instance, Type type) {
- if (instance != null) {
- if (type.IsValueType) {
- EmitAddress(instance, type);
- } else {
- EmitExpression(instance);
- }
- }
- }
-
- private void EmitNewArrayExpression(Expression expr) {
- NewArrayExpression node = (NewArrayExpression)expr;
-
- if (node.NodeType == ExpressionType.NewArrayInit) {
- _ilg.EmitArray(
- node.Type.GetElementType(),
- node.Expressions.Count,
- delegate(int index) {
- EmitExpression(node.Expressions[index]);
- }
- );
- } else {
- ReadOnlyCollection<Expression> bounds = node.Expressions;
- for (int i = 0; i < bounds.Count; i++) {
- Expression x = bounds[i];
- EmitExpression(x);
- _ilg.EmitConvertToType(x.Type, typeof(int), true);
- }
- _ilg.EmitArray(node.Type);
- }
- }
-
- private void EmitDebugInfoExpression(Expression expr) {
- if (!EmitDebugSymbols) {
- return;
- }
- var node = (DebugInfoExpression)expr;
-
- if (node.IsClear && _sequencePointCleared) {
- // Emitting another clearance after one clearance does not
- // have any effect, so we can save it.
- return;
- }
-
- _tree.DebugInfoGenerator.MarkSequencePoint(_lambda, _method, _ilg, node);
- _ilg.Emit(OpCodes.Nop);
- _sequencePointCleared = node.IsClear;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")]
- private static void EmitExtensionExpression(Expression expr) {
- throw Error.ExtensionNotReduced();
- }
-
- #region ListInit, MemberInit
-
- private void EmitListInitExpression(Expression expr) {
- EmitListInit((ListInitExpression)expr);
- }
-
- private void EmitMemberInitExpression(Expression expr) {
- EmitMemberInit((MemberInitExpression)expr);
- }
-
- private void EmitBinding(MemberBinding binding, Type objectType) {
- switch (binding.BindingType) {
- case MemberBindingType.Assignment:
- EmitMemberAssignment((MemberAssignment)binding, objectType);
- break;
- case MemberBindingType.ListBinding:
- EmitMemberListBinding((MemberListBinding)binding);
- break;
- case MemberBindingType.MemberBinding:
- EmitMemberMemberBinding((MemberMemberBinding)binding);
- break;
- default:
- throw Error.UnknownBindingType();
- }
- }
-
- private void EmitMemberAssignment(MemberAssignment binding, Type objectType) {
- EmitExpression(binding.Expression);
- FieldInfo fi = binding.Member as FieldInfo;
- if (fi != null) {
- _ilg.Emit(OpCodes.Stfld, fi);
- } else {
- PropertyInfo pi = binding.Member as PropertyInfo;
- if (pi != null) {
- EmitCall(objectType, pi.GetSetMethod(true));
- } else {
- throw Error.UnhandledBinding();
- }
- }
- }
-
- private void EmitMemberMemberBinding(MemberMemberBinding binding) {
- Type type = GetMemberType(binding.Member);
- if (binding.Member is PropertyInfo && type.IsValueType) {
- throw Error.CannotAutoInitializeValueTypeMemberThroughProperty(binding.Member);
- }
- if (type.IsValueType) {
- EmitMemberAddress(binding.Member, binding.Member.DeclaringType);
- } else {
- EmitMemberGet(binding.Member, binding.Member.DeclaringType);
- }
- EmitMemberInit(binding.Bindings, false, type);
- }
-
- private void EmitMemberListBinding(MemberListBinding binding) {
- Type type = GetMemberType(binding.Member);
- if (binding.Member is PropertyInfo && type.IsValueType) {
- throw Error.CannotAutoInitializeValueTypeElementThroughProperty(binding.Member);
- }
- if (type.IsValueType) {
- EmitMemberAddress(binding.Member, binding.Member.DeclaringType);
- } else {
- EmitMemberGet(binding.Member, binding.Member.DeclaringType);
- }
- EmitListInit(binding.Initializers, false, type);
- }
-
- private void EmitMemberInit(MemberInitExpression init) {
- EmitExpression(init.NewExpression);
- LocalBuilder loc = null;
- if (init.NewExpression.Type.IsValueType && init.Bindings.Count > 0) {
- loc = _ilg.DeclareLocal(init.NewExpression.Type);
- _ilg.Emit(OpCodes.Stloc, loc);
- _ilg.Emit(OpCodes.Ldloca, loc);
- }
- EmitMemberInit(init.Bindings, loc == null, init.NewExpression.Type);
- if (loc != null) {
- _ilg.Emit(OpCodes.Ldloc, loc);
- }
- }
-
- // This method assumes that the instance is on the stack and is expected, based on "keepOnStack" flag
- // to either leave the instance on the stack, or pop it.
- private void EmitMemberInit(ReadOnlyCollection<MemberBinding> bindings, bool keepOnStack, Type objectType) {
- int n = bindings.Count;
- if (n == 0) {
- // If there are no initializers and instance is not to be kept on the stack, we must pop explicitly.
- if (!keepOnStack) {
- _ilg.Emit(OpCodes.Pop);
- }
- } else {
- for (int i = 0; i < n; i++) {
- if (keepOnStack || i < n - 1) {
- _ilg.Emit(OpCodes.Dup);
- }
- EmitBinding(bindings[i], objectType);
- }
- }
- }
-
- private void EmitListInit(ListInitExpression init) {
- EmitExpression(init.NewExpression);
- LocalBuilder loc = null;
- if (init.NewExpression.Type.IsValueType) {
- loc = _ilg.DeclareLocal(init.NewExpression.Type);
- _ilg.Emit(OpCodes.Stloc, loc);
- _ilg.Emit(OpCodes.Ldloca, loc);
- }
- EmitListInit(init.Initializers, loc == null, init.NewExpression.Type);
- if (loc != null) {
- _ilg.Emit(OpCodes.Ldloc, loc);
- }
- }
-
- // This method assumes that the list instance is on the stack and is expected, based on "keepOnStack" flag
- // to either leave the list instance on the stack, or pop it.
- private void EmitListInit(ReadOnlyCollection<ElementInit> initializers, bool keepOnStack, Type objectType) {
- int n = initializers.Count;
-
- if (n == 0) {
- // If there are no initializers and instance is not to be kept on the stack, we must pop explicitly.
- if (!keepOnStack) {
- _ilg.Emit(OpCodes.Pop);
- }
- } else {
- for (int i = 0; i < n; i++) {
- if (keepOnStack || i < n - 1) {
- _ilg.Emit(OpCodes.Dup);
- }
- EmitMethodCall(initializers[i].AddMethod, initializers[i], objectType);
-
- // Aome add methods, ArrayList.Add for example, return non-void
- if (initializers[i].AddMethod.ReturnType != typeof(void)) {
- _ilg.Emit(OpCodes.Pop);
- }
- }
- }
- }
-
- private static Type GetMemberType(MemberInfo member) {
- FieldInfo fi = member as FieldInfo;
- if (fi != null) return fi.FieldType;
- PropertyInfo pi = member as PropertyInfo;
- if (pi != null) return pi.PropertyType;
- throw Error.MemberNotFieldOrProperty(member);
- }
-
- #endregion
-
- #region Expression helpers
-
- internal static void ValidateLift(IList<ParameterExpression> variables, IList<Expression> arguments) {
- System.Diagnostics.Debug.Assert(variables != null);
- System.Diagnostics.Debug.Assert(arguments != null);
-
- if (variables.Count != arguments.Count) {
- throw Error.IncorrectNumberOfIndexes();
- }
- for (int i = 0, n = variables.Count; i < n; i++) {
- if (!TypeUtils.AreReferenceAssignable(variables[i].Type, TypeUtils.GetNonNullableType(arguments[i].Type))) {
- throw Error.ArgumentTypesMustMatch();
- }
- }
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- private void EmitLift(ExpressionType nodeType, Type resultType, MethodCallExpression mc, ParameterExpression[] paramList, Expression[] argList) {
- Debug.Assert(TypeUtils.AreEquivalent(TypeUtils.GetNonNullableType(resultType), TypeUtils.GetNonNullableType(mc.Type)));
-
- switch (nodeType) {
- default:
- case ExpressionType.LessThan:
- case ExpressionType.LessThanOrEqual:
- case ExpressionType.GreaterThan:
- case ExpressionType.GreaterThanOrEqual: {
- Label exit = _ilg.DefineLabel();
- Label exitNull = _ilg.DefineLabel();
- LocalBuilder anyNull = _ilg.DeclareLocal(typeof(bool));
- for (int i = 0, n = paramList.Length; i < n; i++) {
- ParameterExpression v = paramList[i];
- Expression arg = argList[i];
- if (TypeUtils.IsNullableType(arg.Type)) {
- _scope.AddLocal(this, v);
- EmitAddress(arg, arg.Type);
- _ilg.Emit(OpCodes.Dup);
- _ilg.EmitHasValue(arg.Type);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Stloc, anyNull);
- _ilg.EmitGetValueOrDefault(arg.Type);
- _scope.EmitSet(v);
- } else {
- _scope.AddLocal(this, v);
- EmitExpression(arg);
- if (!arg.Type.IsValueType) {
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Ldnull);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Stloc, anyNull);
- }
- _scope.EmitSet(v);
- }
- _ilg.Emit(OpCodes.Ldloc, anyNull);
- _ilg.Emit(OpCodes.Brtrue, exitNull);
- }
- EmitMethodCallExpression(mc);
- if (TypeUtils.IsNullableType(resultType) && !TypeUtils.AreEquivalent(resultType, mc.Type)) {
- ConstructorInfo ci = resultType.GetConstructor(new Type[] { mc.Type });
- _ilg.Emit(OpCodes.Newobj, ci);
- }
- _ilg.Emit(OpCodes.Br_S, exit);
- _ilg.MarkLabel(exitNull);
- if (TypeUtils.AreEquivalent(resultType, TypeUtils.GetNullableType(mc.Type))) {
- if (resultType.IsValueType) {
- LocalBuilder result = GetLocal(resultType);
- _ilg.Emit(OpCodes.Ldloca, result);
- _ilg.Emit(OpCodes.Initobj, resultType);
- _ilg.Emit(OpCodes.Ldloc, result);
- FreeLocal(result);
- } else {
- _ilg.Emit(OpCodes.Ldnull);
- }
- } else {
- switch (nodeType) {
- case ExpressionType.LessThan:
- case ExpressionType.LessThanOrEqual:
- case ExpressionType.GreaterThan:
- case ExpressionType.GreaterThanOrEqual:
- _ilg.Emit(OpCodes.Ldc_I4_0);
- break;
- default:
- throw Error.UnknownLiftType(nodeType);
- }
- }
- _ilg.MarkLabel(exit);
- return;
- }
- case ExpressionType.Equal:
- case ExpressionType.NotEqual: {
- if (TypeUtils.AreEquivalent(resultType, TypeUtils.GetNullableType(mc.Type))) {
- goto default;
- }
- Label exit = _ilg.DefineLabel();
- Label exitAllNull = _ilg.DefineLabel();
- Label exitAnyNull = _ilg.DefineLabel();
-
- LocalBuilder anyNull = _ilg.DeclareLocal(typeof(bool));
- LocalBuilder allNull = _ilg.DeclareLocal(typeof(bool));
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Stloc, anyNull);
- _ilg.Emit(OpCodes.Ldc_I4_1);
- _ilg.Emit(OpCodes.Stloc, allNull);
-
- for (int i = 0, n = paramList.Length; i < n; i++) {
- ParameterExpression v = paramList[i];
- Expression arg = argList[i];
- _scope.AddLocal(this, v);
- if (TypeUtils.IsNullableType(arg.Type)) {
- EmitAddress(arg, arg.Type);
- _ilg.Emit(OpCodes.Dup);
- _ilg.EmitHasValue(arg.Type);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Ldloc, anyNull);
- _ilg.Emit(OpCodes.Or);
- _ilg.Emit(OpCodes.Stloc, anyNull);
- _ilg.Emit(OpCodes.Ldloc, allNull);
- _ilg.Emit(OpCodes.And);
- _ilg.Emit(OpCodes.Stloc, allNull);
- _ilg.EmitGetValueOrDefault(arg.Type);
- } else {
- EmitExpression(arg);
- if (!arg.Type.IsValueType) {
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Ldnull);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Ldloc, anyNull);
- _ilg.Emit(OpCodes.Or);
- _ilg.Emit(OpCodes.Stloc, anyNull);
- _ilg.Emit(OpCodes.Ldloc, allNull);
- _ilg.Emit(OpCodes.And);
- _ilg.Emit(OpCodes.Stloc, allNull);
- } else {
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Stloc, allNull);
- }
- }
- _scope.EmitSet(v);
- }
- _ilg.Emit(OpCodes.Ldloc, allNull);
- _ilg.Emit(OpCodes.Brtrue, exitAllNull);
- _ilg.Emit(OpCodes.Ldloc, anyNull);
- _ilg.Emit(OpCodes.Brtrue, exitAnyNull);
-
- EmitMethodCallExpression(mc);
- if (TypeUtils.IsNullableType(resultType) && !TypeUtils.AreEquivalent(resultType, mc.Type)) {
- ConstructorInfo ci = resultType.GetConstructor(new Type[] { mc.Type });
- _ilg.Emit(OpCodes.Newobj, ci);
- }
- _ilg.Emit(OpCodes.Br_S, exit);
-
- _ilg.MarkLabel(exitAllNull);
- _ilg.EmitBoolean(nodeType == ExpressionType.Equal);
- _ilg.Emit(OpCodes.Br_S, exit);
-
- _ilg.MarkLabel(exitAnyNull);
- _ilg.EmitBoolean(nodeType == ExpressionType.NotEqual);
-
- _ilg.MarkLabel(exit);
- return;
- }
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Generated.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Generated.cs
deleted file mode 100644
index bd79a7a50de..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Generated.cs
+++ /dev/null
@@ -1,282 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- partial class LambdaCompiler {
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- private void EmitExpression(Expression node, CompilationFlags flags) {
- Debug.Assert(node != null);
-
- bool emitStart = (flags & CompilationFlags.EmitExpressionStartMask) == CompilationFlags.EmitExpressionStart;
-
- CompilationFlags startEmitted = emitStart ? EmitExpressionStart(node) : CompilationFlags.EmitNoExpressionStart;
- // only pass tail call flags to emit the expression
- flags = flags & CompilationFlags.EmitAsTailCallMask;
-
- switch (node.NodeType) {
- #region Generated Expression Compiler
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_compiler from: generate_tree.py
-
- case ExpressionType.Add:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.AddChecked:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.And:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.AndAlso:
- EmitAndAlsoBinaryExpression(node, flags);
- break;
- case ExpressionType.ArrayLength:
- EmitUnaryExpression(node, flags);
- break;
- case ExpressionType.ArrayIndex:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.Call:
- EmitMethodCallExpression(node, flags);
- break;
- case ExpressionType.Coalesce:
- EmitCoalesceBinaryExpression(node);
- break;
- case ExpressionType.Conditional:
- EmitConditionalExpression(node, flags);
- break;
- case ExpressionType.Constant:
- EmitConstantExpression(node);
- break;
- case ExpressionType.Convert:
- EmitConvertUnaryExpression(node, flags);
- break;
- case ExpressionType.ConvertChecked:
- EmitConvertUnaryExpression(node, flags);
- break;
- case ExpressionType.Divide:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.Equal:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.ExclusiveOr:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.GreaterThan:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.GreaterThanOrEqual:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.Invoke:
- EmitInvocationExpression(node, flags);
- break;
- case ExpressionType.Lambda:
- EmitLambdaExpression(node);
- break;
- case ExpressionType.LeftShift:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.LessThan:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.LessThanOrEqual:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.ListInit:
- EmitListInitExpression(node);
- break;
- case ExpressionType.MemberAccess:
- EmitMemberExpression(node);
- break;
- case ExpressionType.MemberInit:
- EmitMemberInitExpression(node);
- break;
- case ExpressionType.Modulo:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.Multiply:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.MultiplyChecked:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.Negate:
- EmitUnaryExpression(node, flags);
- break;
- case ExpressionType.UnaryPlus:
- EmitUnaryExpression(node, flags);
- break;
- case ExpressionType.NegateChecked:
- EmitUnaryExpression(node, flags);
- break;
- case ExpressionType.New:
- EmitNewExpression(node);
- break;
- case ExpressionType.NewArrayInit:
- EmitNewArrayExpression(node);
- break;
- case ExpressionType.NewArrayBounds:
- EmitNewArrayExpression(node);
- break;
- case ExpressionType.Not:
- EmitUnaryExpression(node, flags);
- break;
- case ExpressionType.NotEqual:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.Or:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.OrElse:
- EmitOrElseBinaryExpression(node, flags);
- break;
- case ExpressionType.Parameter:
- EmitParameterExpression(node);
- break;
- case ExpressionType.Power:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.Quote:
- EmitQuoteUnaryExpression(node);
- break;
- case ExpressionType.RightShift:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.Subtract:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.SubtractChecked:
- EmitBinaryExpression(node, flags);
- break;
- case ExpressionType.TypeAs:
- EmitUnaryExpression(node, flags);
- break;
- case ExpressionType.TypeIs:
- EmitTypeBinaryExpression(node);
- break;
- case ExpressionType.Assign:
- EmitAssignBinaryExpression(node);
- break;
- case ExpressionType.Block:
- EmitBlockExpression(node, flags);
- break;
- case ExpressionType.DebugInfo:
- EmitDebugInfoExpression(node);
- break;
- case ExpressionType.Decrement:
- EmitUnaryExpression(node, flags);
- break;
- case ExpressionType.Dynamic:
- EmitDynamicExpression(node);
- break;
- case ExpressionType.Default:
- EmitDefaultExpression(node);
- break;
- case ExpressionType.Extension:
- EmitExtensionExpression(node);
- break;
- case ExpressionType.Goto:
- EmitGotoExpression(node, flags);
- break;
- case ExpressionType.Increment:
- EmitUnaryExpression(node, flags);
- break;
- case ExpressionType.Index:
- EmitIndexExpression(node);
- break;
- case ExpressionType.Label:
- EmitLabelExpression(node, flags);
- break;
- case ExpressionType.RuntimeVariables:
- EmitRuntimeVariablesExpression(node);
- break;
- case ExpressionType.Loop:
- EmitLoopExpression(node);
- break;
- case ExpressionType.Switch:
- EmitSwitchExpression(node, flags);
- break;
- case ExpressionType.Throw:
- EmitThrowUnaryExpression(node);
- break;
- case ExpressionType.Try:
- EmitTryExpression(node);
- break;
- case ExpressionType.Unbox:
- EmitUnboxUnaryExpression(node);
- break;
- case ExpressionType.TypeEqual:
- EmitTypeBinaryExpression(node);
- break;
- case ExpressionType.OnesComplement:
- EmitUnaryExpression(node, flags);
- break;
- case ExpressionType.IsTrue:
- EmitUnaryExpression(node, flags);
- break;
- case ExpressionType.IsFalse:
- EmitUnaryExpression(node, flags);
- break;
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- default:
- throw ContractUtils.Unreachable;
- }
-
- if (emitStart) {
- EmitExpressionEnd(startEmitted);
- }
- }
-
- private static bool IsChecked(ExpressionType op) {
- switch (op) {
- #region Generated Checked Operations
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_checked_ops from: generate_tree.py
-
- case ExpressionType.AddChecked:
- case ExpressionType.ConvertChecked:
- case ExpressionType.MultiplyChecked:
- case ExpressionType.NegateChecked:
- case ExpressionType.SubtractChecked:
- case ExpressionType.AddAssignChecked:
- case ExpressionType.MultiplyAssignChecked:
- case ExpressionType.SubtractAssignChecked:
-
- // *** END GENERATED CODE ***
-
- #endregion
- return true;
- }
- return false;
- }
-
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Lambda.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Lambda.cs
deleted file mode 100644
index 40756223bdf..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Lambda.cs
+++ /dev/null
@@ -1,199 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Reflection.Emit;
-using System.Runtime.CompilerServices;
-using System.Threading;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
-
- /// <summary>
- /// Dynamic Language Runtime Compiler.
- /// This part compiles lambdas.
- /// </summary>
- partial class LambdaCompiler {
- private static int _Counter;
-
- internal void EmitConstantArray<T>(T[] array) {
- // Emit as runtime constant if possible
- // if not, emit into IL
- if (_method is DynamicMethod) {
- EmitConstant(array, typeof(T[]));
-#if FEATURE_REFEMIT
- } else if(_typeBuilder != null) {
- // store into field in our type builder, we will initialize
- // the value only once.
- FieldBuilder fb = CreateStaticField("ConstantArray", typeof(T[]));
- Label l = _ilg.DefineLabel();
- _ilg.Emit(OpCodes.Ldsfld, fb);
- _ilg.Emit(OpCodes.Ldnull);
- _ilg.Emit(OpCodes.Bne_Un, l);
- _ilg.EmitArray(array);
- _ilg.Emit(OpCodes.Stsfld, fb);
- _ilg.MarkLabel(l);
- _ilg.Emit(OpCodes.Ldsfld, fb);
-#endif
- } else {
- _ilg.EmitArray(array);
- }
- }
-
- private void EmitClosureCreation(LambdaCompiler inner) {
- bool closure = inner._scope.NeedsClosure;
- bool boundConstants = inner._boundConstants.Count > 0;
-
- if (!closure && !boundConstants) {
- _ilg.EmitNull();
- return;
- }
-
- // new Closure(constantPool, currentHoistedLocals)
- if (boundConstants) {
- _boundConstants.EmitConstant(this, inner._boundConstants.ToArray(), typeof(object[]));
- } else {
- _ilg.EmitNull();
- }
- if (closure) {
- _scope.EmitGet(_scope.NearestHoistedLocals.SelfVariable);
- } else {
- _ilg.EmitNull();
- }
- _ilg.EmitNew(typeof(Closure).GetConstructor(new Type[] { typeof(object[]), typeof(object[]) }));
- }
-
- /// <summary>
- /// Emits code which creates new instance of the delegateType delegate.
- ///
- /// Since the delegate is getting closed over the "Closure" argument, this
- /// cannot be used with virtual/instance methods (inner must be static method)
- /// </summary>
- private void EmitDelegateConstruction(LambdaCompiler inner) {
- Type delegateType = inner._lambda.Type;
- DynamicMethod dynamicMethod = inner._method as DynamicMethod;
- if (dynamicMethod != null) {
- // dynamicMethod.CreateDelegate(delegateType, closure)
- _boundConstants.EmitConstant(this, dynamicMethod, typeof(DynamicMethod));
- _ilg.EmitType(delegateType);
- EmitClosureCreation(inner);
- _ilg.Emit(OpCodes.Callvirt, typeof(DynamicMethod).GetMethod("CreateDelegate", new Type[] { typeof(Type), typeof(object) }));
- _ilg.Emit(OpCodes.Castclass, delegateType);
- } else {
- // new DelegateType(closure)
- EmitClosureCreation(inner);
- _ilg.Emit(OpCodes.Ldftn, (MethodInfo)inner._method);
- _ilg.Emit(OpCodes.Newobj, (ConstructorInfo)(delegateType.GetMember(".ctor")[0]));
- }
- }
-
- /// <summary>
- /// Emits a delegate to the method generated for the LambdaExpression.
- /// May end up creating a wrapper to match the requested delegate type.
- /// </summary>
- /// <param name="lambda">Lambda for which to generate a delegate</param>
- ///
- private void EmitDelegateConstruction(LambdaExpression lambda) {
- // 1. Create the new compiler
- LambdaCompiler impl = CreateCompiler(lambda);
-
- // 2. emit the lambda
- // Since additional ILs are always emitted after the lambda's body, should not emit with tail call optimization.
- impl.EmitLambdaBody(_scope, false, CompilationFlags.EmitAsNoTail);
-
- // 3. emit the delegate creation in the outer lambda
- EmitDelegateConstruction(impl);
- }
-
- private LambdaCompiler CreateCompiler(LambdaExpression lambda) {
-#if FEATURE_REFEMIT
- if (!(_method is DynamicMethod)) {
- // When the lambda does not have a name or the name is empty, generate a unique name for it.
- string name = String.IsNullOrEmpty(lambda.Name) ? GetUniqueMethodName() : lambda.Name;
- MethodBuilder mb = _typeBuilder.DefineMethod(name, MethodAttributes.Private | MethodAttributes.Static);
- return new LambdaCompiler(_tree, lambda, mb);
- }
-#endif
- return new LambdaCompiler(_tree, lambda);
- }
-
- private static Type[] GetParameterTypes(LambdaExpression lambda) {
- return lambda.Parameters.Map(p => p.IsByRef ? p.Type.MakeByRefType() : p.Type);
- }
-
- private static string GetUniqueMethodName() {
- return "<ExpressionCompilerImplementationDetails>{" + Interlocked.Increment(ref _Counter) + "}lambda_method";
- }
-
- private void EmitLambdaBody() {
- // The lambda body is the "last" expression of the lambda
- CompilationFlags tailCallFlag = _lambda.TailCall ? CompilationFlags.EmitAsTail : CompilationFlags.EmitAsNoTail;
- EmitLambdaBody(null, false, tailCallFlag);
- }
-
- /// <summary>
- /// Emits the lambda body. If inlined, the parameters should already be
- /// pushed onto the IL stack.
- /// </summary>
- /// <param name="parent">The parent scope.</param>
- /// <param name="inlined">true if the lambda is inlined; false otherwise.</param>
- /// <param name="flags">
- /// The emum to specify if the lambda is compiled with the tail call optimization.
- /// </param>
- private void EmitLambdaBody(CompilerScope parent, bool inlined, CompilationFlags flags) {
- _scope.Enter(this, parent);
-
- if (inlined) {
- // The arguments were already pushed onto the IL stack.
- // Store them into locals, popping in reverse order.
- //
- // If any arguments were ByRef, the address is on the stack and
- // we'll be storing it into the variable, which has a ref type.
- for (int i = _lambda.Parameters.Count - 1; i >= 0; i--) {
- _scope.EmitSet(_lambda.Parameters[i]);
- }
- }
-
- // Need to emit the expression start for the lambda body
- flags = UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart);
- if (_lambda.ReturnType == typeof(void)) {
- EmitExpressionAsVoid(_lambda.Body, flags);
- } else {
- EmitExpression(_lambda.Body, flags);
- }
-
- // Return must be the last instruction in a CLI method.
- // But if we're inlining the lambda, we want to leave the return
- // value on the IL stack.
- if (!inlined) {
- _ilg.Emit(OpCodes.Ret);
- }
-
- _scope.Exit();
-
- // Validate labels
- Debug.Assert(_labelBlock.Parent == null && _labelBlock.Kind == LabelScopeKind.Lambda);
- foreach (LabelInfo label in _labelInfo.Values) {
- label.ValidateFinish();
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Logical.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Logical.cs
deleted file mode 100644
index 5af3a571386..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Logical.cs
+++ /dev/null
@@ -1,645 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Reflection.Emit;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
-
- partial class LambdaCompiler {
-
- #region Conditional
-
- private void EmitConditionalExpression(Expression expr, CompilationFlags flags) {
- ConditionalExpression node = (ConditionalExpression)expr;
- Debug.Assert(node.Test.Type == typeof(bool));
- Label labFalse = _ilg.DefineLabel();
- EmitExpressionAndBranch(false, node.Test, labFalse);
- EmitExpressionAsType(node.IfTrue, node.Type, flags);
-
- if (NotEmpty(node.IfFalse)) {
- Label labEnd = _ilg.DefineLabel();
- if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) {
- // We know the conditional expression is at the end of the lambda,
- // so it is safe to emit Ret here.
- _ilg.Emit(OpCodes.Ret);
- } else {
- _ilg.Emit(OpCodes.Br, labEnd);
- }
- _ilg.MarkLabel(labFalse);
- EmitExpressionAsType(node.IfFalse, node.Type, flags);
- _ilg.MarkLabel(labEnd);
- } else {
- _ilg.MarkLabel(labFalse);
- }
- }
-
- /// <summary>
- /// returns true if the expression is not empty, otherwise false.
- /// </summary>
- private static bool NotEmpty(Expression node) {
- var empty = node as DefaultExpression;
- if (empty == null || empty.Type != typeof(void)) {
- return true;
- }
-
- return false;
- }
-
- /// <summary>
- /// returns true if the expression is NOT empty and is not debug info,
- /// or a block that contains only insignificant expressions.
- /// </summary>
- private static bool Significant(Expression node) {
- var block = node as BlockExpression;
- if (block != null) {
- for (int i = 0; i < block.ExpressionCount; i++) {
- if (Significant(block.GetExpression(i))) {
- return true;
- }
- }
- return false;
- }
- return NotEmpty(node) && !(node is DebugInfoExpression);
- }
-
- #endregion
-
- #region Coalesce
-
-
- private void EmitCoalesceBinaryExpression(Expression expr) {
- BinaryExpression b = (BinaryExpression)expr;
- Debug.Assert(b.Method == null);
-
- if (TypeUtils.IsNullableType(b.Left.Type)) {
- EmitNullableCoalesce(b);
- } else if (b.Left.Type.IsValueType) {
- throw Error.CoalesceUsedOnNonNullType();
- } else if (b.Conversion != null) {
- EmitLambdaReferenceCoalesce(b);
- } else {
- EmitReferenceCoalesceWithoutConversion(b);
- }
- }
-
-
- private void EmitNullableCoalesce(BinaryExpression b) {
- Debug.Assert(b.Method == null);
-
- LocalBuilder loc = GetLocal(b.Left.Type);
- Label labIfNull = _ilg.DefineLabel();
- Label labEnd = _ilg.DefineLabel();
- EmitExpression(b.Left);
- _ilg.Emit(OpCodes.Stloc, loc);
- _ilg.Emit(OpCodes.Ldloca, loc);
- _ilg.EmitHasValue(b.Left.Type);
- _ilg.Emit(OpCodes.Brfalse, labIfNull);
-
- Type nnLeftType = TypeUtils.GetNonNullableType(b.Left.Type);
- if (b.Conversion != null) {
- Debug.Assert(b.Conversion.Parameters.Count == 1);
- ParameterExpression p = b.Conversion.Parameters[0];
- Debug.Assert(p.Type.IsAssignableFrom(b.Left.Type) ||
- p.Type.IsAssignableFrom(nnLeftType));
-
- // emit the delegate instance
- EmitLambdaExpression(b.Conversion);
-
- // emit argument
- if (!p.Type.IsAssignableFrom(b.Left.Type)) {
- _ilg.Emit(OpCodes.Ldloca, loc);
- _ilg.EmitGetValueOrDefault(b.Left.Type);
- } else {
- _ilg.Emit(OpCodes.Ldloc, loc);
- }
-
- // emit call to invoke
- _ilg.Emit(OpCodes.Callvirt, b.Conversion.Type.GetMethod("Invoke"));
- } else if (!TypeUtils.AreEquivalent(b.Type, nnLeftType)) {
- _ilg.Emit(OpCodes.Ldloca, loc);
- _ilg.EmitGetValueOrDefault(b.Left.Type);
- _ilg.EmitConvertToType(nnLeftType, b.Type, true);
- } else {
- _ilg.Emit(OpCodes.Ldloca, loc);
- _ilg.EmitGetValueOrDefault(b.Left.Type);
- }
- FreeLocal(loc);
-
- _ilg.Emit(OpCodes.Br, labEnd);
- _ilg.MarkLabel(labIfNull);
- EmitExpression(b.Right);
- if (!TypeUtils.AreEquivalent(b.Right.Type, b.Type)) {
- _ilg.EmitConvertToType(b.Right.Type, b.Type, true);
- }
- _ilg.MarkLabel(labEnd);
- }
-
-
- private void EmitLambdaReferenceCoalesce(BinaryExpression b) {
- LocalBuilder loc = GetLocal(b.Left.Type);
- Label labEnd = _ilg.DefineLabel();
- Label labNotNull = _ilg.DefineLabel();
- EmitExpression(b.Left);
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Stloc, loc);
- _ilg.Emit(OpCodes.Ldnull);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Brfalse, labNotNull);
- EmitExpression(b.Right);
- _ilg.Emit(OpCodes.Br, labEnd);
-
- // if not null, call conversion
- _ilg.MarkLabel(labNotNull);
- Debug.Assert(b.Conversion.Parameters.Count == 1);
-
- // emit the delegate instance
- EmitLambdaExpression(b.Conversion);
-
- // emit argument
- _ilg.Emit(OpCodes.Ldloc, loc);
- FreeLocal(loc);
-
- // emit call to invoke
- _ilg.Emit(OpCodes.Callvirt, b.Conversion.Type.GetMethod("Invoke"));
-
- _ilg.MarkLabel(labEnd);
- }
-
-
- private void EmitReferenceCoalesceWithoutConversion(BinaryExpression b) {
- Label labEnd = _ilg.DefineLabel();
- Label labCast = _ilg.DefineLabel();
- EmitExpression(b.Left);
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Ldnull);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Brfalse, labCast);
- _ilg.Emit(OpCodes.Pop);
- EmitExpression(b.Right);
- if (!TypeUtils.AreEquivalent(b.Right.Type, b.Type)) {
- if (b.Right.Type.IsValueType) {
- _ilg.Emit(OpCodes.Box, b.Right.Type);
- }
- _ilg.Emit(OpCodes.Castclass, b.Type);
- }
- _ilg.Emit(OpCodes.Br_S, labEnd);
- _ilg.MarkLabel(labCast);
- if (!TypeUtils.AreEquivalent(b.Left.Type, b.Type)) {
- Debug.Assert(!b.Left.Type.IsValueType);
- _ilg.Emit(OpCodes.Castclass, b.Type);
- }
- _ilg.MarkLabel(labEnd);
- }
-
- #endregion
-
- #region AndAlso
-
- private void EmitLiftedAndAlso(BinaryExpression b) {
- Type type = typeof(bool?);
- Label labComputeRight = _ilg.DefineLabel();
- Label labReturnFalse = _ilg.DefineLabel();
- Label labReturnNull = _ilg.DefineLabel();
- Label labReturnValue = _ilg.DefineLabel();
- Label labExit = _ilg.DefineLabel();
- LocalBuilder locLeft = GetLocal(type);
- LocalBuilder locRight = GetLocal(type);
- EmitExpression(b.Left);
- _ilg.Emit(OpCodes.Stloc, locLeft);
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(type);
- _ilg.Emit(OpCodes.Brfalse, labComputeRight);
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitGetValueOrDefault(type);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Brtrue, labReturnFalse);
- // compute right
- _ilg.MarkLabel(labComputeRight);
- EmitExpression(b.Right);
- _ilg.Emit(OpCodes.Stloc, locRight);
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitHasValue(type);
- _ilg.Emit(OpCodes.Brfalse_S, labReturnNull);
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitGetValueOrDefault(type);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Brtrue_S, labReturnFalse);
- // check left for null again
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(type);
- _ilg.Emit(OpCodes.Brfalse, labReturnNull);
- // return true
- _ilg.Emit(OpCodes.Ldc_I4_1);
- _ilg.Emit(OpCodes.Br_S, labReturnValue);
- // return false
- _ilg.MarkLabel(labReturnFalse);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Br_S, labReturnValue);
- _ilg.MarkLabel(labReturnValue);
- ConstructorInfo ci = type.GetConstructor(new Type[] { typeof(bool) });
- _ilg.Emit(OpCodes.Newobj, ci);
- _ilg.Emit(OpCodes.Stloc, locLeft);
- _ilg.Emit(OpCodes.Br, labExit);
- // return null
- _ilg.MarkLabel(labReturnNull);
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.Emit(OpCodes.Initobj, type);
- _ilg.MarkLabel(labExit);
- _ilg.Emit(OpCodes.Ldloc, locLeft);
- FreeLocal(locLeft);
- FreeLocal(locRight);
- }
-
- private void EmitMethodAndAlso(BinaryExpression b, CompilationFlags flags) {
- Label labEnd = _ilg.DefineLabel();
- EmitExpression(b.Left);
- _ilg.Emit(OpCodes.Dup);
- MethodInfo opFalse = TypeUtils.GetBooleanOperator(b.Method.DeclaringType, "op_False");
- Debug.Assert(opFalse != null, "factory should check that the method exists");
- _ilg.Emit(OpCodes.Call, opFalse);
- _ilg.Emit(OpCodes.Brtrue, labEnd);
-
- //store the value of the left value before emitting b.Right to empty the evaluation stack
- LocalBuilder locLeft = GetLocal(b.Left.Type);
- _ilg.Emit(OpCodes.Stloc, locLeft);
-
- EmitExpression(b.Right);
- //store the right value to local
- LocalBuilder locRight = GetLocal(b.Right.Type);
- _ilg.Emit(OpCodes.Stloc, locRight);
-
- Debug.Assert(b.Method.IsStatic);
- _ilg.Emit(OpCodes.Ldloc, locLeft);
- _ilg.Emit(OpCodes.Ldloc, locRight);
- if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) {
- _ilg.Emit(OpCodes.Tailcall);
- }
- _ilg.Emit(OpCodes.Call, b.Method);
- FreeLocal(locLeft);
- FreeLocal(locRight);
- _ilg.MarkLabel(labEnd);
- }
-
- private void EmitUnliftedAndAlso(BinaryExpression b) {
- Label @else = _ilg.DefineLabel();
- Label end = _ilg.DefineLabel();
- EmitExpressionAndBranch(false, b.Left, @else);
- EmitExpression(b.Right);
- _ilg.Emit(OpCodes.Br, end);
- _ilg.MarkLabel(@else);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.MarkLabel(end);
- }
-
- private void EmitAndAlsoBinaryExpression(Expression expr, CompilationFlags flags) {
- BinaryExpression b = (BinaryExpression)expr;
-
- if (b.Method != null && !b.IsLiftedLogical) {
- EmitMethodAndAlso(b, flags);
- } else if (b.Left.Type == typeof(bool?)) {
- EmitLiftedAndAlso(b);
- } else if (b.IsLiftedLogical) {
- EmitExpression(b.ReduceUserdefinedLifted());
- } else {
- EmitUnliftedAndAlso(b);
- }
- }
-
- #endregion
-
- #region OrElse
-
- private void EmitLiftedOrElse(BinaryExpression b) {
- Type type = typeof(bool?);
- Label labComputeRight = _ilg.DefineLabel();
- Label labReturnTrue = _ilg.DefineLabel();
- Label labReturnNull = _ilg.DefineLabel();
- Label labReturnValue = _ilg.DefineLabel();
- Label labExit = _ilg.DefineLabel();
- LocalBuilder locLeft = GetLocal(type);
- LocalBuilder locRight = GetLocal(type);
- EmitExpression(b.Left);
- _ilg.Emit(OpCodes.Stloc, locLeft);
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(type);
- _ilg.Emit(OpCodes.Brfalse, labComputeRight);
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitGetValueOrDefault(type);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Brfalse, labReturnTrue);
- // compute right
- _ilg.MarkLabel(labComputeRight);
- EmitExpression(b.Right);
- _ilg.Emit(OpCodes.Stloc, locRight);
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitHasValue(type);
- _ilg.Emit(OpCodes.Brfalse_S, labReturnNull);
- _ilg.Emit(OpCodes.Ldloca, locRight);
- _ilg.EmitGetValueOrDefault(type);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Brfalse_S, labReturnTrue);
- // check left for null again
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.EmitHasValue(type);
- _ilg.Emit(OpCodes.Brfalse, labReturnNull);
- // return false
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Br_S, labReturnValue);
- // return true
- _ilg.MarkLabel(labReturnTrue);
- _ilg.Emit(OpCodes.Ldc_I4_1);
- _ilg.Emit(OpCodes.Br_S, labReturnValue);
- _ilg.MarkLabel(labReturnValue);
- ConstructorInfo ci = type.GetConstructor(new Type[] { typeof(bool) });
- _ilg.Emit(OpCodes.Newobj, ci);
- _ilg.Emit(OpCodes.Stloc, locLeft);
- _ilg.Emit(OpCodes.Br, labExit);
- // return null
- _ilg.MarkLabel(labReturnNull);
- _ilg.Emit(OpCodes.Ldloca, locLeft);
- _ilg.Emit(OpCodes.Initobj, type);
- _ilg.MarkLabel(labExit);
- _ilg.Emit(OpCodes.Ldloc, locLeft);
- FreeLocal(locLeft);
- FreeLocal(locRight);
- }
-
- private void EmitUnliftedOrElse(BinaryExpression b) {
- Label @else = _ilg.DefineLabel();
- Label end = _ilg.DefineLabel();
- EmitExpressionAndBranch(false, b.Left, @else);
- _ilg.Emit(OpCodes.Ldc_I4_1);
- _ilg.Emit(OpCodes.Br, end);
- _ilg.MarkLabel(@else);
- EmitExpression(b.Right);
- _ilg.MarkLabel(end);
- }
-
- private void EmitMethodOrElse(BinaryExpression b, CompilationFlags flags) {
- Label labEnd = _ilg.DefineLabel();
- EmitExpression(b.Left);
- _ilg.Emit(OpCodes.Dup);
- MethodInfo opTrue = TypeUtils.GetBooleanOperator(b.Method.DeclaringType, "op_True");
- Debug.Assert(opTrue != null, "factory should check that the method exists");
- _ilg.Emit(OpCodes.Call, opTrue);
- _ilg.Emit(OpCodes.Brtrue, labEnd);
-
- //store the value of the left value before emitting b.Right to empty the evaluation stack
- LocalBuilder locLeft = GetLocal(b.Left.Type);
- _ilg.Emit(OpCodes.Stloc, locLeft);
-
- EmitExpression(b.Right);
- //store the right value to local
- LocalBuilder locRight = GetLocal(b.Right.Type);
- _ilg.Emit(OpCodes.Stloc, locRight);
-
- Debug.Assert(b.Method.IsStatic);
- _ilg.Emit(OpCodes.Ldloc, locLeft);
- _ilg.Emit(OpCodes.Ldloc, locRight);
- if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) {
- _ilg.Emit(OpCodes.Tailcall);
- }
- _ilg.Emit(OpCodes.Call, b.Method);
- FreeLocal(locLeft);
- FreeLocal(locRight);
- _ilg.MarkLabel(labEnd);
- }
-
- private void EmitOrElseBinaryExpression(Expression expr, CompilationFlags flags) {
- BinaryExpression b = (BinaryExpression)expr;
-
- if (b.Method != null && !b.IsLiftedLogical) {
- EmitMethodOrElse(b, flags);
- } else if (b.Left.Type == typeof(bool?)) {
- EmitLiftedOrElse(b);
- } else if (b.IsLiftedLogical) {
- EmitExpression(b.ReduceUserdefinedLifted());
- } else {
- EmitUnliftedOrElse(b);
- }
- }
-
- #endregion
-
- #region Optimized branching
-
- /// <summary>
- /// Emits the expression and then either brtrue/brfalse to the label.
- /// </summary>
- /// <param name="branchValue">True for brtrue, false for brfalse.</param>
- /// <param name="node">The expression to emit.</param>
- /// <param name="label">The label to conditionally branch to.</param>
- /// <remarks>
- /// This function optimizes equality and short circuiting logical
- /// operators to avoid double-branching, minimize instruction count,
- /// and generate similar IL to the C# compiler. This is important for
- /// the JIT to optimize patterns like:
- /// x != null AndAlso x.GetType() == typeof(SomeType)
- ///
- /// One optimization we don't do: we always emits at least one
- /// conditional branch to the label, and always possibly falls through,
- /// even if we know if the branch will always succeed or always fail.
- /// We do this to avoid generating unreachable code, which is fine for
- /// the CLR JIT, but doesn't verify with peverify.
- ///
- /// This kind of optimization could be implemented safely, by doing
- /// constant folding over conditionals and logical expressions at the
- /// tree level.
- /// </remarks>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
- private void EmitExpressionAndBranch(bool branchValue, Expression node, Label label) {
- CompilationFlags startEmitted = EmitExpressionStart(node);
- try {
- if (node.Type == typeof(bool)) {
- switch (node.NodeType) {
- case ExpressionType.Not:
- EmitBranchNot(branchValue, (UnaryExpression)node, label);
- return;
- case ExpressionType.AndAlso:
- case ExpressionType.OrElse:
- EmitBranchLogical(branchValue, (BinaryExpression)node, label);
- return;
- case ExpressionType.Block:
- EmitBranchBlock(branchValue, (BlockExpression)node, label);
- return;
- case ExpressionType.Equal:
- case ExpressionType.NotEqual:
- EmitBranchComparison(branchValue, (BinaryExpression)node, label);
- return;
- }
- }
- EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart);
- EmitBranchOp(branchValue, label);
- } finally {
- EmitExpressionEnd(startEmitted);
- }
- }
-
- private void EmitBranchOp(bool branch, Label label) {
- _ilg.Emit(branch ? OpCodes.Brtrue : OpCodes.Brfalse, label);
- }
-
- private void EmitBranchNot(bool branch, UnaryExpression node, Label label) {
- if (node.Method != null) {
- EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart);
- EmitBranchOp(branch, label);
- return;
- }
- EmitExpressionAndBranch(!branch, node.Operand, label);
- }
-
- private void EmitBranchComparison(bool branch, BinaryExpression node, Label label) {
- Debug.Assert(node.NodeType == ExpressionType.Equal || node.NodeType == ExpressionType.NotEqual);
- Debug.Assert(!node.IsLiftedToNull);
-
- // To share code paths, we want to treat NotEqual as an inverted Equal
- bool branchWhenEqual = branch == (node.NodeType == ExpressionType.Equal);
-
- if (node.Method != null) {
- EmitBinaryMethod(node, CompilationFlags.EmitAsNoTail);
- // EmitBinaryMethod takes into account the Equal/NotEqual
- // node kind, so use the original branch value
- EmitBranchOp(branch, label);
- } else if (ConstantCheck.IsNull(node.Left)) {
- if (TypeUtils.IsNullableType(node.Right.Type)) {
- EmitAddress(node.Right, node.Right.Type);
- _ilg.EmitHasValue(node.Right.Type);
- } else {
- Debug.Assert(!node.Right.Type.IsValueType);
- EmitExpression(GetEqualityOperand(node.Right));
- }
- EmitBranchOp(!branchWhenEqual, label);
- } else if (ConstantCheck.IsNull(node.Right)) {
- if (TypeUtils.IsNullableType(node.Left.Type)) {
- EmitAddress(node.Left, node.Left.Type);
- _ilg.EmitHasValue(node.Left.Type);
- } else {
- Debug.Assert(!node.Left.Type.IsValueType);
- EmitExpression(GetEqualityOperand(node.Left));
- }
- EmitBranchOp(!branchWhenEqual, label);
- } else if (TypeUtils.IsNullableType(node.Left.Type) || TypeUtils.IsNullableType(node.Right.Type)) {
- EmitBinaryExpression(node);
- // EmitBinaryExpression takes into account the Equal/NotEqual
- // node kind, so use the original branch value
- EmitBranchOp(branch, label);
- } else {
- EmitExpression(GetEqualityOperand(node.Left));
- EmitExpression(GetEqualityOperand(node.Right));
- if (branchWhenEqual) {
- _ilg.Emit(OpCodes.Beq, label);
- } else {
- _ilg.Emit(OpCodes.Ceq);
- _ilg.Emit(OpCodes.Brfalse, label);
- }
- }
- }
-
- // For optimized Equal/NotEqual, we can eliminate reference
- // conversions. IL allows comparing managed pointers regardless of
- // type. See ECMA-335 "Binary Comparison or Branch Operations", in
- // Partition III, Section 1.5 Table 4.
- private static Expression GetEqualityOperand(Expression expression) {
- if (expression.NodeType == ExpressionType.Convert) {
- var convert = (UnaryExpression)expression;
- if (TypeUtils.AreReferenceAssignable(convert.Type, convert.Operand.Type)) {
- return convert.Operand;
- }
- }
- return expression;
- }
-
- private void EmitBranchLogical(bool branch, BinaryExpression node, Label label) {
- Debug.Assert(node.NodeType == ExpressionType.AndAlso || node.NodeType == ExpressionType.OrElse);
- Debug.Assert(!node.IsLiftedToNull);
-
- if (node.Method != null || node.IsLifted) {
- EmitExpression(node);
- EmitBranchOp(branch, label);
- return;
- }
-
-
- bool isAnd = node.NodeType == ExpressionType.AndAlso;
-
- // To share code, we make the following substitutions:
- // if (!(left || right)) branch value
- // becomes:
- // if (!left && !right) branch value
- // and:
- // if (!(left && right)) branch value
- // becomes:
- // if (!left || !right) branch value
- //
- // The observation is that "brtrue(x && y)" has the same codegen as
- // "brfalse(x || y)" except the branches have the opposite sign.
- // Same for "brfalse(x && y)" and "brtrue(x || y)".
- //
- if (branch == isAnd) {
- EmitBranchAnd(branch, node, label);
- } else {
- EmitBranchOr(branch, node, label);
- }
- }
-
- // Generates optimized AndAlso with branch == true
- // or optimized OrElse with branch == false
- private void EmitBranchAnd(bool branch, BinaryExpression node, Label label) {
- // if (left) then
- // if (right) branch label
- // endif
-
- Label endif = _ilg.DefineLabel();
- EmitExpressionAndBranch(!branch, node.Left, endif);
- EmitExpressionAndBranch(branch, node.Right, label);
- _ilg.MarkLabel(endif);
- }
-
- // Generates optimized OrElse with branch == true
- // or optimized AndAlso with branch == false
- private void EmitBranchOr(bool branch, BinaryExpression node, Label label) {
- // if (left OR right) branch label
-
- EmitExpressionAndBranch(branch, node.Left, label);
- EmitExpressionAndBranch(branch, node.Right, label);
- }
-
- private void EmitBranchBlock(bool branch, BlockExpression node, Label label) {
- EnterScope(node);
-
- int count = node.ExpressionCount;
- for (int i = 0; i < count - 1; i++) {
- EmitExpressionAsVoid(node.GetExpression(i));
- }
- EmitExpressionAndBranch(branch, node.GetExpression(count - 1), label);
-
- ExitScope(node);
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Statements.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Statements.cs
deleted file mode 100644
index 7ab065c2d93..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Statements.cs
+++ /dev/null
@@ -1,821 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Reflection.Emit;
-using System.Globalization;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- partial class LambdaCompiler {
- private void EmitBlockExpression(Expression expr, CompilationFlags flags) {
- // emit body
- Emit((BlockExpression)expr, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsDefaultType));
- }
-
- private void Emit(BlockExpression node, CompilationFlags flags) {
- EnterScope(node);
-
- CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask;
-
- int count = node.ExpressionCount;
- CompilationFlags tailCall = flags & CompilationFlags.EmitAsTailCallMask;
- for (int index = 0; index < count - 1; index++) {
- var e = node.GetExpression(index);
- var next = node.GetExpression(index + 1);
-
- if (EmitDebugSymbols) {
- // No need to emit a clearance if the next expression in the block is also a
- // DebugInfoExprssion.
- var debugInfo = e as DebugInfoExpression;
- if (debugInfo != null && debugInfo.IsClear && next is DebugInfoExpression) {
- continue;
- }
- }
-
- CompilationFlags tailCallFlag;
- if (tailCall != CompilationFlags.EmitAsNoTail) {
- var g = next as GotoExpression;
- if (g != null && (g.Value == null || !Significant(g.Value)) && ReferenceLabel(g.Target).CanReturn) {
- // Since tail call flags are not passed into EmitTryExpression, CanReturn means the goto will be emitted
- // as Ret. Therefore we can emit the current expression with tail call.
- tailCallFlag = CompilationFlags.EmitAsTail;
- } else {
- // In the middle of the block.
- // We may do better here by marking it as Tail if the following expressions are not going to emit any IL.
- tailCallFlag = CompilationFlags.EmitAsMiddle;
- }
- } else {
- tailCallFlag = CompilationFlags.EmitAsNoTail;
- }
-
- flags = UpdateEmitAsTailCallFlag(flags, tailCallFlag);
- EmitExpressionAsVoid(e, flags);
- }
-
- // if the type of Block it means this is not a Comma
- // so we will force the last expression to emit as void.
- // We don't need EmitAsType flag anymore, should only pass
- // the EmitTailCall field in flags to emitting the last expression.
- if (emitAs == CompilationFlags.EmitAsVoidType || node.Type == typeof(void)) {
- EmitExpressionAsVoid(node.GetExpression(count - 1), tailCall);
- } else {
- EmitExpressionAsType(node.GetExpression(count - 1), node.Type, tailCall);
- }
-
- ExitScope(node);
- }
-
- private void EnterScope(object node) {
- if (HasVariables(node) &&
- (_scope.MergedScopes == null || !_scope.MergedScopes.Contains(node))) {
-
- CompilerScope scope;
- if (!_tree.Scopes.TryGetValue(node, out scope)) {
- //
- // Very often, we want to compile nodes as reductions
- // rather than as IL, but usually they need to allocate
- // some IL locals. To support this, we allow emitting a
- // BlockExpression that was not bound by VariableBinder.
- // This works as long as the variables are only used
- // locally -- i.e. not closed over.
- //
- // User-created blocks will never hit this case; only our
- // internally reduced nodes will.
- //
- scope = new CompilerScope(node, false) { NeedsClosure = _scope.NeedsClosure };
- }
-
- _scope = scope.Enter(this, _scope);
- Debug.Assert(_scope.Node == node);
- }
- }
-
- private static bool HasVariables(object node) {
- var block = node as BlockExpression;
- if (block != null) {
- return block.Variables.Count > 0;
- }
- return ((CatchBlock)node).Variable != null;
- }
-
- private void ExitScope(object node) {
- if (_scope.Node == node) {
- _scope = _scope.Exit();
- }
- }
-
- private void EmitDefaultExpression(Expression expr) {
- var node = (DefaultExpression)expr;
- if (node.Type != typeof(void)) {
- // emit default(T)
- _ilg.EmitDefault(node.Type);
- }
- }
-
- private void EmitLoopExpression(Expression expr) {
- LoopExpression node = (LoopExpression)expr;
-
- PushLabelBlock(LabelScopeKind.Statement);
- LabelInfo breakTarget = DefineLabel(node.BreakLabel);
- LabelInfo continueTarget = DefineLabel(node.ContinueLabel);
-
- continueTarget.MarkWithEmptyStack();
-
- EmitExpressionAsVoid(node.Body);
-
- _ilg.Emit(OpCodes.Br, continueTarget.Label);
-
- PopLabelBlock(LabelScopeKind.Statement);
-
- breakTarget.MarkWithEmptyStack();
- }
-
- #region SwitchExpression
-
- private void EmitSwitchExpression(Expression expr, CompilationFlags flags) {
- SwitchExpression node = (SwitchExpression)expr;
-
- // Try to emit it as an IL switch. Works for integer types.
- if (TryEmitSwitchInstruction(node, flags)) {
- return;
- }
-
- // Try to emit as a hashtable lookup. Works for strings.
- if (TryEmitHashtableSwitch(node, flags)) {
- return;
- }
-
- //
- // Fall back to a series of tests. We need to IL gen instead of
- // transform the tree to avoid stack overflow on a big switch.
- //
-
- var switchValue = Expression.Parameter(node.SwitchValue.Type, "switchValue");
- var testValue = Expression.Parameter(GetTestValueType(node), "testValue");
- _scope.AddLocal(this, switchValue);
- _scope.AddLocal(this, testValue);
-
- EmitExpression(node.SwitchValue);
- _scope.EmitSet(switchValue);
-
- // Emit tests
- var labels = new Label[node.Cases.Count];
- var isGoto = new bool[node.Cases.Count];
- for (int i = 0, n = node.Cases.Count; i < n; i++) {
- DefineSwitchCaseLabel(node.Cases[i], out labels[i], out isGoto[i]);
- foreach (Expression test in node.Cases[i].TestValues) {
- // Pull the test out into a temp so it runs on the same
- // stack as the switch. This simplifies spilling.
- EmitExpression(test);
- _scope.EmitSet(testValue);
- Debug.Assert(TypeUtils.AreReferenceAssignable(testValue.Type, test.Type));
- EmitExpressionAndBranch(true, Expression.Equal(switchValue, testValue, false, node.Comparison), labels[i]);
- }
- }
-
- // Define labels
- Label end = _ilg.DefineLabel();
- Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel();
-
- // Emit the case and default bodies
- EmitSwitchCases(node, labels, isGoto, @default, end, flags);
- }
-
- /// <summary>
- /// Gets the common test test value type of the SwitchExpression.
- /// </summary>
- private static Type GetTestValueType(SwitchExpression node) {
- if (node.Comparison == null) {
- // If we have no comparison, all right side types must be the
- // same.
- return node.Cases[0].TestValues[0].Type;
- }
-
- // Otherwise, get the type from the method.
- Type result = node.Comparison.GetParametersCached()[1].ParameterType.GetNonRefType();
- if (node.IsLifted) {
- result = TypeUtils.GetNullableType(result);
- }
- return result;
- }
-
- private sealed class SwitchLabel {
- internal readonly decimal Key;
- internal readonly Label Label;
-
- // Boxed version of Key, preseving the original type.
- internal readonly object Constant;
-
- internal SwitchLabel(decimal key, object @constant, Label label) {
- Key = key;
- Constant = @constant;
- Label = label;
- }
- }
-
- private sealed class SwitchInfo {
- internal readonly SwitchExpression Node;
- internal readonly LocalBuilder Value;
- internal readonly Label Default;
- internal readonly Type Type;
- internal readonly bool IsUnsigned;
- internal readonly bool Is64BitSwitch;
-
- internal SwitchInfo(SwitchExpression node, LocalBuilder value, Label @default) {
- Node = node;
- Value = value;
- Default = @default;
- Type = Node.SwitchValue.Type;
- IsUnsigned = TypeUtils.IsUnsigned(Type);
- var code = Type.GetTypeCode(Type);
- Is64BitSwitch = code == TypeCode.UInt64 || code == TypeCode.Int64;
- }
- }
-
- private static bool FitsInBucket(List<SwitchLabel> buckets, decimal key, int count) {
- Debug.Assert(key > buckets[buckets.Count - 1].Key);
- decimal jumpTableSlots = key - buckets[0].Key + 1;
- if (jumpTableSlots > int.MaxValue) {
- return false;
- }
- // density must be > 50%
- return (buckets.Count + count) * 2 > jumpTableSlots;
- }
-
- private static void MergeBuckets(List<List<SwitchLabel>> buckets) {
- while (buckets.Count > 1) {
- List<SwitchLabel> first = buckets[buckets.Count - 2];
- List<SwitchLabel> second = buckets[buckets.Count - 1];
-
- if (!FitsInBucket(first, second[second.Count - 1].Key, second.Count)) {
- return;
- }
-
- // Merge them
- first.AddRange(second);
- buckets.RemoveAt(buckets.Count - 1);
- }
- }
-
- // Add key to a new or existing bucket
- private static void AddToBuckets(List<List<SwitchLabel>> buckets, SwitchLabel key) {
- if (buckets.Count > 0) {
- List<SwitchLabel> last = buckets[buckets.Count - 1];
- if (FitsInBucket(last, key.Key, 1)) {
- last.Add(key);
- // we might be able to merge now
- MergeBuckets(buckets);
- return;
- }
- }
- // else create a new bucket
- buckets.Add(new List<SwitchLabel> { key });
- }
-
- // Determines if the type is an integer we can switch on.
- private static bool CanOptimizeSwitchType(Type valueType) {
- // enums & char are allowed
- switch (Type.GetTypeCode(valueType)) {
- case TypeCode.Byte:
- case TypeCode.SByte:
- case TypeCode.Char:
- case TypeCode.Int16:
- case TypeCode.Int32:
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.Int64:
- case TypeCode.UInt64:
- return true;
- default:
- return false;
- }
- }
-
- // Tries to emit switch as a jmp table
- private bool TryEmitSwitchInstruction(SwitchExpression node, CompilationFlags flags) {
- // If we have a comparison, bail
- if (node.Comparison != null) {
- return false;
- }
-
- // Make sure the switch value type and the right side type
- // are types we can optimize
- Type type = node.SwitchValue.Type;
- if (!CanOptimizeSwitchType(type) ||
- !TypeUtils.AreEquivalent(type, node.Cases[0].TestValues[0].Type)) {
- return false;
- }
-
- // Make sure all test values are constant, or we can't emit the
- // jump table.
- if (!node.Cases.All(c => c.TestValues.All(t => t is ConstantExpression))) {
- return false;
- }
-
- //
- // We can emit the optimized switch, let's do it.
- //
-
- // Build target labels, collect keys.
- var labels = new Label[node.Cases.Count];
- var isGoto = new bool[node.Cases.Count];
-
- var uniqueKeys = new Set<decimal>();
- var keys = new List<SwitchLabel>();
- for (int i = 0; i < node.Cases.Count; i++) {
-
- DefineSwitchCaseLabel(node.Cases[i], out labels[i], out isGoto[i]);
-
- foreach (ConstantExpression test in node.Cases[i].TestValues) {
- // Guarenteed to work thanks to CanOptimizeSwitchType.
- //
- // Use decimal because it can hold Int64 or UInt64 without
- // precision loss or signed/unsigned conversions.
- decimal key = ConvertSwitchValue(test.Value);
-
- // Only add each key once. If it appears twice, it's
- // allowed, but can't be reached.
- if (!uniqueKeys.Contains(key)) {
- keys.Add(new SwitchLabel(key, test.Value, labels[i]));
- uniqueKeys.Add(key);
- }
- }
- }
-
- // Sort the keys, and group them into buckets.
- keys.Sort((x, y) => Math.Sign(x.Key - y.Key));
- var buckets = new List<List<SwitchLabel>>();
- foreach (var key in keys) {
- AddToBuckets(buckets, key);
- }
-
- // Emit the switchValue
- LocalBuilder value = GetLocal(node.SwitchValue.Type);
- EmitExpression(node.SwitchValue);
- _ilg.Emit(OpCodes.Stloc, value);
-
- // Create end label, and default label if needed
- Label end = _ilg.DefineLabel();
- Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel();
-
- // Emit the switch
- var info = new SwitchInfo(node, value, @default);
- EmitSwitchBuckets(info, buckets, 0, buckets.Count - 1);
-
- // Emit the case bodies and default
- EmitSwitchCases(node, labels, isGoto, @default, end, flags);
-
- FreeLocal(value);
- return true;
- }
-
- private static decimal ConvertSwitchValue(object value) {
- if (value is char) {
- return (int)(char)value;
- }
- return Convert.ToDecimal(value, CultureInfo.InvariantCulture);
- }
-
- /// <summary>
- /// Creates the label for this case.
- /// Optimization: if the body is just a goto, and we can branch
- /// to it, put the goto target directly in the jump table.
- /// </summary>
- private void DefineSwitchCaseLabel(SwitchCase @case, out Label label, out bool isGoto) {
- var jump = @case.Body as GotoExpression;
- // if it's a goto with no value
- if (jump != null && jump.Value == null) {
- // Reference the label from the switch. This will cause us to
- // analyze the jump target and determine if it is safe.
- LabelInfo jumpInfo = ReferenceLabel(jump.Target);
-
- // If we have are allowed to emit the "branch" opcode, then we
- // can jump directly there from the switch's jump table.
- // (Otherwise, we need to emit the goto later as a "leave".)
- if (jumpInfo.CanBranch) {
- label = jumpInfo.Label;
- isGoto = true;
- return;
- }
- }
- // otherwise, just define a new label
- label = _ilg.DefineLabel();
- isGoto = false;
- }
-
- private void EmitSwitchCases(SwitchExpression node, Label[] labels, bool[] isGoto, Label @default, Label end, CompilationFlags flags) {
- // Jump to default (to handle the fallthrough case)
- _ilg.Emit(OpCodes.Br, @default);
-
- // Emit the cases
- for (int i = 0, n = node.Cases.Count; i < n; i++) {
- // If the body is a goto, we already emitted an optimized
- // branch directly to it. No need to emit anything else.
- if (isGoto[i]) {
- continue;
- }
-
- _ilg.MarkLabel(labels[i]);
- EmitExpressionAsType(node.Cases[i].Body, node.Type, flags);
-
- // Last case doesn't need branch
- if (node.DefaultBody != null || i < n - 1) {
- if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) {
- //The switch case is at the tail of the lambda so
- //it is safe to emit a Ret.
- _ilg.Emit(OpCodes.Ret);
- } else {
- _ilg.Emit(OpCodes.Br, end);
- }
- }
- }
-
- // Default value
- if (node.DefaultBody != null) {
- _ilg.MarkLabel(@default);
- EmitExpressionAsType(node.DefaultBody, node.Type, flags);
- }
-
- _ilg.MarkLabel(end);
- }
-
- private void EmitSwitchBuckets(SwitchInfo info, List<List<SwitchLabel>> buckets, int first, int last) {
- if (first == last) {
- EmitSwitchBucket(info, buckets[first]);
- return;
- }
-
- // Split the buckets into two groups, and use an if test to find
- // the right bucket. This ensures we'll only need O(lg(B)) tests
- // where B is the number of buckets
- int mid = (int)(((long)first + last + 1) / 2);
-
- if (first == mid - 1) {
- EmitSwitchBucket(info, buckets[first]);
- } else {
- // If the first half contains more than one, we need to emit an
- // explicit guard
- Label secondHalf = _ilg.DefineLabel();
- _ilg.Emit(OpCodes.Ldloc, info.Value);
- _ilg.EmitConstant(buckets[mid - 1].Last().Constant);
- _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, secondHalf);
- EmitSwitchBuckets(info, buckets, first, mid - 1);
- _ilg.MarkLabel(secondHalf);
- }
-
- EmitSwitchBuckets(info, buckets, mid, last);
- }
-
- private void EmitSwitchBucket(SwitchInfo info, List<SwitchLabel> bucket) {
- // No need for switch if we only have one value
- if (bucket.Count == 1) {
- _ilg.Emit(OpCodes.Ldloc, info.Value);
- _ilg.EmitConstant(bucket[0].Constant);
- _ilg.Emit(OpCodes.Beq, bucket[0].Label);
- return;
- }
-
- //
- // If we're switching off of Int64/UInt64, we need more guards here
- // because we'll have to narrow the switch value to an Int32, and
- // we can't do that unless the value is in the right range.
- //
- Label? after = null;
- if (info.Is64BitSwitch) {
- after = _ilg.DefineLabel();
- _ilg.Emit(OpCodes.Ldloc, info.Value);
- _ilg.EmitConstant(bucket.Last().Constant);
- _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, after.Value);
- _ilg.Emit(OpCodes.Ldloc, info.Value);
- _ilg.EmitConstant(bucket[0].Constant);
- _ilg.Emit(info.IsUnsigned ? OpCodes.Blt_Un : OpCodes.Blt, after.Value);
- }
-
- _ilg.Emit(OpCodes.Ldloc, info.Value);
-
- // Normalize key
- decimal key = bucket[0].Key;
- if (key != 0) {
- _ilg.EmitConstant(bucket[0].Constant);
- _ilg.Emit(OpCodes.Sub);
- }
-
- if (info.Is64BitSwitch) {
- _ilg.Emit(OpCodes.Conv_I4);
- }
-
- // Collect labels
- int len = (int)(bucket[bucket.Count - 1].Key - bucket[0].Key + 1);
- Label[] jmpLabels = new Label[len];
-
- // Initialize all labels to the default
- int slot = 0;
- foreach (SwitchLabel label in bucket) {
- while (key++ != label.Key) {
- jmpLabels[slot++] = info.Default;
- }
- jmpLabels[slot++] = label.Label;
- }
-
- // check we used all keys and filled all slots
- Debug.Assert(key == bucket[bucket.Count - 1].Key + 1);
- Debug.Assert(slot == jmpLabels.Length);
-
- // Finally, emit the switch instruction
- _ilg.Emit(OpCodes.Switch, jmpLabels);
-
- if (info.Is64BitSwitch) {
- _ilg.MarkLabel(after.Value);
- }
- }
-
- private bool TryEmitHashtableSwitch(SwitchExpression node, CompilationFlags flags) {
- // If we have a comparison other than string equality, bail
- if (node.Comparison != typeof(string).GetMethod("op_Equality", BindingFlags.Public | BindingFlags.Static | BindingFlags.ExactBinding, null, new[] { typeof(string), typeof(string) }, null)) {
- return false;
- }
-
- // All test values must be constant.
- int tests = 0;
- foreach (SwitchCase c in node.Cases) {
- foreach (Expression t in c.TestValues) {
- if (!(t is ConstantExpression)) {
- return false;
- }
- tests++;
- }
- }
-
- // Must have >= 7 labels for it to be worth it.
- if (tests < 7) {
- return false;
- }
-
- // If we're in a DynamicMethod, we could just build the dictionary
- // immediately. But that would cause the two code paths to be more
- // different than they really need to be.
- var initializers = new List<ElementInit>(tests);
- var cases = new List<SwitchCase>(node.Cases.Count);
-
- int nullCase = -1;
- MethodInfo add = typeof(Dictionary<string, int>).GetMethod("Add", new[] { typeof(string), typeof(int) });
- for (int i = 0, n = node.Cases.Count; i < n; i++) {
- foreach (ConstantExpression t in node.Cases[i].TestValues) {
- if (t.Value != null) {
- initializers.Add(Expression.ElementInit(add, t, Expression.Constant(i)));
- } else {
- nullCase = i;
- }
- }
- cases.Add(Expression.SwitchCase(node.Cases[i].Body, Expression.Constant(i)));
- }
-
- // Create the field to hold the lazily initialized dictionary
- MemberExpression dictField = CreateLazyInitializedField<Dictionary<string, int>>("dictionarySwitch");
-
- // If we happen to initialize it twice (multithreaded case), it's
- // not the end of the world. The C# compiler does better here by
- // emitting a volatile access to the field.
- Expression dictInit = Expression.Condition(
- Expression.Equal(dictField, Expression.Constant(null, dictField.Type)),
- Expression.Assign(
- dictField,
- Expression.ListInit(
- Expression.New(
- typeof(Dictionary<string, int>).GetConstructor(new[] { typeof(int) }),
- Expression.Constant(initializers.Count)
- ),
- initializers
- )
- ),
- dictField
- );
-
- //
- // Create a tree like:
- //
- // switchValue = switchValueExpression;
- // if (switchValue == null) {
- // switchIndex = nullCase;
- // } else {
- // if (_dictField == null) {
- // _dictField = new Dictionary<string, int>(count) { { ... }, ... };
- // }
- // if (!_dictField.TryGetValue(switchValue, out switchIndex)) {
- // switchIndex = -1;
- // }
- // }
- // switch (switchIndex) {
- // case 0: ...
- // case 1: ...
- // ...
- // default:
- // }
- //
- var switchValue = Expression.Variable(typeof(string), "switchValue");
- var switchIndex = Expression.Variable(typeof(int), "switchIndex");
- var reduced = Expression.Block(
- new[] { switchIndex, switchValue },
- Expression.Assign(switchValue, node.SwitchValue),
- Expression.IfThenElse(
- Expression.Equal(switchValue, Expression.Constant(null, typeof(string))),
- Expression.Assign(switchIndex, Expression.Constant(nullCase)),
- Expression.IfThenElse(
- Expression.Call(dictInit, "TryGetValue", null, switchValue, switchIndex),
- Expression.Empty(),
- Expression.Assign(switchIndex, Expression.Constant(-1))
- )
- ),
- Expression.Switch(node.Type, switchIndex, node.DefaultBody, null, cases)
- );
-
- EmitExpression(reduced, flags);
- return true;
- }
-
- #endregion
-
- private void CheckRethrow() {
- // Rethrow is only valid inside a catch.
- for (LabelScopeInfo j = _labelBlock; j != null; j = j.Parent) {
- if (j.Kind == LabelScopeKind.Catch) {
- return;
- } else if (j.Kind == LabelScopeKind.Finally) {
- // Rethrow from inside finally is not verifiable
- break;
- }
- }
- throw Error.RethrowRequiresCatch();
- }
-
- #region TryStatement
-
- private void CheckTry() {
- // Try inside a filter is not verifiable
- for (LabelScopeInfo j = _labelBlock; j != null; j = j.Parent) {
- if (j.Kind == LabelScopeKind.Filter) {
- throw Error.TryNotAllowedInFilter();
- }
- }
- }
-
- private void EmitSaveExceptionOrPop(CatchBlock cb) {
- if (cb.Variable != null) {
- // If the variable is present, store the exception
- // in the variable.
- _scope.EmitSet(cb.Variable);
- } else {
- // Otherwise, pop it off the stack.
- _ilg.Emit(OpCodes.Pop);
- }
- }
-
- private void EmitTryExpression(Expression expr) {
- var node = (TryExpression)expr;
-
- CheckTry();
-
- //******************************************************************
- // 1. ENTERING TRY
- //******************************************************************
-
- PushLabelBlock(LabelScopeKind.Try);
- _ilg.BeginExceptionBlock();
-
- //******************************************************************
- // 2. Emit the try statement body
- //******************************************************************
-
- EmitExpression(node.Body);
-
- Type tryType = expr.Type;
- LocalBuilder value = null;
- if (tryType != typeof(void)) {
- //store the value of the try body
- value = GetLocal(tryType);
- _ilg.Emit(OpCodes.Stloc, value);
- }
- //******************************************************************
- // 3. Emit the catch blocks
- //******************************************************************
-
- foreach (CatchBlock cb in node.Handlers) {
- PushLabelBlock(LabelScopeKind.Catch);
-
- // Begin the strongly typed exception block
- if (cb.Filter == null) {
- _ilg.BeginCatchBlock(cb.Test);
- } else {
- _ilg.BeginExceptFilterBlock();
- }
-
- EnterScope(cb);
-
- EmitCatchStart(cb);
-
- //
- // Emit the catch block body
- //
- EmitExpression(cb.Body);
- if (tryType != typeof(void)) {
- //store the value of the catch block body
- _ilg.Emit(OpCodes.Stloc, value);
- }
-
- ExitScope(cb);
-
- PopLabelBlock(LabelScopeKind.Catch);
- }
-
- //******************************************************************
- // 4. Emit the finally block
- //******************************************************************
-
- if (node.Finally != null || node.Fault != null) {
- PushLabelBlock(LabelScopeKind.Finally);
-
- if (node.Finally != null) {
- _ilg.BeginFinallyBlock();
- } else {
- _ilg.BeginFaultBlock();
- }
-
- // Emit the body
- EmitExpressionAsVoid(node.Finally ?? node.Fault);
-
- _ilg.EndExceptionBlock();
- PopLabelBlock(LabelScopeKind.Finally);
- } else {
- _ilg.EndExceptionBlock();
- }
-
- if (tryType != typeof(void)) {
- _ilg.Emit(OpCodes.Ldloc, value);
- FreeLocal(value);
- }
- PopLabelBlock(LabelScopeKind.Try);
- }
-
- /// <summary>
- /// Emits the start of a catch block. The exception value that is provided by the
- /// CLR is stored in the variable specified by the catch block or popped if no
- /// variable is provided.
- /// </summary>
- private void EmitCatchStart(CatchBlock cb) {
- if (cb.Filter == null) {
- EmitSaveExceptionOrPop(cb);
- return;
- }
-
- // emit filter block. Filter blocks are untyped so we need to do
- // the type check ourselves.
- Label endFilter = _ilg.DefineLabel();
- Label rightType = _ilg.DefineLabel();
-
- // skip if it's not our exception type, but save
- // the exception if it is so it's available to the
- // filter
- _ilg.Emit(OpCodes.Isinst, cb.Test);
- _ilg.Emit(OpCodes.Dup);
- _ilg.Emit(OpCodes.Brtrue, rightType);
- _ilg.Emit(OpCodes.Pop);
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Br, endFilter);
-
- // it's our type, save it and emit the filter.
- _ilg.MarkLabel(rightType);
- EmitSaveExceptionOrPop(cb);
- PushLabelBlock(LabelScopeKind.Filter);
- EmitExpression(cb.Filter);
- PopLabelBlock(LabelScopeKind.Filter);
-
- // begin the catch, clear the exception, we've
- // already saved it
- _ilg.MarkLabel(endFilter);
- _ilg.BeginCatchBlock(null);
- _ilg.Emit(OpCodes.Pop);
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Unary.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Unary.cs
deleted file mode 100644
index 79726b09a0d..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Unary.cs
+++ /dev/null
@@ -1,344 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Reflection.Emit;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- partial class LambdaCompiler {
-
- private void EmitQuoteUnaryExpression(Expression expr) {
- EmitQuote((UnaryExpression)expr);
- }
-
-
- private void EmitQuote(UnaryExpression quote) {
- // emit the quoted expression as a runtime constant
- EmitConstant(quote.Operand, quote.Type);
-
- // Heuristic: only emit the tree rewrite logic if we have hoisted
- // locals.
- if (_scope.NearestHoistedLocals != null) {
- // HoistedLocals is internal so emit as System.Object
- EmitConstant(_scope.NearestHoistedLocals, typeof(object));
- _scope.EmitGet(_scope.NearestHoistedLocals.SelfVariable);
- _ilg.Emit(OpCodes.Call, typeof(RuntimeOps).GetMethod("Quote"));
-
- if (quote.Type != typeof(Expression)) {
- _ilg.Emit(OpCodes.Castclass, quote.Type);
- }
- }
- }
-
- private void EmitThrowUnaryExpression(Expression expr) {
- EmitThrow((UnaryExpression)expr, CompilationFlags.EmitAsDefaultType);
- }
-
- private void EmitThrow(UnaryExpression expr, CompilationFlags flags) {
- if (expr.Operand == null) {
- CheckRethrow();
-
- _ilg.Emit(OpCodes.Rethrow);
- } else {
- EmitExpression(expr.Operand);
- _ilg.Emit(OpCodes.Throw);
- }
-
- EmitUnreachable(expr, flags);
- }
-
- private void EmitUnaryExpression(Expression expr, CompilationFlags flags) {
- EmitUnary((UnaryExpression)expr, flags);
- }
-
- private void EmitUnary(UnaryExpression node, CompilationFlags flags) {
- if (node.Method != null) {
- EmitUnaryMethod(node, flags);
- } else if (node.NodeType == ExpressionType.NegateChecked && TypeUtils.IsInteger(node.Operand.Type)) {
- EmitExpression(node.Operand);
- LocalBuilder loc = GetLocal(node.Operand.Type);
- _ilg.Emit(OpCodes.Stloc, loc);
- _ilg.EmitInt(0);
- _ilg.EmitConvertToType(typeof(int), node.Operand.Type, false);
- _ilg.Emit(OpCodes.Ldloc, loc);
- FreeLocal(loc);
- EmitBinaryOperator(ExpressionType.SubtractChecked, node.Operand.Type, node.Operand.Type, node.Type, false);
- } else {
- EmitExpression(node.Operand);
- EmitUnaryOperator(node.NodeType, node.Operand.Type, node.Type);
- }
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- private void EmitUnaryOperator(ExpressionType op, Type operandType, Type resultType) {
- bool operandIsNullable = TypeUtils.IsNullableType(operandType);
-
- if (op == ExpressionType.ArrayLength) {
- _ilg.Emit(OpCodes.Ldlen);
- return;
- }
-
- if (operandIsNullable) {
- switch (op) {
- case ExpressionType.Not: {
- if (operandType != typeof(bool?)) {
- goto case ExpressionType.Negate;
- }
- Label labEnd = _ilg.DefineLabel();
- LocalBuilder loc = GetLocal(operandType);
-
- // store values (reverse order since they are already on the stack)
- _ilg.Emit(OpCodes.Stloc, loc);
-
- // test for null
- _ilg.Emit(OpCodes.Ldloca, loc);
- _ilg.EmitHasValue(operandType);
- _ilg.Emit(OpCodes.Brfalse_S, labEnd);
-
- // do op on non-null value
- _ilg.Emit(OpCodes.Ldloca, loc);
- _ilg.EmitGetValueOrDefault(operandType);
- Type nnOperandType = TypeUtils.GetNonNullableType(operandType);
- EmitUnaryOperator(op, nnOperandType, typeof(bool));
-
- // construct result
- ConstructorInfo ci = resultType.GetConstructor(new Type[] { typeof(bool) });
- _ilg.Emit(OpCodes.Newobj, ci);
- _ilg.Emit(OpCodes.Stloc, loc);
-
- _ilg.MarkLabel(labEnd);
- _ilg.Emit(OpCodes.Ldloc, loc);
- FreeLocal(loc);
- return;
- }
- case ExpressionType.UnaryPlus:
- case ExpressionType.NegateChecked:
- case ExpressionType.Negate:
- case ExpressionType.Increment:
- case ExpressionType.Decrement:
- case ExpressionType.OnesComplement:
- case ExpressionType.IsFalse:
- case ExpressionType.IsTrue: {
- Debug.Assert(TypeUtils.AreEquivalent(operandType, resultType));
- Label labIfNull = _ilg.DefineLabel();
- Label labEnd = _ilg.DefineLabel();
- LocalBuilder loc = GetLocal(operandType);
-
- // check for null
- _ilg.Emit(OpCodes.Stloc, loc);
- _ilg.Emit(OpCodes.Ldloca, loc);
- _ilg.EmitHasValue(operandType);
- _ilg.Emit(OpCodes.Brfalse_S, labIfNull);
-
- // apply operator to non-null value
- _ilg.Emit(OpCodes.Ldloca, loc);
- _ilg.EmitGetValueOrDefault(operandType);
- Type nnOperandType = TypeUtils.GetNonNullableType(resultType);
- EmitUnaryOperator(op, nnOperandType, nnOperandType);
-
- // construct result
- ConstructorInfo ci = resultType.GetConstructor(new Type[] { nnOperandType });
- _ilg.Emit(OpCodes.Newobj, ci);
- _ilg.Emit(OpCodes.Stloc, loc);
- _ilg.Emit(OpCodes.Br_S, labEnd);
-
- // if null then create a default one
- _ilg.MarkLabel(labIfNull);
- _ilg.Emit(OpCodes.Ldloca, loc);
- _ilg.Emit(OpCodes.Initobj, resultType);
-
- _ilg.MarkLabel(labEnd);
- _ilg.Emit(OpCodes.Ldloc, loc);
- FreeLocal(loc);
- return;
- }
- case ExpressionType.TypeAs:
- _ilg.Emit(OpCodes.Box, operandType);
- _ilg.Emit(OpCodes.Isinst, resultType);
- if (TypeUtils.IsNullableType(resultType)) {
- _ilg.Emit(OpCodes.Unbox_Any, resultType);
- }
- return;
- default:
- throw Error.UnhandledUnary(op);
- }
- } else {
- switch (op) {
- case ExpressionType.Not:
- if (operandType == typeof(bool)) {
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- } else {
- _ilg.Emit(OpCodes.Not);
- }
- break;
- case ExpressionType.OnesComplement:
- _ilg.Emit(OpCodes.Not);
- break;
- case ExpressionType.IsFalse:
- _ilg.Emit(OpCodes.Ldc_I4_0);
- _ilg.Emit(OpCodes.Ceq);
- // Not an arithmetic operation -> no conversion
- return;
- case ExpressionType.IsTrue:
- _ilg.Emit(OpCodes.Ldc_I4_1);
- _ilg.Emit(OpCodes.Ceq);
- // Not an arithmetic operation -> no conversion
- return;
- case ExpressionType.UnaryPlus:
- _ilg.Emit(OpCodes.Nop);
- break;
- case ExpressionType.Negate:
- case ExpressionType.NegateChecked:
- _ilg.Emit(OpCodes.Neg);
- break;
- case ExpressionType.TypeAs:
- if (operandType.IsValueType) {
- _ilg.Emit(OpCodes.Box, operandType);
- }
- _ilg.Emit(OpCodes.Isinst, resultType);
- if (TypeUtils.IsNullableType(resultType)) {
- _ilg.Emit(OpCodes.Unbox_Any, resultType);
- }
- // Not an arithmetic operation -> no conversion
- return;
- case ExpressionType.Increment:
- EmitConstantOne(resultType);
- _ilg.Emit(OpCodes.Add);
- break;
- case ExpressionType.Decrement:
- EmitConstantOne(resultType);
- _ilg.Emit(OpCodes.Sub);
- break;
- default:
- throw Error.UnhandledUnary(op);
- }
-
- EmitConvertArithmeticResult(op, resultType);
- }
- }
-
- private void EmitConstantOne(Type type) {
- switch (Type.GetTypeCode(type)) {
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- case TypeCode.Int16:
- case TypeCode.Int32:
- _ilg.Emit(OpCodes.Ldc_I4_1);
- break;
- case TypeCode.Int64:
- case TypeCode.UInt64:
- _ilg.Emit(OpCodes.Ldc_I8, (long)1);
- break;
- case TypeCode.Single:
- _ilg.Emit(OpCodes.Ldc_R4, 1.0f);
- break;
- case TypeCode.Double:
- _ilg.Emit(OpCodes.Ldc_R8, 1.0d);
- break;
- default:
- // we only have to worry about aritmetic types, see
- // TypeUtils.IsArithmetic
- throw ContractUtils.Unreachable;
- }
- }
-
- private void EmitUnboxUnaryExpression(Expression expr) {
- var node = (UnaryExpression)expr;
- Debug.Assert(node.Type.IsValueType && !TypeUtils.IsNullableType(node.Type));
-
- // Unbox_Any leaves the value on the stack
- EmitExpression(node.Operand);
- _ilg.Emit(OpCodes.Unbox_Any, node.Type);
- }
-
- private void EmitConvertUnaryExpression(Expression expr, CompilationFlags flags) {
- EmitConvert((UnaryExpression)expr, flags);
- }
-
- private void EmitConvert(UnaryExpression node, CompilationFlags flags) {
- if (node.Method != null) {
- // User-defined conversions are only lifted if both source and
- // destination types are value types. The C# compiler gets this wrong.
- // In C#, if you have an implicit conversion from int->MyClass and you
- // "lift" the conversion to int?->MyClass then a null int? goes to a
- // null MyClass. This is contrary to the specification, which states
- // that the correct behaviour is to unwrap the int?, throw an exception
- // if it is null, and then call the conversion.
- //
- // We cannot fix this in C# but there is no reason why we need to
- // propagate this bug into the expression tree API. Unfortunately
- // this means that when the C# compiler generates the lambda
- // (int? i)=>(MyClass)i, we will get different results for converting
- // that lambda to a delegate directly and converting that lambda to
- // an expression tree and then compiling it. We can live with this
- // discrepancy however.
-
- if (node.IsLifted && (!node.Type.IsValueType || !node.Operand.Type.IsValueType)) {
- ParameterInfo[] pis = node.Method.GetParametersCached();
- Debug.Assert(pis != null && pis.Length == 1);
- Type paramType = pis[0].ParameterType;
- if (paramType.IsByRef) {
- paramType = paramType.GetElementType();
- }
-
- UnaryExpression e = Expression.Convert(
- Expression.Call(
- node.Method,
- Expression.Convert(node.Operand, pis[0].ParameterType)
- ),
- node.Type
- );
-
- EmitConvert(e, flags);
- } else {
- EmitUnaryMethod(node, flags);
- }
- } else if (node.Type == typeof(void)) {
- EmitExpressionAsVoid(node.Operand, flags);
- } else {
- if (TypeUtils.AreEquivalent(node.Operand.Type, node.Type)) {
- EmitExpression(node.Operand, flags);
- } else {
- // A conversion is emitted after emitting the operand, no tail call is emitted
- EmitExpression(node.Operand);
- _ilg.EmitConvertToType(node.Operand.Type, node.Type, node.NodeType == ExpressionType.ConvertChecked);
- }
- }
- }
-
-
- private void EmitUnaryMethod(UnaryExpression node, CompilationFlags flags) {
- if (node.IsLifted) {
- ParameterExpression v = Expression.Variable(TypeUtils.GetNonNullableType(node.Operand.Type), null);
- MethodCallExpression mc = Expression.Call(node.Method, v);
-
- Type resultType = TypeUtils.GetNullableType(mc.Type);
- EmitLift(node.NodeType, resultType, mc, new ParameterExpression[] { v }, new Expression[] { node.Operand });
- _ilg.EmitConvertToType(resultType, node.Type, false);
- } else {
- EmitMethodCallExpression(Expression.Call(node.Method, node.Operand), flags);
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.cs
deleted file mode 100644
index 3c13eac7020..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.cs
+++ /dev/null
@@ -1,327 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Reflection.Emit;
-using System.Runtime.CompilerServices;
-using System.Threading;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
-#if !FEATURE_CORE_DLR || SILVERLIGHT
- using ILGenerator = OffsetTrackingILGenerator;
-#endif
-
- /// <summary>
- /// LambdaCompiler is responsible for compiling individual lambda (LambdaExpression). The complete tree may
- /// contain multiple lambdas, the Compiler class is reponsible for compiling the whole tree, individual
- /// lambdas are then compiled by the LambdaCompiler.
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
- internal sealed partial class LambdaCompiler {
-
- private delegate void WriteBack();
-
- // Information on the entire lambda tree currently being compiled
- private readonly AnalyzedTree _tree;
-
- private readonly ILGenerator _ilg;
-
-#if FEATURE_REFEMIT
- // The TypeBuilder backing this method, if any
- private readonly TypeBuilder _typeBuilder;
-#endif
- private readonly MethodInfo _method;
-
- // Currently active LabelTargets and their mapping to IL labels
- private LabelScopeInfo _labelBlock = new LabelScopeInfo(null, LabelScopeKind.Lambda);
- // Mapping of labels used for "long" jumps (jumping out and into blocks)
- private readonly Dictionary<LabelTarget, LabelInfo> _labelInfo = new Dictionary<LabelTarget, LabelInfo>();
-
- // The currently active variable scope
- private CompilerScope _scope;
-
- // The lambda we are compiling
- private readonly LambdaExpression _lambda;
-
- // True if the method's first argument is of type Closure
- private readonly bool _hasClosureArgument;
-
- // True if we want to emitting debug symbols
- private bool EmitDebugSymbols { get { return _tree.DebugInfoGenerator != null; } }
-
- // Runtime constants bound to the delegate
- private readonly BoundConstants _boundConstants;
-
- // Free list of locals, so we reuse them rather than creating new ones
- private readonly KeyedQueue<Type, LocalBuilder> _freeLocals = new KeyedQueue<Type, LocalBuilder>();
-
- /// <summary>
- /// The value is true if a clearance was emitted and no new sequence point
- /// has been emitted since that.
- /// </summary>
- bool _sequencePointCleared;
-
- /// <summary>
- /// Creates a lambda compiler that will compile to a dynamic method
- /// </summary>
- private LambdaCompiler(AnalyzedTree tree, LambdaExpression lambda) {
- Type[] parameterTypes = GetParameterTypes(lambda).AddFirst(typeof(Closure));
-
-#if (SILVERLIGHT && CLR2) || WP75
- var method = new DynamicMethod(lambda.Name ?? "lambda_method", lambda.ReturnType, parameterTypes);
-#else
- var method = new DynamicMethod(lambda.Name ?? "lambda_method", lambda.ReturnType, parameterTypes, true);
-#endif
-
- _tree = tree;
- _lambda = lambda;
- _method = method;
-
-#if !FEATURE_CORE_DLR || SILVERLIGHT
- _ilg = new OffsetTrackingILGenerator(method.GetILGenerator());
-#else
- _ilg = method.GetILGenerator();
-#endif
-
- _hasClosureArgument = true;
-
- // These are populated by AnalyzeTree/VariableBinder
- _scope = tree.Scopes[lambda];
- _boundConstants = tree.Constants[lambda];
-
- InitializeMethod();
- }
-
-#if FEATURE_REFEMIT
- /// <summary>
- /// Creates a lambda compiler that will compile into the provided Methodbuilder
- /// </summary>
- private LambdaCompiler(AnalyzedTree tree, LambdaExpression lambda, MethodBuilder method) {
- _hasClosureArgument = tree.Scopes[lambda].NeedsClosure;
- Type[] paramTypes = GetParameterTypes(lambda);
- if (_hasClosureArgument) {
- paramTypes = paramTypes.AddFirst(typeof(Closure));
- }
-
- method.SetReturnType(lambda.ReturnType);
- method.SetParameters(paramTypes);
- var paramNames = lambda.Parameters.Map(p => p.Name);
- // parameters are index from 1, with closure argument we need to skip the first arg
- int startIndex = _hasClosureArgument ? 2 : 1;
- for (int i = 0; i < paramNames.Length; i++) {
- method.DefineParameter(i + startIndex, ParameterAttributes.None, paramNames[i]);
- }
-
- _tree = tree;
- _lambda = lambda;
- _typeBuilder = (TypeBuilder)method.DeclaringType;
- _method = method;
-
-#if !FEATURE_CORE_DLR || SILVERLIGHT
- _ilg = new OffsetTrackingILGenerator(method.GetILGenerator());
-#else
- _ilg = method.GetILGenerator();
-#endif
-
- // These are populated by AnalyzeTree/VariableBinder
- _scope = tree.Scopes[lambda];
- _boundConstants = tree.Constants[lambda];
-
- InitializeMethod();
- }
-#endif
-
- /// <summary>
- /// Creates a lambda compiler for an inlined lambda
- /// </summary>
- private LambdaCompiler(LambdaCompiler parent, LambdaExpression lambda) {
- _tree = parent._tree;
- _lambda = lambda;
- _method = parent._method;
- _ilg = parent._ilg;
- _hasClosureArgument = parent._hasClosureArgument;
- _scope = _tree.Scopes[lambda];
- _boundConstants = parent._boundConstants;
-#if FEATURE_REFEMIT
- _typeBuilder = parent._typeBuilder;
-#endif
- }
-
- private void InitializeMethod() {
- // See if we can find a return label, so we can emit better IL
- AddReturnLabel(_lambda);
- _boundConstants.EmitCacheConstants(this);
- }
-
- public override string ToString() {
- return _method.ToString();
- }
-
- internal ILGenerator IL {
- get { return _ilg; }
- }
-
- internal ReadOnlyCollection<ParameterExpression> Parameters {
- get { return _lambda.Parameters; }
- }
-
- internal bool CanEmitBoundConstants {
- get { return _method is DynamicMethod; }
- }
-
- #region Compiler entry points
-
- /// <summary>
- /// Compiler entry point
- /// </summary>
- /// <param name="lambda">LambdaExpression to compile.</param>
- /// <param name="debugInfoGenerator">Debug info generator.</param>
- /// <returns>The compiled delegate.</returns>
- internal static Delegate Compile(LambdaExpression lambda, DebugInfoGenerator debugInfoGenerator) {
- // 1. Bind lambda
- AnalyzedTree tree = AnalyzeLambda(ref lambda);
-
- tree.DebugInfoGenerator = debugInfoGenerator;
-
- // 2. Create lambda compiler
- LambdaCompiler c = new LambdaCompiler(tree, lambda);
-
- // 3. Emit
- c.EmitLambdaBody();
-
- // 4. Return the delegate.
- return c.CreateDelegate();
- }
-
-#if FEATURE_REFEMIT
- /// <summary>
- /// Mutates the MethodBuilder parameter, filling in IL, parameters,
- /// and return type.
- ///
- /// (probably shouldn't be modifying parameters/return type...)
- /// </summary>
- internal static void Compile(LambdaExpression lambda, MethodBuilder method, DebugInfoGenerator debugInfoGenerator) {
- // 1. Bind lambda
- AnalyzedTree tree = AnalyzeLambda(ref lambda);
-
- tree.DebugInfoGenerator = debugInfoGenerator;
-
- // 2. Create lambda compiler
- LambdaCompiler c = new LambdaCompiler(tree, lambda, method);
-
- // 3. Emit
- c.EmitLambdaBody();
- }
-#endif
- #endregion
-
- private static AnalyzedTree AnalyzeLambda(ref LambdaExpression lambda) {
- // Spill the stack for any exception handling blocks or other
- // constructs which require entering with an empty stack
- lambda = StackSpiller.AnalyzeLambda(lambda);
-
- // Bind any variable references in this lambda
- return VariableBinder.Bind(lambda);
- }
-
- internal LocalBuilder GetLocal(Type type) {
- Debug.Assert(type != null);
-
- LocalBuilder local;
- if (_freeLocals.TryDequeue(type, out local)) {
- Debug.Assert(type == local.LocalType);
- return local;
- }
-
- return _ilg.DeclareLocal(type);
- }
-
- internal void FreeLocal(LocalBuilder local) {
- if (local != null) {
- _freeLocals.Enqueue(local.LocalType, local);
- }
- }
-
- internal LocalBuilder GetNamedLocal(Type type, ParameterExpression variable) {
- Debug.Assert(type != null && variable != null);
-
- LocalBuilder lb = _ilg.DeclareLocal(type);
- if (EmitDebugSymbols && variable.Name != null) {
- _tree.DebugInfoGenerator.SetLocalName(lb, variable.Name);
- }
- return lb;
- }
-
- /// <summary>
- /// Gets the argument slot corresponding to the parameter at the given
- /// index. Assumes that the method takes a certain number of prefix
- /// arguments, followed by the real parameters stored in Parameters
- /// </summary>
- internal int GetLambdaArgument(int index) {
- return index + (_hasClosureArgument ? 1 : 0) + (_method.IsStatic ? 0 : 1);
- }
-
- /// <summary>
- /// Returns the index-th argument. This method provides access to the actual arguments
- /// defined on the lambda itself, and excludes the possible 0-th closure argument.
- /// </summary>
- internal void EmitLambdaArgument(int index) {
- _ilg.EmitLoadArg(GetLambdaArgument(index));
- }
-
- internal void EmitClosureArgument() {
- Debug.Assert(_hasClosureArgument, "must have a Closure argument");
- Debug.Assert(_method.IsStatic, "must be a static method");
- _ilg.EmitLoadArg(0);
- }
-
- private Delegate CreateDelegate() {
- Debug.Assert(_method is DynamicMethod);
-
- return _method.CreateDelegate(_lambda.Type, new Closure(_boundConstants.ToArray(), null));
- }
-
-#if FEATURE_REFEMIT
- private FieldBuilder CreateStaticField(string name, Type type) {
- // We are emitting into someone else's type. We don't want name
- // conflicts, so choose a long name that is unlikely to confict.
- // Naming scheme chosen here is similar to what the C# compiler
- // uses.
- return _typeBuilder.DefineField("<ExpressionCompilerImplementationDetails>{" + Interlocked.Increment(ref _Counter) + "}" + name, type, FieldAttributes.Static | FieldAttributes.Private);
- }
-#endif
- /// <summary>
- /// Creates an unitialized field suitible for private implementation details
- /// Works with DynamicMethods or TypeBuilders.
- /// </summary>
- private MemberExpression CreateLazyInitializedField<T>(string name) {
-#if FEATURE_REFEMIT
- if (!(_method is DynamicMethod)) {
- return Expression.Field(null, CreateStaticField(name, typeof(T)));
- }
-#endif
- return Expression.Field(Expression.Constant(new StrongBox<T>(default(T))), "Value");
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/OffsetTrackingILGenerator.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/OffsetTrackingILGenerator.cs
deleted file mode 100644
index 024cfb90aff..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/OffsetTrackingILGenerator.cs
+++ /dev/null
@@ -1,366 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Reflection.Emit;
-using System.Diagnostics.SymbolStore;
-
-// Not needed in CLR 4 builds because we have the
-// ILGenerator.ILOffset property.
-
-#if !FEATURE_CORE_DLR || SILVERLIGHT
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- /// <summary>
- /// Wraps ILGenerator with code that tracks the current IL offset as instructions are emitted into the IL stream.
- /// </summary>
- internal sealed class OffsetTrackingILGenerator {
- private readonly ILGenerator _ilg;
- internal int _offset;
-
- internal int ILOffset { get { return _offset; } }
-
- internal OffsetTrackingILGenerator(ILGenerator ilg) {
- Debug.Assert(ilg != null);
- _ilg = ilg;
- }
-
- private void AdvanceOffset(OpCode opcode) {
- _offset += opcode.Size;
- }
-
- private void AdvanceOffsetWithLabel(OpCode opcode) {
- AdvanceOffset(opcode);
- if (OpCodes.TakesSingleByteArgument(opcode)) {
- _offset++;
- } else {
- _offset += 4;
- }
- }
-
- #region Simple Instructions
-
- internal void Emit(OpCode opcode) {
- _ilg.Emit(opcode);
- AdvanceOffset(opcode);
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, byte arg) {
- _ilg.Emit(opcode, arg);
- AdvanceOffset(opcode);
- _offset++;
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, sbyte arg) {
- _ilg.Emit(opcode, arg);
- AdvanceOffset(opcode);
- _offset++;
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, int arg) {
- _ilg.Emit(opcode, arg);
- AdvanceOffset(opcode);
- _offset += 4;
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, MethodInfo meth) {
- _ilg.Emit(opcode, meth);
- AdvanceOffset(opcode);
- _offset += 4;
- AssertOffsetMatches();
- }
-
- internal void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) {
- _ilg.EmitCall(opcode, methodInfo, optionalParameterTypes);
- AdvanceOffset(opcode);
- _offset += 4;
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, ConstructorInfo con) {
- _ilg.Emit(opcode, con);
- AdvanceOffset(opcode);
- _offset += 4;
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, Type cls) {
- _ilg.Emit(opcode, cls);
- AdvanceOffset(opcode);
- _offset += 4;
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, long arg) {
- _ilg.Emit(opcode, arg);
- AdvanceOffset(opcode);
- _offset += 8;
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, float arg) {
- _ilg.Emit(opcode, arg);
- AdvanceOffset(opcode);
- _offset += 4;
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, double arg) {
- _ilg.Emit(opcode, arg);
- AdvanceOffset(opcode);
- _offset += 8;
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, Label label) {
- _ilg.Emit(opcode, label);
- AdvanceOffsetWithLabel(opcode);
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, Label[] labels) {
- _ilg.Emit(opcode, labels);
- AdvanceOffset(opcode);
- _offset += 4;
- for (int remaining = labels.Length * 4, i = 0; remaining > 0; remaining -= 4, i++) {
- _offset += 4;
- }
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, FieldInfo field) {
- _ilg.Emit(opcode, field);
- AdvanceOffset(opcode);
- _offset += 4;
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, String str) {
- _ilg.Emit(opcode, str);
- AdvanceOffset(opcode);
- _offset += 4;
- AssertOffsetMatches();
- }
-
- internal void Emit(OpCode opcode, LocalBuilder local) {
- _ilg.Emit(opcode, local);
- int tempVal = local.LocalIndex;
- if (opcode.Equals(OpCodes.Ldloc)) {
- switch (tempVal) {
- case 0:
- opcode = OpCodes.Ldloc_0;
- break;
- case 1:
- opcode = OpCodes.Ldloc_1;
- break;
- case 2:
- opcode = OpCodes.Ldloc_2;
- break;
- case 3:
- opcode = OpCodes.Ldloc_3;
- break;
- default:
- if (tempVal <= 255)
- opcode = OpCodes.Ldloc_S;
- break;
- }
- } else if (opcode.Equals(OpCodes.Stloc)) {
- switch (tempVal) {
- case 0:
- opcode = OpCodes.Stloc_0;
- break;
- case 1:
- opcode = OpCodes.Stloc_1;
- break;
- case 2:
- opcode = OpCodes.Stloc_2;
- break;
- case 3:
- opcode = OpCodes.Stloc_3;
- break;
- default:
- if (tempVal <= 255)
- opcode = OpCodes.Stloc_S;
- break;
- }
- } else if (opcode.Equals(OpCodes.Ldloca)) {
- if (tempVal <= 255)
- opcode = OpCodes.Ldloca_S;
- }
-
- AdvanceOffset(opcode);
-
- if (opcode.OperandType == OperandType.InlineNone)
- return;
- else if (!OpCodes.TakesSingleByteArgument(opcode)) {
- _offset += 2;
- } else {
- _offset++;
- }
- AssertOffsetMatches();
- }
-
- #endregion
-
- #region Exception Handling
-
- private enum ExceptionState {
- Try = 0,
- Filter = 1,
- Catch = 2,
- Finally = 3,
- Fault = 4,
- }
-
- private Stack<ExceptionState> _exceptionState = new Stack<ExceptionState>();
-
- internal void BeginExceptionBlock() {
- _ilg.BeginExceptionBlock();
- _exceptionState.Push(ExceptionState.Try);
- AssertOffsetMatches();
- }
-
- internal void EndExceptionBlock() {
- _ilg.EndExceptionBlock();
-
- ExceptionState state = _exceptionState.Pop();
- if (state == ExceptionState.Catch) {
- AdvanceOffsetWithLabel(OpCodes.Leave);
- } else if (state == ExceptionState.Finally || state == ExceptionState.Fault) {
- AdvanceOffset(OpCodes.Endfinally);
- }
-
- AssertOffsetMatches();
- }
-
- internal void BeginExceptFilterBlock() {
- _ilg.BeginExceptFilterBlock();
-
- _exceptionState.Pop();
- _exceptionState.Push(ExceptionState.Filter);
-
- AssertOffsetMatches();
- }
-
- internal void BeginCatchBlock(Type exceptionType) {
- _ilg.BeginCatchBlock(exceptionType);
-
- ExceptionState state = _exceptionState.Pop();
- if (state == ExceptionState.Filter) {
- AdvanceOffset(OpCodes.Endfilter);
- } else {
- AdvanceOffsetWithLabel(OpCodes.Leave);
- }
-
- _exceptionState.Push(ExceptionState.Catch);
-
- AssertOffsetMatches();
- }
-
- internal void BeginFaultBlock() {
- _ilg.BeginFaultBlock();
-
- AdvanceOffsetWithLabel(OpCodes.Leave);
- _exceptionState.Pop();
- _exceptionState.Push(ExceptionState.Fault);
-
- AssertOffsetMatches();
- }
-
- internal void BeginFinallyBlock() {
- _ilg.BeginFinallyBlock();
-
- ExceptionState state = _exceptionState.Pop();
- if (state != ExceptionState.Try) {
- // leave for any preceeding catch clause
- AdvanceOffsetWithLabel(OpCodes.Leave);
- }
-
- // leave for try clause
- AdvanceOffsetWithLabel(OpCodes.Leave);
- _exceptionState.Push(ExceptionState.Finally);
-
- AssertOffsetMatches();
- }
-
- #endregion
-
- #region Labels and Locals
-
- internal Label DefineLabel() {
- return _ilg.DefineLabel();
- }
-
- internal void MarkLabel(Label loc) {
- _ilg.MarkLabel(loc);
- }
-
- internal LocalBuilder DeclareLocal(Type localType) {
- return _ilg.DeclareLocal(localType);
- }
-
- internal void MarkSequencePoint(ISymbolDocumentWriter document, int startLine, int startColumn, int endLine, int endColumn) {
- _ilg.MarkSequencePoint(document, startLine, startColumn, endLine, endColumn);
- }
-
- #endregion
-
- #region Assertions
-
-#if STRESS_DEBUG
- private FieldInfo _ilgOffsetField;
- private bool _checkOffset = true;
-#endif
-
- [Conditional("STRESS_DEBUG")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
- private void AssertOffsetMatches() {
-#if STRESS_DEBUG
- if (!_checkOffset) {
- return;
- }
-
- int m_length = -1;
- try {
- if (_ilgOffsetField == null) {
- _ilgOffsetField = typeof(ILGenerator).GetField("m_length", BindingFlags.NonPublic | BindingFlags.Instance);
- }
- m_length = (int)_ilgOffsetField.GetValue(_ilg);
- } catch (Exception) {
- _checkOffset = false;
- }
-
- if (_checkOffset) {
- Debug.Assert(m_length == _offset);
- }
-#endif
- }
-
- #endregion
- }
-}
-
-#endif
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/RuntimeVariableList.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/RuntimeVariableList.cs
deleted file mode 100644
index 3b22542c2dc..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/RuntimeVariableList.cs
+++ /dev/null
@@ -1,123 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast.Compiler;
-#else
-using System.Linq.Expressions.Compiler;
-#endif
-
-using System.ComponentModel;
-using System.Diagnostics;
-
-namespace System.Runtime.CompilerServices {
-
- /// <summary>
- /// This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
- /// Contains helper methods called from dynamically generated methods.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never), DebuggerStepThrough]
- public static partial class RuntimeOps {
- /// <summary>
- /// Creates an interface that can be used to modify closed over variables at runtime.
- /// </summary>
- /// <param name="data">The closure array.</param>
- /// <param name="indexes">An array of indicies into the closure array where variables are found.</param>
- /// <returns>An interface to access variables.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static IRuntimeVariables CreateRuntimeVariables(object[] data, long[] indexes) {
- return new RuntimeVariableList(data, indexes);
- }
-
- /// <summary>
- /// Creates an interface that can be used to modify closed over variables at runtime.
- /// </summary>
- /// <returns>An interface to access variables.</returns>
- [Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
- public static IRuntimeVariables CreateRuntimeVariables() {
- return new EmptyRuntimeVariables();
- }
-
- private sealed class EmptyRuntimeVariables : IRuntimeVariables {
- int IRuntimeVariables.Count {
- get { return 0; }
- }
-
- object IRuntimeVariables.this[int index] {
- get {
- throw new ArgumentOutOfRangeException("index");
- }
- set {
- throw new ArgumentOutOfRangeException("index");
- }
- }
- }
-
- /// <summary>
- /// Provides a list of variables, supporing read/write of the values
- /// Exposed via RuntimeVariablesExpression
- /// </summary>
- private sealed class RuntimeVariableList : IRuntimeVariables {
- // The top level environment. It contains pointers to parent
- // environments, which are always in the first element
- private readonly object[] _data;
-
- // An array of (int, int) pairs, each representing how to find a
- // variable in the environment data struction.
- //
- // The first integer indicates the number of times to go up in the
- // closure chain, the second integer indicates the index into that
- // closure chain.
- private readonly long[] _indexes;
-
- internal RuntimeVariableList(object[] data, long[] indexes) {
- Debug.Assert(data != null);
- Debug.Assert(indexes != null);
-
- _data = data;
- _indexes = indexes;
- }
-
- public int Count {
- get { return _indexes.Length; }
- }
-
- public object this[int index] {
- get {
- return GetStrongBox(index).Value;
- }
- set {
- GetStrongBox(index).Value = value;
- }
- }
-
- private IStrongBox GetStrongBox(int index) {
- // We lookup the closure using two ints:
- // 1. The high dword is the number of parents to go up
- // 2. The low dword is the index into that array
- long closureKey = _indexes[index];
-
- // walk up the parent chain to find the real environment
- object[] result = _data;
- for (int parents = (int)(closureKey >> 32); parents > 0; parents--) {
- result = HoistedLocals.GetParent(result);
- }
-
- // Return the variable storage
- return (IStrongBox)result[(int)closureKey];
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/Set.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/Set.cs
deleted file mode 100644
index 4c864ad58fb..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/Set.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Collections;
-using System.Collections.Generic;
-
-// Note: can't move to Utils because name conflicts with System.Linq.Set
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- /// <summary>
- /// A simple hashset, built on Dictionary{K, V}
- /// </summary>
- internal sealed class Set<T> : ICollection<T> {
- private readonly Dictionary<T, object> _data;
-
- internal Set() {
- _data = new Dictionary<T, object>();
- }
-
- internal Set(IEqualityComparer<T> comparer) {
- _data = new Dictionary<T, object>(comparer);
- }
-
- internal Set(IList<T> list) {
- _data = new Dictionary<T, object>(list.Count);
- foreach (T t in list) {
- Add(t);
- }
- }
-
- internal Set(IEnumerable<T> list) {
- _data = new Dictionary<T, object>();
- foreach (T t in list) {
- Add(t);
- }
- }
-
- internal Set(int capacity) {
- _data = new Dictionary<T, object>(capacity);
- }
-
- public void Add(T item) {
- _data[item] = null;
- }
-
- public void Clear() {
- _data.Clear();
- }
-
- public bool Contains(T item) {
- return _data.ContainsKey(item);
- }
-
- public void CopyTo(T[] array, int arrayIndex) {
- _data.Keys.CopyTo(array, arrayIndex);
- }
-
- public int Count {
- get { return _data.Count; }
- }
-
- public bool IsReadOnly {
- get { return false; }
- }
-
- public bool Remove(T item) {
- return _data.Remove(item);
- }
-
- public IEnumerator<T> GetEnumerator() {
- return _data.Keys.GetEnumerator();
- }
-
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
- return _data.Keys.GetEnumerator();
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Bindings.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Bindings.cs
deleted file mode 100644
index 1c166a6ce4e..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Bindings.cs
+++ /dev/null
@@ -1,228 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Collections.ObjectModel;
-using System.Dynamic.Utils;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
-
- internal partial class StackSpiller {
-
- private abstract class BindingRewriter {
- protected MemberBinding _binding;
- protected RewriteAction _action;
- protected StackSpiller _spiller;
-
- internal BindingRewriter(MemberBinding binding, StackSpiller spiller) {
- _binding = binding;
- _spiller = spiller;
- }
-
- internal RewriteAction Action {
- get { return _action; }
- }
-
- internal abstract MemberBinding AsBinding();
- internal abstract Expression AsExpression(Expression target);
-
- internal static BindingRewriter Create(MemberBinding binding, StackSpiller spiller, Stack stack) {
- switch (binding.BindingType) {
- case MemberBindingType.Assignment:
- MemberAssignment assign = (MemberAssignment)binding;
- return new MemberAssignmentRewriter(assign, spiller, stack);
- case MemberBindingType.ListBinding:
- MemberListBinding list = (MemberListBinding)binding;
- return new ListBindingRewriter(list, spiller, stack);
- case MemberBindingType.MemberBinding:
- MemberMemberBinding member = (MemberMemberBinding)binding;
- return new MemberMemberBindingRewriter(member, spiller, stack);
- }
- throw Error.UnhandledBinding();
- }
- }
-
- private class MemberMemberBindingRewriter : BindingRewriter {
- ReadOnlyCollection<MemberBinding> _bindings;
- BindingRewriter[] _bindingRewriters;
-
- internal MemberMemberBindingRewriter(MemberMemberBinding binding, StackSpiller spiller, Stack stack) :
- base(binding, spiller) {
-
- _bindings = binding.Bindings;
- _bindingRewriters = new BindingRewriter[_bindings.Count];
- for (int i = 0; i < _bindings.Count; i++) {
- BindingRewriter br = BindingRewriter.Create(_bindings[i], spiller, stack);
- _action |= br.Action;
- _bindingRewriters[i] = br;
- }
- }
-
- internal override MemberBinding AsBinding() {
- switch (_action) {
- case RewriteAction.None:
- return _binding;
- case RewriteAction.Copy:
- MemberBinding[] newBindings = new MemberBinding[_bindings.Count];
- for (int i = 0; i < _bindings.Count; i++) {
- newBindings[i] = _bindingRewriters[i].AsBinding();
- }
- return Expression.MemberBind(_binding.Member, new TrueReadOnlyCollection<MemberBinding>(newBindings));
- }
- throw ContractUtils.Unreachable;
- }
-
- internal override Expression AsExpression(Expression target) {
- if (target.Type.IsValueType && _binding.Member is System.Reflection.PropertyInfo) {
- throw Error.CannotAutoInitializeValueTypeMemberThroughProperty(_binding.Member);
- }
- RequireNotRefInstance(target);
-
- MemberExpression member = Expression.MakeMemberAccess(target, _binding.Member);
- ParameterExpression memberTemp = _spiller.MakeTemp(member.Type);
-
- Expression[] block = new Expression[_bindings.Count + 2];
- block[0] = Expression.Assign(memberTemp, member);
-
- for (int i = 0; i < _bindings.Count; i++) {
- BindingRewriter br = _bindingRewriters[i];
- block[i + 1] = br.AsExpression(memberTemp);
- }
-
- // We need to copy back value types
- if (memberTemp.Type.IsValueType) {
- block[_bindings.Count + 1] = Expression.Block(
- typeof(void),
- Expression.Assign(Expression.MakeMemberAccess(target, _binding.Member), memberTemp)
- );
- } else {
- block[_bindings.Count + 1] = Expression.Empty();
- }
- return MakeBlock(block);
- }
- }
-
- private class ListBindingRewriter : BindingRewriter {
- ReadOnlyCollection<ElementInit> _inits;
- ChildRewriter[] _childRewriters;
-
- internal ListBindingRewriter(MemberListBinding binding, StackSpiller spiller, Stack stack) :
- base(binding, spiller) {
-
- _inits = binding.Initializers;
-
- _childRewriters = new ChildRewriter[_inits.Count];
- for (int i = 0; i < _inits.Count; i++) {
- ElementInit init = _inits[i];
-
- ChildRewriter cr = new ChildRewriter(spiller, stack, init.Arguments.Count);
- cr.Add(init.Arguments);
-
- _action |= cr.Action;
- _childRewriters[i] = cr;
- }
- }
-
- internal override MemberBinding AsBinding() {
- switch (_action) {
- case RewriteAction.None:
- return _binding;
- case RewriteAction.Copy:
- ElementInit[] newInits = new ElementInit[_inits.Count];
- for (int i = 0; i < _inits.Count; i++) {
- ChildRewriter cr = _childRewriters[i];
- if (cr.Action == RewriteAction.None) {
- newInits[i] = _inits[i];
- } else {
- newInits[i] = Expression.ElementInit(_inits[i].AddMethod, cr[0, -1]);
- }
- }
- return Expression.ListBind(_binding.Member, new TrueReadOnlyCollection<ElementInit>(newInits));
- }
- throw ContractUtils.Unreachable;
- }
-
- internal override Expression AsExpression(Expression target) {
- if (target.Type.IsValueType && _binding.Member is System.Reflection.PropertyInfo) {
- throw Error.CannotAutoInitializeValueTypeElementThroughProperty(_binding.Member);
- }
- RequireNotRefInstance(target);
-
- MemberExpression member = Expression.MakeMemberAccess(target, _binding.Member);
- ParameterExpression memberTemp = _spiller.MakeTemp(member.Type);
-
- Expression[] block = new Expression[_inits.Count + 2];
- block[0] = Expression.Assign(memberTemp, member);
-
- for (int i = 0; i < _inits.Count; i++) {
- ChildRewriter cr = _childRewriters[i];
- Result add = cr.Finish(Expression.Call(memberTemp, _inits[i].AddMethod, cr[0, -1]));
- block[i + 1] = add.Node;
- }
-
- // We need to copy back value types
- if (memberTemp.Type.IsValueType) {
- block[_inits.Count + 1] = Expression.Block(
- typeof(void),
- Expression.Assign(Expression.MakeMemberAccess(target, _binding.Member), memberTemp)
- );
- } else {
- block[_inits.Count + 1] = Expression.Empty();
- }
- return MakeBlock(block);
- }
- }
-
- private class MemberAssignmentRewriter : BindingRewriter {
- Expression _rhs;
-
- internal MemberAssignmentRewriter(MemberAssignment binding, StackSpiller spiller, Stack stack) :
- base(binding, spiller) {
-
- Result result = spiller.RewriteExpression(binding.Expression, stack);
- _action = result.Action;
- _rhs = result.Node;
- }
-
- internal override MemberBinding AsBinding() {
- switch (_action) {
- case RewriteAction.None:
- return _binding;
- case RewriteAction.Copy:
- return Expression.Bind(_binding.Member, _rhs);
- }
- throw ContractUtils.Unreachable;
- }
-
- internal override Expression AsExpression(Expression target) {
- RequireNotRefInstance(target);
-
- MemberExpression member = Expression.MakeMemberAccess(target, _binding.Member);
- ParameterExpression memberTemp = _spiller.MakeTemp(member.Type);
-
- return MakeBlock(
- Expression.Assign(memberTemp, _rhs),
- Expression.Assign(member, memberTemp),
- Expression.Empty()
- );
- }
- }
-
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Generated.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Generated.cs
deleted file mode 100644
index d0aea62ff84..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Generated.cs
+++ /dev/null
@@ -1,272 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- internal partial class StackSpiller {
-
- /// <summary>
- /// Rewrite the expression
- /// </summary>
- ///
- /// <param name="node">Expression to rewrite</param>
- /// <param name="stack">State of the stack before the expression is emitted.</param>
- /// <returns>Rewritten expression.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- private Result RewriteExpression(Expression node, Stack stack) {
- if (node == null) {
- return new Result(RewriteAction.None, null);
- }
-
- Result result;
- switch (node.NodeType) {
- #region Generated StackSpiller Switch
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_stackspiller_switch from: generate_tree.py
-
- case ExpressionType.Add:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.AddChecked:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.And:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.AndAlso:
- result = RewriteLogicalBinaryExpression(node, stack);
- break;
- case ExpressionType.ArrayLength:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.ArrayIndex:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.Call:
- result = RewriteMethodCallExpression(node, stack);
- break;
- case ExpressionType.Coalesce:
- result = RewriteLogicalBinaryExpression(node, stack);
- break;
- case ExpressionType.Conditional:
- result = RewriteConditionalExpression(node, stack);
- break;
- case ExpressionType.Convert:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.ConvertChecked:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.Divide:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.Equal:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.ExclusiveOr:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.GreaterThan:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.GreaterThanOrEqual:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.Invoke:
- result = RewriteInvocationExpression(node, stack);
- break;
- case ExpressionType.Lambda:
- result = RewriteLambdaExpression(node, stack);
- break;
- case ExpressionType.LeftShift:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.LessThan:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.LessThanOrEqual:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.ListInit:
- result = RewriteListInitExpression(node, stack);
- break;
- case ExpressionType.MemberAccess:
- result = RewriteMemberExpression(node, stack);
- break;
- case ExpressionType.MemberInit:
- result = RewriteMemberInitExpression(node, stack);
- break;
- case ExpressionType.Modulo:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.Multiply:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.MultiplyChecked:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.Negate:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.UnaryPlus:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.NegateChecked:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.New:
- result = RewriteNewExpression(node, stack);
- break;
- case ExpressionType.NewArrayInit:
- result = RewriteNewArrayExpression(node, stack);
- break;
- case ExpressionType.NewArrayBounds:
- result = RewriteNewArrayExpression(node, stack);
- break;
- case ExpressionType.Not:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.NotEqual:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.Or:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.OrElse:
- result = RewriteLogicalBinaryExpression(node, stack);
- break;
- case ExpressionType.Power:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.RightShift:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.Subtract:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.SubtractChecked:
- result = RewriteBinaryExpression(node, stack);
- break;
- case ExpressionType.TypeAs:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.TypeIs:
- result = RewriteTypeBinaryExpression(node, stack);
- break;
- case ExpressionType.Assign:
- result = RewriteAssignBinaryExpression(node, stack);
- break;
- case ExpressionType.Block:
- result = RewriteBlockExpression(node, stack);
- break;
- case ExpressionType.Decrement:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.Dynamic:
- result = RewriteDynamicExpression(node, stack);
- break;
- case ExpressionType.Extension:
- result = RewriteExtensionExpression(node, stack);
- break;
- case ExpressionType.Goto:
- result = RewriteGotoExpression(node, stack);
- break;
- case ExpressionType.Increment:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.Index:
- result = RewriteIndexExpression(node, stack);
- break;
- case ExpressionType.Label:
- result = RewriteLabelExpression(node, stack);
- break;
- case ExpressionType.Loop:
- result = RewriteLoopExpression(node, stack);
- break;
- case ExpressionType.Switch:
- result = RewriteSwitchExpression(node, stack);
- break;
- case ExpressionType.Throw:
- result = RewriteThrowUnaryExpression(node, stack);
- break;
- case ExpressionType.Try:
- result = RewriteTryExpression(node, stack);
- break;
- case ExpressionType.Unbox:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.TypeEqual:
- result = RewriteTypeBinaryExpression(node, stack);
- break;
- case ExpressionType.OnesComplement:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.IsTrue:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.IsFalse:
- result = RewriteUnaryExpression(node, stack);
- break;
- case ExpressionType.AddAssign:
- case ExpressionType.AndAssign:
- case ExpressionType.DivideAssign:
- case ExpressionType.ExclusiveOrAssign:
- case ExpressionType.LeftShiftAssign:
- case ExpressionType.ModuloAssign:
- case ExpressionType.MultiplyAssign:
- case ExpressionType.OrAssign:
- case ExpressionType.PowerAssign:
- case ExpressionType.RightShiftAssign:
- case ExpressionType.SubtractAssign:
- case ExpressionType.AddAssignChecked:
- case ExpressionType.MultiplyAssignChecked:
- case ExpressionType.SubtractAssignChecked:
- case ExpressionType.PreIncrementAssign:
- case ExpressionType.PreDecrementAssign:
- case ExpressionType.PostIncrementAssign:
- case ExpressionType.PostDecrementAssign:
- result = RewriteReducibleExpression(node, stack);
- break;
- case ExpressionType.Quote:
- case ExpressionType.Parameter:
- case ExpressionType.Constant:
- case ExpressionType.RuntimeVariables:
- case ExpressionType.Default:
- case ExpressionType.DebugInfo:
- return new Result(RewriteAction.None, node);
-
- // *** END GENERATED CODE ***
-
- #endregion
-
- default:
- throw ContractUtils.Unreachable;
- }
-
- VerifyRewrite(result, node);
-
- return result;
- }
- }
-}
-
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Temps.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Temps.cs
deleted file mode 100644
index fce1b961e57..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Temps.cs
+++ /dev/null
@@ -1,308 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
-
- internal partial class StackSpiller {
-
- private class TempMaker {
- /// <summary>
- /// Current temporary variable
- /// </summary>
- private int _temp;
-
- /// <summary>
- /// List of free temporary variables. These can be recycled for new temps.
- /// </summary>
- private List<ParameterExpression> _freeTemps;
-
- /// <summary>
- /// Stack of currently active temporary variables.
- /// </summary>
- private Stack<ParameterExpression> _usedTemps;
-
- /// <summary>
- /// List of all temps created by stackspiller for this rule/lambda
- /// </summary>
- private List<ParameterExpression> _temps = new List<ParameterExpression>();
-
- internal List<ParameterExpression> Temps {
- get { return _temps; }
- }
-
- internal ParameterExpression Temp(Type type) {
- ParameterExpression temp;
- if (_freeTemps != null) {
- // Recycle from the free-list if possible.
- for (int i = _freeTemps.Count - 1; i >= 0; i--) {
- temp = _freeTemps[i];
- if (temp.Type == type) {
- _freeTemps.RemoveAt(i);
- return UseTemp(temp);
- }
- }
- }
- // Not on the free-list, create a brand new one.
- temp = Expression.Variable(type, "$temp$" + _temp++);
- _temps.Add(temp);
- return UseTemp(temp);
- }
-
- private ParameterExpression UseTemp(ParameterExpression temp) {
- Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp));
- Debug.Assert(_usedTemps == null || !_usedTemps.Contains(temp));
-
- if (_usedTemps == null) {
- _usedTemps = new Stack<ParameterExpression>();
- }
- _usedTemps.Push(temp);
- return temp;
- }
-
- private void FreeTemp(ParameterExpression temp) {
- Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp));
- if (_freeTemps == null) {
- _freeTemps = new List<ParameterExpression>();
- }
- _freeTemps.Add(temp);
- }
-
- internal int Mark() {
- return _usedTemps != null ? _usedTemps.Count : 0;
- }
-
- // Free temporaries created since the last marking.
- // This is a performance optimization to lower the overall number of tempories needed.
- internal void Free(int mark) {
- // (_usedTemps != null) ==> (mark <= _usedTemps.Count)
- Debug.Assert(_usedTemps == null || mark <= _usedTemps.Count);
- // (_usedTemps == null) ==> (mark == 0)
- Debug.Assert(mark == 0 || _usedTemps != null);
-
- if (_usedTemps != null) {
- while (mark < _usedTemps.Count) {
- FreeTemp(_usedTemps.Pop());
- }
- }
- }
-
- [Conditional("DEBUG")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
- internal void VerifyTemps() {
- Debug.Assert(_usedTemps == null || _usedTemps.Count == 0);
- }
- }
-
-
- /// <summary>
- /// Rewrites child expressions, spilling them into temps if needed. The
- /// stack starts in the inital state, and after the first subexpression
- /// is added it is change to non-empty. This behavior can be overridden
- /// by setting the stack manually between adds.
- ///
- /// When all children have been added, the caller should rewrite the
- /// node if Rewrite is true. Then, it should call Finish with etiher
- /// the orignal expression or the rewritten expression. Finish will call
- /// Expression.Comma if necessary and return a new Result.
- /// </summary>
- private class ChildRewriter {
- private readonly StackSpiller _self;
- private readonly Expression[] _expressions;
- private int _expressionsCount;
- private List<Expression> _comma;
- private RewriteAction _action;
- private Stack _stack;
- private bool _done;
-
- internal ChildRewriter(StackSpiller self, Stack stack, int count) {
- _self = self;
- _stack = stack;
- _expressions = new Expression[count];
- }
-
- internal void Add(Expression node) {
- Debug.Assert(!_done);
-
- if (node == null) {
- _expressions[_expressionsCount++] = null;
- return;
- }
-
- Result exp = _self.RewriteExpression(node, _stack);
- _action |= exp.Action;
- _stack = Stack.NonEmpty;
-
- // track items in case we need to copy or spill stack
- _expressions[_expressionsCount++] = exp.Node;
- }
-
- internal void Add(IList<Expression> expressions) {
- for (int i = 0, count = expressions.Count; i < count; i++) {
- Add(expressions[i]);
- }
- }
-
- internal void AddArguments(IArgumentProvider expressions) {
- for (int i = 0, count = expressions.ArgumentCount; i < count; i++) {
- Add(expressions.GetArgument(i));
- }
- }
-
- private void EnsureDone() {
- // done adding arguments, build the comma if necessary
- if (!_done) {
- _done = true;
-
- if (_action == RewriteAction.SpillStack) {
- Expression[] clone = _expressions;
- int count = clone.Length;
- List<Expression> comma = new List<Expression>(count + 1);
- for (int i = 0; i < count; i++) {
- if (clone[i] != null) {
- Expression temp;
- clone[i] = _self.ToTemp(clone[i], out temp);
- comma.Add(temp);
- }
- }
- comma.Capacity = comma.Count + 1;
- _comma = comma;
- }
- }
- }
-
- internal bool Rewrite {
- get { return _action != RewriteAction.None; }
- }
-
- internal RewriteAction Action {
- get { return _action; }
- }
-
- internal Result Finish(Expression expr) {
- EnsureDone();
-
- if (_action == RewriteAction.SpillStack) {
- Debug.Assert(_comma.Capacity == _comma.Count + 1);
- _comma.Add(expr);
- expr = MakeBlock(_comma);
- }
-
- return new Result(_action, expr);
- }
-
- internal Expression this[int index] {
- get {
- EnsureDone();
- if (index < 0) {
- index += _expressions.Length;
- }
- return _expressions[index];
- }
- }
-
- internal Expression[] this[int first, int last] {
- get {
- EnsureDone();
- if (last < 0) {
- last += _expressions.Length;
- }
- int count = last - first + 1;
- ContractUtils.RequiresArrayRange(_expressions, first, count, "first", "last");
-
- if (count == _expressions.Length) {
- Debug.Assert(first == 0);
- // if the entire array is requested just return it so we don't make a new array
- return _expressions;
- }
-
- Expression[] clone = new Expression[count];
- Array.Copy(_expressions, first, clone, 0, count);
- return clone;
- }
- }
- }
-
-
- private ParameterExpression MakeTemp(Type type) {
- return _tm.Temp(type);
- }
-
- private int Mark() {
- return _tm.Mark();
- }
-
- private void Free(int mark) {
- _tm.Free(mark);
- }
-
- [Conditional("DEBUG")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
- private void VerifyTemps() {
- _tm.VerifyTemps();
- }
-
- /// <summary>
- /// Will perform:
- /// save: temp = expression
- /// return value: temp
- /// </summary>
- private ParameterExpression ToTemp(Expression expression, out Expression save) {
- ParameterExpression temp = MakeTemp(expression.Type);
- save = Expression.Assign(temp, expression);
- return temp;
- }
-
- /// <summary>
- /// Creates a special block that is marked as not allowing jumps in.
- /// This should not be used for rewriting BlockExpression itself, or
- /// anything else that supports jumping.
- /// </summary>
- private static Expression MakeBlock(params Expression[] expressions) {
- return MakeBlock((IList<Expression>)expressions);
- }
-
- /// <summary>
- /// Creates a special block that is marked as not allowing jumps in.
- /// This should not be used for rewriting BlockExpression itself, or
- /// anything else that supports jumping.
- /// </summary>
- private static Expression MakeBlock(IList<Expression> expressions) {
- return new SpilledExpressionBlock(expressions);
- }
- }
-
- /// <summary>
- /// A special subtype of BlockExpression that indicates to the compiler
- /// that this block is a spilled expression and should not allow jumps in.
- /// </summary>
- internal sealed class SpilledExpressionBlock : BlockN {
- internal SpilledExpressionBlock(IList<Expression> expressions)
- : base(expressions) {
- }
- internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) {
- throw ContractUtils.Unreachable;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.cs
deleted file mode 100644
index ff1077ce758..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.cs
+++ /dev/null
@@ -1,982 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
-
- /// <summary>
- /// Expression rewriting to spill the CLR stack into temporary variables
- /// in order to guarantee some properties of code generation, for
- /// example that we always enter try block on empty stack.
- /// </summary>
- internal partial class StackSpiller {
-
- // Is the evaluation stack empty?
- private enum Stack {
- Empty,
- NonEmpty
- };
-
- // Should the parent nodes be rewritten, and in what way?
- // Designed so bitwise-or produces the correct result when merging two
- // subtrees. In particular, SpillStack is preferred over Copy which is
- // preferred over None.
- //
- // Values:
- // None -> no rewrite needed
- // Copy -> copy into a new node
- // SpillStack -> spill stack into temps
- [Flags]
- private enum RewriteAction {
- None = 0,
- Copy = 1,
- SpillStack = 3,
- }
-
- // Result of a rewrite operation. Always contains an action and a node.
- private struct Result {
- internal readonly RewriteAction Action;
- internal readonly Expression Node;
-
- internal Result(RewriteAction action, Expression node) {
- Action = action;
- Node = node;
- }
- }
-
- /// <summary>
- /// The source of temporary variables
- /// </summary>
- private readonly TempMaker _tm = new TempMaker();
-
- /// <summary>
- /// Initial stack state. Normally empty, but when inlining the lambda
- /// we might have a non-empty starting stack state.
- /// </summary>
- private readonly Stack _startingStack;
-
- /// <summary>
- /// Lambda rewrite result. We need this for inlined lambdas to figure
- /// out whether we need to guarentee it an empty stack.
- /// </summary>
- private RewriteAction _lambdaRewrite;
-
- /// <summary>
- /// Analyzes a lambda, producing a new one that has correct invariants
- /// for codegen. In particular, it spills the IL stack to temps in
- /// places where it's invalid to have a non-empty stack (for example,
- /// entering a try statement).
- /// </summary>
- internal static LambdaExpression AnalyzeLambda(LambdaExpression lambda) {
- return lambda.Accept(new StackSpiller(Stack.Empty));
- }
-
- private StackSpiller(Stack stack) {
- _startingStack = stack;
- }
-
- // called by Expression<T>.Accept
- internal Expression<T> Rewrite<T>(Expression<T> lambda) {
- VerifyTemps();
-
- // Lambda starts with an empty stack
- Result body = RewriteExpressionFreeTemps(lambda.Body, _startingStack);
- _lambdaRewrite = body.Action;
-
- VerifyTemps();
-
- if (body.Action != RewriteAction.None) {
- // Create a new scope for temps
- // (none of these will be hoisted so there is no closure impact)
- Expression newBody = body.Node;
- if (_tm.Temps.Count > 0) {
- newBody = Expression.Block(_tm.Temps, newBody);
- }
-
- // Clone the lambda, replacing the body & variables
- return new Expression<T>(newBody, lambda.Name, lambda.TailCall, lambda.Parameters);
- }
-
- return lambda;
- }
-
- #region Expressions
-
- [Conditional("DEBUG")]
- private static void VerifyRewrite(Result result, Expression node) {
- Debug.Assert(result.Node != null);
-
- // (result.Action == RewriteAction.None) if and only if (node == result.Node)
- Debug.Assert((result.Action == RewriteAction.None) ^ (node != result.Node), "rewrite action does not match node object identity");
-
- // if the original node is an extension node, it should have been rewritten
- Debug.Assert(result.Node.NodeType != ExpressionType.Extension, "extension nodes must be rewritten");
-
- // if we have Copy, then node type must match
- Debug.Assert(
- result.Action != RewriteAction.Copy || node.NodeType == result.Node.NodeType || node.CanReduce,
- "rewrite action does not match node object kind"
- );
-
- // New type must be reference assignable to the old type
- // (our rewrites preserve type exactly, but the rules for rewriting
- // an extension node are more lenient, see Expression.ReduceAndCheck())
- Debug.Assert(
- TypeUtils.AreReferenceAssignable(node.Type, result.Node.Type),
- "rewritten object must be reference assignable to the original type"
- );
- }
-
- private Result RewriteExpressionFreeTemps(Expression expression, Stack stack) {
- int mark = Mark();
- Result result = RewriteExpression(expression, stack);
- Free(mark);
- return result;
- }
-
- // DynamicExpression
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "stack")]
- private Result RewriteDynamicExpression(Expression expr, Stack stack) {
- var node = (DynamicExpression)expr;
-
- // CallSite is on the stack
- IArgumentProvider argNode = (IArgumentProvider)node;
- ChildRewriter cr = new ChildRewriter(this, Stack.NonEmpty, argNode.ArgumentCount);
- cr.AddArguments(argNode);
- if (cr.Action == RewriteAction.SpillStack) {
- RequireNoRefArgs(node.DelegateType.GetMethod("Invoke"));
- }
- return cr.Finish(cr.Rewrite ? node.Rewrite(cr[0, -1]) : expr);
- }
-
- private Result RewriteIndexAssignment(BinaryExpression node, Stack stack) {
- IndexExpression index = (IndexExpression)node.Left;
-
- ChildRewriter cr = new ChildRewriter(this, stack, 2 + index.Arguments.Count);
-
- cr.Add(index.Object);
- cr.Add(index.Arguments);
- cr.Add(node.Right);
-
- if (cr.Action == RewriteAction.SpillStack) {
- RequireNotRefInstance(index.Object);
- }
-
- if (cr.Rewrite) {
- node = new AssignBinaryExpression(
- new IndexExpression(
- cr[0], // Object
- index.Indexer,
- cr[1, -2] // arguments
- ),
- cr[-1] // value
- );
- }
-
- return cr.Finish(node);
- }
-
- // BinaryExpression: AndAlso, OrElse
- private Result RewriteLogicalBinaryExpression(Expression expr, Stack stack) {
- BinaryExpression node = (BinaryExpression)expr;
-
- // Left expression runs on a stack as left by parent
- Result left = RewriteExpression(node.Left, stack);
- // ... and so does the right one
- Result right = RewriteExpression(node.Right, stack);
- //conversion is a lambda. stack state will be ignored.
- Result conversion = RewriteExpression(node.Conversion, stack);
-
- RewriteAction action = left.Action | right.Action | conversion.Action;
- if (action != RewriteAction.None) {
-
- // We don't have to worry about byref parameters here, because the
- // factory doesn't allow it (it requires identical parameters and
- // return type from the AndAlso/OrElse method)
-
- expr = BinaryExpression.Create(
- node.NodeType,
- left.Node,
- right.Node,
- node.Type,
- node.Method,
- (LambdaExpression)conversion.Node
- );
- }
- return new Result(action, expr);
- }
-
- private Result RewriteReducibleExpression(Expression expr, Stack stack) {
- Result result = RewriteExpression(expr.Reduce(), stack);
- // it's at least Copy because we reduced the node
- return new Result(result.Action | RewriteAction.Copy, result.Node);
- }
-
- // BinaryExpression
- private Result RewriteBinaryExpression(Expression expr, Stack stack) {
- BinaryExpression node = (BinaryExpression)expr;
-
- ChildRewriter cr = new ChildRewriter(this, stack, 3);
- // Left expression executes on the stack as left by parent
- cr.Add(node.Left);
- // Right expression always has non-empty stack (left is on it)
- cr.Add(node.Right);
- // conversion is a lambda, stack state will be ignored
- cr.Add(node.Conversion);
-
- if (cr.Action == RewriteAction.SpillStack) {
- RequireNoRefArgs(node.Method);
- }
-
- return cr.Finish(cr.Rewrite ?
- BinaryExpression.Create(
- node.NodeType,
- cr[0],
- cr[1],
- node.Type,
- node.Method,
- (LambdaExpression)cr[2]) :
- expr);
- }
-
- // variable assignment
- private Result RewriteVariableAssignment(BinaryExpression node, Stack stack) {
- // Expression is evaluated on a stack in current state
- Result right = RewriteExpression(node.Right, stack);
- if (right.Action != RewriteAction.None) {
- node = Expression.Assign(node.Left, right.Node);
- }
- return new Result(right.Action, node);
- }
-
- private Result RewriteAssignBinaryExpression(Expression expr, Stack stack) {
- var node = (BinaryExpression)expr;
-
- switch (node.Left.NodeType) {
- case ExpressionType.Index:
- return RewriteIndexAssignment(node, stack);
- case ExpressionType.MemberAccess:
- return RewriteMemberAssignment(node, stack);
- case ExpressionType.Parameter:
- return RewriteVariableAssignment(node, stack);
- case ExpressionType.Extension:
- return RewriteExtensionAssignment(node, stack);
- default:
- throw Error.InvalidLvalue(node.Left.NodeType);
- }
- }
-
- private Result RewriteExtensionAssignment(BinaryExpression node, Stack stack) {
- node = Expression.Assign(node.Left.ReduceExtensions(), node.Right);
- Result result = RewriteAssignBinaryExpression(node, stack);
- // it's at least Copy because we reduced the node
- return new Result(result.Action | RewriteAction.Copy, result.Node);
- }
-
- // LambdaExpression
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "stack")]
- private static Result RewriteLambdaExpression(Expression expr, Stack stack) {
- LambdaExpression node = (LambdaExpression)expr;
-
- // Call back into the rewriter
- expr = AnalyzeLambda(node);
-
- // If the lambda gets rewritten, we don't need to spill the stack,
- // but we do need to rebuild the tree above us so it includes the new node.
- RewriteAction action = (expr == node) ? RewriteAction.None : RewriteAction.Copy;
-
- return new Result(action, expr);
- }
-
- // ConditionalExpression
- private Result RewriteConditionalExpression(Expression expr, Stack stack) {
- ConditionalExpression node = (ConditionalExpression)expr;
- // Test executes at the stack as left by parent
- Result test = RewriteExpression(node.Test, stack);
- // The test is popped by conditional jump so branches execute
- // at the stack as left by parent too.
- Result ifTrue = RewriteExpression(node.IfTrue, stack);
- Result ifFalse = RewriteExpression(node.IfFalse, stack);
-
- RewriteAction action = test.Action | ifTrue.Action | ifFalse.Action;
- if (action != RewriteAction.None) {
- expr = Expression.Condition(test.Node, ifTrue.Node, ifFalse.Node, node.Type);
- }
-
- return new Result(action, expr);
- }
-
- // member assignment
- private Result RewriteMemberAssignment(BinaryExpression node, Stack stack) {
- MemberExpression lvalue = (MemberExpression)node.Left;
-
- ChildRewriter cr = new ChildRewriter(this, stack, 2);
-
- // If there's an instance, it executes on the stack in current state
- // and rest is executed on non-empty stack.
- // Otherwise the stack is left unchaged.
- cr.Add(lvalue.Expression);
-
- cr.Add(node.Right);
-
- if (cr.Action == RewriteAction.SpillStack) {
- RequireNotRefInstance(lvalue.Expression);
- }
-
- if (cr.Rewrite) {
- return cr.Finish(
- new AssignBinaryExpression(
- MemberExpression.Make(cr[0], lvalue.Member),
- cr[1]
- )
- );
- }
- return new Result(RewriteAction.None, node);
- }
-
- // MemberExpression
- private Result RewriteMemberExpression(Expression expr, Stack stack) {
- MemberExpression node = (MemberExpression)expr;
-
- // Expression is emitted on top of the stack in current state
- Result expression = RewriteExpression(node.Expression, stack);
- if (expression.Action != RewriteAction.None) {
- if (expression.Action == RewriteAction.SpillStack &&
- node.Member.MemberType == MemberTypes.Property) {
- // Only need to validate propreties because reading a field
- // is always side-effect free.
- RequireNotRefInstance(node.Expression);
- }
- expr = MemberExpression.Make(expression.Node, node.Member);
- }
- return new Result(expression.Action, expr);
- }
-
- //RewriteIndexExpression
- private Result RewriteIndexExpression(Expression expr, Stack stack) {
- IndexExpression node = (IndexExpression)expr;
-
- ChildRewriter cr = new ChildRewriter(this, stack, node.Arguments.Count + 1);
-
- // For instance methods, the instance executes on the
- // stack as is, but stays on the stack, making it non-empty.
- cr.Add(node.Object);
- cr.Add(node.Arguments);
-
- if (cr.Action == RewriteAction.SpillStack) {
- RequireNotRefInstance(node.Object);
- }
-
- if (cr.Rewrite) {
- expr = new IndexExpression(
- cr[0],
- node.Indexer,
- cr[1, -1]
- );
- }
-
- return cr.Finish(expr);
- }
-
- // MethodCallExpression
- private Result RewriteMethodCallExpression(Expression expr, Stack stack) {
- MethodCallExpression node = (MethodCallExpression)expr;
-
- ChildRewriter cr = new ChildRewriter(this, stack, node.Arguments.Count + 1);
-
- // For instance methods, the instance executes on the
- // stack as is, but stays on the stack, making it non-empty.
- cr.Add(node.Object);
-
- cr.AddArguments(node);
-
- if (cr.Action == RewriteAction.SpillStack) {
- RequireNotRefInstance(node.Object);
- RequireNoRefArgs(node.Method);
- }
-
- return cr.Finish(cr.Rewrite ? node.Rewrite(cr[0], cr[1, -1]) : expr);
- }
-
- // NewArrayExpression
- private Result RewriteNewArrayExpression(Expression expr, Stack stack) {
- NewArrayExpression node = (NewArrayExpression)expr;
-
- if (node.NodeType == ExpressionType.NewArrayInit) {
- // In a case of array construction with element initialization
- // the element expressions are never emitted on an empty stack because
- // the array reference and the index are on the stack.
- stack = Stack.NonEmpty;
- } else {
- // In a case of NewArrayBounds we make no modifications to the stack
- // before emitting bounds expressions.
- }
-
- ChildRewriter cr = new ChildRewriter(this, stack, node.Expressions.Count);
- cr.Add(node.Expressions);
-
- if (cr.Rewrite) {
- Type element = node.Type.GetElementType();
- if (node.NodeType == ExpressionType.NewArrayInit) {
- expr = Expression.NewArrayInit(element, cr[0, -1]);
- } else {
- expr = Expression.NewArrayBounds(element, cr[0, -1]);
- }
- }
-
- return cr.Finish(expr);
- }
-
- // InvocationExpression
- private Result RewriteInvocationExpression(Expression expr, Stack stack) {
- InvocationExpression node = (InvocationExpression)expr;
-
- ChildRewriter cr;
-
- // See if the lambda will be inlined
- LambdaExpression lambda = node.LambdaOperand;
- if (lambda != null) {
- // Arguments execute on current stack
- cr = new ChildRewriter(this, stack, node.Arguments.Count);
- cr.Add(node.Arguments);
-
- if (cr.Action == RewriteAction.SpillStack) {
- RequireNoRefArgs(Expression.GetInvokeMethod(node.Expression));
- }
-
- // Lambda body also executes on current stack
- var spiller = new StackSpiller(stack);
- lambda = lambda.Accept(spiller);
-
- if (cr.Rewrite || spiller._lambdaRewrite != RewriteAction.None) {
- node = new InvocationExpression(lambda, cr[0, -1], node.Type);
- }
-
- Result result = cr.Finish(node);
- return new Result(result.Action | spiller._lambdaRewrite, result.Node);
- }
-
- cr = new ChildRewriter(this, stack, node.Arguments.Count + 1);
-
- // first argument starts on stack as provided
- cr.Add(node.Expression);
-
- // rest of arguments have non-empty stack (delegate instance on the stack)
- cr.Add(node.Arguments);
-
- if (cr.Action == RewriteAction.SpillStack) {
- RequireNoRefArgs(Expression.GetInvokeMethod(node.Expression));
- }
-
- return cr.Finish(cr.Rewrite ? new InvocationExpression(cr[0], cr[1, -1], node.Type) : expr);
- }
-
- // NewExpression
- private Result RewriteNewExpression(Expression expr, Stack stack) {
- NewExpression node = (NewExpression)expr;
-
- // The first expression starts on a stack as provided by parent,
- // rest are definitely non-emtpy (which ChildRewriter guarantees)
- ChildRewriter cr = new ChildRewriter(this, stack, node.Arguments.Count);
- cr.AddArguments(node);
-
- if (cr.Action == RewriteAction.SpillStack) {
- RequireNoRefArgs(node.Constructor);
- }
-
- return cr.Finish(cr.Rewrite ? new NewExpression(node.Constructor, cr[0, -1], node.Members) : expr);
- }
-
- // TypeBinaryExpression
- private Result RewriteTypeBinaryExpression(Expression expr, Stack stack) {
- TypeBinaryExpression node = (TypeBinaryExpression)expr;
- // The expression is emitted on top of current stack
- Result expression = RewriteExpression(node.Expression, stack);
- if (expression.Action != RewriteAction.None) {
- if (node.NodeType == ExpressionType.TypeIs) {
- expr = Expression.TypeIs(expression.Node, node.TypeOperand);
- } else {
- expr = Expression.TypeEqual(expression.Node, node.TypeOperand);
- }
- }
- return new Result(expression.Action, expr);
- }
-
- // Throw
- private Result RewriteThrowUnaryExpression(Expression expr, Stack stack) {
- UnaryExpression node = (UnaryExpression)expr;
-
- // Throw statement itself does not care about the stack
- // but it will empty the stack and it may cause stack misbalance
- // it so we need to restore stack after unconditional throw to make JIT happy
- // this has an effect of executing Throw on an empty stack.
-
- Result value = RewriteExpressionFreeTemps(node.Operand, Stack.Empty);
- RewriteAction action = value.Action;
-
- if (stack != Stack.Empty) {
- action = RewriteAction.SpillStack;
- }
-
- if (action != RewriteAction.None) {
- expr = Expression.Throw(value.Node, node.Type);
- }
-
- return new Result(action, expr);
- }
-
- // UnaryExpression
- private Result RewriteUnaryExpression(Expression expr, Stack stack) {
- UnaryExpression node = (UnaryExpression)expr;
-
- Debug.Assert(node.NodeType != ExpressionType.Quote, "unexpected Quote");
- Debug.Assert(node.NodeType != ExpressionType.Throw, "unexpected Throw");
-
- // Operand is emitted on top of the stack as is
- Result expression = RewriteExpression(node.Operand, stack);
-
- if (expression.Action == RewriteAction.SpillStack) {
- RequireNoRefArgs(node.Method);
- }
-
- if (expression.Action != RewriteAction.None) {
- expr = new UnaryExpression(node.NodeType, expression.Node, node.Type, node.Method);
- }
- return new Result(expression.Action, expr);
- }
-
- // RewriteListInitExpression
- private Result RewriteListInitExpression(Expression expr, Stack stack) {
- ListInitExpression node = (ListInitExpression)expr;
-
- //ctor runs on initial stack
- Result newResult = RewriteExpression(node.NewExpression, stack);
- Expression rewrittenNew = newResult.Node;
- RewriteAction action = newResult.Action;
-
- ReadOnlyCollection<ElementInit> inits = node.Initializers;
-
- ChildRewriter[] cloneCrs = new ChildRewriter[inits.Count];
-
- for (int i = 0; i < inits.Count; i++) {
- ElementInit init = inits[i];
-
- //initializers all run on nonempty stack
- ChildRewriter cr = new ChildRewriter(this, Stack.NonEmpty, init.Arguments.Count);
- cr.Add(init.Arguments);
-
- action |= cr.Action;
- cloneCrs[i] = cr;
- }
-
- switch (action) {
- case RewriteAction.None:
- break;
- case RewriteAction.Copy:
- ElementInit[] newInits = new ElementInit[inits.Count];
- for (int i = 0; i < inits.Count; i++) {
- ChildRewriter cr = cloneCrs[i];
- if (cr.Action == RewriteAction.None) {
- newInits[i] = inits[i];
- } else {
- newInits[i] = Expression.ElementInit(inits[i].AddMethod, cr[0, -1]);
- }
- }
- expr = Expression.ListInit((NewExpression)rewrittenNew, new TrueReadOnlyCollection<ElementInit>(newInits));
- break;
- case RewriteAction.SpillStack:
- RequireNotRefInstance(node.NewExpression);
-
- ParameterExpression tempNew = MakeTemp(rewrittenNew.Type);
- Expression[] comma = new Expression[inits.Count + 2];
- comma[0] = Expression.Assign(tempNew, rewrittenNew);
-
- for (int i = 0; i < inits.Count; i++) {
- ChildRewriter cr = cloneCrs[i];
- Result add = cr.Finish(Expression.Call(tempNew, inits[i].AddMethod, cr[0, -1]));
- comma[i + 1] = add.Node;
- }
- comma[inits.Count + 1] = tempNew;
- expr = MakeBlock(comma);
- break;
- default:
- throw ContractUtils.Unreachable;
- }
-
- return new Result(action, expr);
- }
-
- // RewriteMemberInitExpression
- private Result RewriteMemberInitExpression(Expression expr, Stack stack) {
- MemberInitExpression node = (MemberInitExpression)expr;
-
- //ctor runs on original stack
- Result result = RewriteExpression(node.NewExpression, stack);
- Expression rewrittenNew = result.Node;
- RewriteAction action = result.Action;
-
- ReadOnlyCollection<MemberBinding> bindings = node.Bindings;
- BindingRewriter[] bindingRewriters = new BindingRewriter[bindings.Count];
- for (int i = 0; i < bindings.Count; i++) {
- MemberBinding binding = bindings[i];
- //bindings run on nonempty stack
- BindingRewriter rewriter = BindingRewriter.Create(binding, this, Stack.NonEmpty);
- bindingRewriters[i] = rewriter;
- action |= rewriter.Action;
- }
-
- switch (action) {
- case RewriteAction.None:
- break;
- case RewriteAction.Copy:
- MemberBinding[] newBindings = new MemberBinding[bindings.Count];
- for (int i = 0; i < bindings.Count; i++) {
- newBindings[i] = bindingRewriters[i].AsBinding();
- }
- expr = Expression.MemberInit((NewExpression)rewrittenNew, new TrueReadOnlyCollection<MemberBinding>(newBindings));
- break;
- case RewriteAction.SpillStack:
- RequireNotRefInstance(node.NewExpression);
-
- ParameterExpression tempNew = MakeTemp(rewrittenNew.Type);
- Expression[] comma = new Expression[bindings.Count + 2];
- comma[0] = Expression.Assign(tempNew, rewrittenNew);
- for (int i = 0; i < bindings.Count; i++) {
- BindingRewriter cr = bindingRewriters[i];
- Expression initExpr = cr.AsExpression(tempNew);
- comma[i + 1] = initExpr;
- }
- comma[bindings.Count + 1] = tempNew;
- expr = MakeBlock(comma);
- break;
- default:
- throw ContractUtils.Unreachable;
- }
- return new Result(action, expr);
- }
-
- #endregion
-
- #region Statements
-
- // Block
- private Result RewriteBlockExpression(Expression expr, Stack stack) {
- BlockExpression node = (BlockExpression)expr;
-
- int count = node.ExpressionCount;
- RewriteAction action = RewriteAction.None;
- Expression[] clone = null;
- for (int i = 0; i < count; i++) {
- Expression expression = node.GetExpression(i);
- // All statements within the block execute at the
- // same stack state.
- Result rewritten = RewriteExpression(expression, stack);
- action |= rewritten.Action;
-
- if (clone == null && rewritten.Action != RewriteAction.None) {
- clone = Clone(node.Expressions, i);
- }
-
- if (clone != null) {
- clone[i] = rewritten.Node;
- }
- }
-
- if (action != RewriteAction.None) {
- // okay to wrap since we know no one can mutate the clone array
- expr = node.Rewrite(null, clone);
- }
- return new Result(action, expr);
- }
-
- // LabelExpression
- private Result RewriteLabelExpression(Expression expr, Stack stack) {
- LabelExpression node = (LabelExpression)expr;
-
- Result expression = RewriteExpression(node.DefaultValue, stack);
- if (expression.Action != RewriteAction.None) {
- expr = Expression.Label(node.Target, expression.Node);
- }
- return new Result(expression.Action, expr);
- }
-
- // LoopStatement
- private Result RewriteLoopExpression(Expression expr, Stack stack) {
- LoopExpression node = (LoopExpression)expr;
-
- // The loop statement requires empty stack for itself, so it
- // can guarantee it to the child nodes.
- Result body = RewriteExpression(node.Body, Stack.Empty);
-
- RewriteAction action = body.Action;
-
- // However, the loop itself requires that it executes on an empty stack
- // so we need to rewrite if the stack is not empty.
- if (stack != Stack.Empty) {
- action = RewriteAction.SpillStack;
- }
-
- if (action != RewriteAction.None) {
- expr = new LoopExpression(body.Node, node.BreakLabel, node.ContinueLabel);
- }
- return new Result(action, expr);
- }
-
- // GotoExpression
- // Note: goto does not necessarily need an empty stack. We could always
- // emit it as a "leave" which would clear the stack for us. That would
- // prevent us from doing certain optimizations we might want to do,
- // however, like the switch-case-goto pattern. For now, be conservative
- private Result RewriteGotoExpression(Expression expr, Stack stack) {
- GotoExpression node = (GotoExpression)expr;
-
- // Goto requires empty stack to execute so the expression is
- // going to execute on an empty stack.
- Result value = RewriteExpressionFreeTemps(node.Value, Stack.Empty);
-
- // However, the statement itself needs an empty stack for itself
- // so if stack is not empty, rewrite to empty the stack.
- RewriteAction action = value.Action;
- if (stack != Stack.Empty) {
- action = RewriteAction.SpillStack;
- }
-
- if (action != RewriteAction.None) {
- expr = Expression.MakeGoto(node.Kind, node.Target, value.Node, node.Type);
- }
- return new Result(action, expr);
- }
-
- // SwitchStatement
- private Result RewriteSwitchExpression(Expression expr, Stack stack) {
- SwitchExpression node = (SwitchExpression)expr;
-
- // The switch statement test is emitted on the stack in current state
- Result switchValue = RewriteExpressionFreeTemps(node.SwitchValue, stack);
-
- RewriteAction action = switchValue.Action;
- ReadOnlyCollection<SwitchCase> cases = node.Cases;
- SwitchCase[] clone = null;
- for (int i = 0; i < cases.Count; i++) {
- SwitchCase @case = cases[i];
-
- Expression[] cloneTests = null;
- ReadOnlyCollection<Expression> testValues = @case.TestValues;
- for (int j = 0; j < testValues.Count; j++) {
- // All tests execute at the same stack state as the switch.
- // This is guarenteed by the compiler (to simplify spilling)
- Result test = RewriteExpression(testValues[j], stack);
- action |= test.Action;
-
- if (cloneTests == null && test.Action != RewriteAction.None) {
- cloneTests = Clone(testValues, j);
- }
-
- if (cloneTests != null) {
- cloneTests[j] = test.Node;
- }
- }
-
- // And all the cases also run on the same stack level.
- Result body = RewriteExpression(@case.Body, stack);
- action |= body.Action;
-
- if (body.Action != RewriteAction.None || cloneTests != null) {
- if (cloneTests != null) {
- testValues = new ReadOnlyCollection<Expression>(cloneTests);
- }
- @case = new SwitchCase(body.Node, testValues);
-
- if (clone == null) {
- clone = Clone(cases, i);
- }
- }
-
- if (clone != null) {
- clone[i] = @case;
- }
- }
-
- // default body also runs on initial stack
- Result defaultBody = RewriteExpression(node.DefaultBody, stack);
- action |= defaultBody.Action;
-
- if (action != RewriteAction.None) {
- if (clone != null) {
- // okay to wrap because we aren't modifying the array
- cases = new ReadOnlyCollection<SwitchCase>(clone);
- }
-
- expr = new SwitchExpression(node.Type, switchValue.Node, defaultBody.Node, node.Comparison, cases);
- }
-
- return new Result(action, expr);
- }
-
- // TryStatement
- private Result RewriteTryExpression(Expression expr, Stack stack) {
- TryExpression node = (TryExpression)expr;
-
- // Try statement definitely needs an empty stack so its
- // child nodes execute at empty stack.
- Result body = RewriteExpression(node.Body, Stack.Empty);
- ReadOnlyCollection<CatchBlock> handlers = node.Handlers;
- CatchBlock[] clone = null;
-
- RewriteAction action = body.Action;
- if (handlers != null) {
- for (int i = 0; i < handlers.Count; i++) {
- RewriteAction curAction = body.Action;
-
- CatchBlock handler = handlers[i];
-
- Expression filter = handler.Filter;
- if (handler.Filter != null) {
- // our code gen saves the incoming filter value and provides it as a varaible so the stack is empty
- Result rfault = RewriteExpression(handler.Filter, Stack.Empty);
- action |= rfault.Action;
- curAction |= rfault.Action;
- filter = rfault.Node;
- }
-
- // Catch block starts with an empty stack (guaranteed by TryStatement)
- Result rbody = RewriteExpression(handler.Body, Stack.Empty);
- action |= rbody.Action;
- curAction |= rbody.Action;
-
- if (curAction != RewriteAction.None) {
- handler = Expression.MakeCatchBlock(handler.Test, handler.Variable, rbody.Node, filter);
-
- if (clone == null) {
- clone = Clone(handlers, i);
- }
- }
-
- if (clone != null) {
- clone[i] = handler;
- }
- }
- }
-
- Result fault = RewriteExpression(node.Fault, Stack.Empty);
- action |= fault.Action;
-
- Result @finally = RewriteExpression(node.Finally, Stack.Empty);
- action |= @finally.Action;
-
- // If the stack is initially not empty, rewrite to spill the stack
- if (stack != Stack.Empty) {
- action = RewriteAction.SpillStack;
- }
-
- if (action != RewriteAction.None) {
- if (clone != null) {
- // okay to wrap because we aren't modifying the array
- handlers = new ReadOnlyCollection<CatchBlock>(clone);
- }
-
- expr = new TryExpression(node.Type, body.Node, @finally.Node, fault.Node, handlers);
- }
- return new Result(action, expr);
- }
-
- private Result RewriteExtensionExpression(Expression expr, Stack stack) {
- Result result = RewriteExpression(expr.ReduceExtensions(), stack);
- // it's at least Copy because we reduced the node
- return new Result(result.Action | RewriteAction.Copy, result.Node);
- }
-
- #endregion
-
- #region Cloning
-
- /// <summary>
- /// Will clone an IList into an array of the same size, and copy
- /// all vaues up to (and NOT including) the max index
- /// </summary>
- /// <returns>The cloned array.</returns>
- private static T[] Clone<T>(ReadOnlyCollection<T> original, int max) {
- Debug.Assert(original != null);
- Debug.Assert(max < original.Count);
-
- T[] clone = new T[original.Count];
- for (int j = 0; j < max; j++) {
- clone[j] = original[j];
- }
- return clone;
- }
-
- #endregion
-
- /// <summary>
- /// If we are spilling, requires that there are no byref arguments to
- /// the method call.
- ///
- /// Used for:
- /// NewExpression,
- /// MethodCallExpression,
- /// InvocationExpression,
- /// DynamicExpression,
- /// UnaryExpression,
- /// BinaryExpression.
- /// </summary>
- /// <remarks>
- /// We could support this if spilling happened later in the compiler.
- /// Other expressions that can emit calls with arguments (such as
- /// ListInitExpression and IndexExpression) don't allow byref arguments.
- /// </remarks>
- private static void RequireNoRefArgs(MethodBase method) {
- if (method != null && method.GetParametersCached().Any(p => p.ParameterType.IsByRef)) {
- throw Error.TryNotSupportedForMethodsWithRefArgs(method);
- }
- }
-
- /// <summary>
- /// Requires that the instance is not a value type (primitive types are
- /// okay because they're immutable).
- ///
- /// Used for:
- /// MethodCallExpression,
- /// MemberExpression (for properties),
- /// IndexExpression,
- /// ListInitExpression,
- /// MemberInitExpression,
- /// assign to MemberExpression,
- /// assign to IndexExpression.
- /// </summary>
- /// <remarks>
- /// We could support this if spilling happened later in the compiler.
- /// </remarks>
- private static void RequireNotRefInstance(Expression instance) {
- // Primitive value types are okay because they are all readonly,
- // but we can't rely on this for non-primitive types. So we throw
- // NotSupported.
- if (instance != null && instance.Type.IsValueType && Type.GetTypeCode(instance.Type) == TypeCode.Object) {
- throw Error.TryNotSupportedForValueTypeInstances(instance.Type);
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/SymbolDocumentGenerator.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/SymbolDocumentGenerator.cs
deleted file mode 100644
index 25e0b394d88..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/SymbolDocumentGenerator.cs
+++ /dev/null
@@ -1,72 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-#if FEATURE_REFEMIT && FEATURE_PDBEMIT
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-using Microsoft.Scripting.Ast.Compiler;
-#else
-using System.Linq.Expressions;
-using System.Linq.Expressions.Compiler;
-#endif
-
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Diagnostics.SymbolStore;
-using System.Reflection;
-using System.Reflection.Emit;
-
-namespace System.Runtime.CompilerServices {
-#if !FEATURE_CORE_DLR || SILVERLIGHT
- using ILGenerator = OffsetTrackingILGenerator;
-#endif
-
- /// <summary>
- /// Generator of PDB debugging information for expression trees.
- /// </summary>
- internal sealed class SymbolDocumentGenerator : DebugInfoGenerator {
- private Dictionary<SymbolDocumentInfo, ISymbolDocumentWriter> _symbolWriters;
-
- private ISymbolDocumentWriter GetSymbolWriter(MethodBuilder method, SymbolDocumentInfo document) {
- ISymbolDocumentWriter result;
- if (_symbolWriters == null) {
- _symbolWriters = new Dictionary<SymbolDocumentInfo, ISymbolDocumentWriter>();
- }
-
- if (!_symbolWriters.TryGetValue(document, out result)) {
- result = ((ModuleBuilder)method.Module).DefineDocument(document.FileName, document.Language, document.LanguageVendor, SymbolGuids.DocumentType_Text);
- _symbolWriters.Add(document, result);
- }
-
- return result;
- }
-
- internal override void MarkSequencePoint(LambdaExpression method, MethodBase methodBase, ILGenerator ilg, DebugInfoExpression sequencePoint) {
- MethodBuilder builder = methodBase as MethodBuilder;
- if (builder != null) {
- ilg.MarkSequencePoint(GetSymbolWriter(builder, sequencePoint.Document), sequencePoint.StartLine, sequencePoint.StartColumn, sequencePoint.EndLine, sequencePoint.EndColumn);
- }
- }
-
- public override void MarkSequencePoint(LambdaExpression method, int ilOffset, DebugInfoExpression sequencePoint) {
- throw Error.PdbGeneratorNeedsExpressionCompiler();
- }
-
- internal override void SetLocalName(LocalBuilder localBuilder, string name) {
- localBuilder.SetLocalSymInfo(name);
- }
- }
-}
-#endif
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/SymbolGuids.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/SymbolGuids.cs
deleted file mode 100644
index ec8f0f84c2d..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/SymbolGuids.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using System;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- internal static class SymbolGuids {
- internal static readonly Guid DocumentType_Text =
- new Guid(0x5a869d0b, 0x6611, 0x11d3, 0xbd, 0x2a, 0, 0, 0xf8, 8, 0x49, 0xbd);
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/VariableBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/VariableBinder.cs
deleted file mode 100644
index 2711f48d08f..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/VariableBinder.cs
+++ /dev/null
@@ -1,244 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Dynamic.Utils;
-
-#if SILVERLIGHT
-using System.Core;
-#endif
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast.Compiler {
-#else
-namespace System.Linq.Expressions.Compiler {
-#endif
- /// <summary>
- /// Determines if variables are closed over in nested lambdas and need to
- /// be hoisted.
- /// </summary>
- internal sealed class VariableBinder : ExpressionVisitor {
- private readonly AnalyzedTree _tree = new AnalyzedTree();
- private readonly Stack<CompilerScope> _scopes = new Stack<CompilerScope>();
- private readonly Stack<BoundConstants> _constants = new Stack<BoundConstants>();
- private bool _inQuote;
-
- internal static AnalyzedTree Bind(LambdaExpression lambda) {
- var binder = new VariableBinder();
- binder.Visit(lambda);
- return binder._tree;
- }
-
- private VariableBinder() {
- }
-
- protected internal override Expression VisitConstant(ConstantExpression node) {
- // If we're in Quote, we can ignore constants completely
- if (_inQuote) {
- return node;
- }
-
- // Constants that can be emitted into IL don't need to be stored on
- // the delegate
- if (ILGen.CanEmitConstant(node.Value, node.Type)) {
- return node;
- }
-
- _constants.Peek().AddReference(node.Value, node.Type);
- return node;
- }
-
- protected internal override Expression VisitUnary(UnaryExpression node) {
- if (node.NodeType == ExpressionType.Quote) {
- bool savedInQuote = _inQuote;
- _inQuote = true;
- Visit(node.Operand);
- _inQuote = savedInQuote;
- } else {
- Visit(node.Operand);
- }
- return node;
- }
-
- protected internal override Expression VisitLambda<T>(Expression<T> node) {
- _scopes.Push(_tree.Scopes[node] = new CompilerScope(node, true));
- _constants.Push(_tree.Constants[node] = new BoundConstants());
- Visit(MergeScopes(node));
- _constants.Pop();
- _scopes.Pop();
- return node;
- }
-
- protected internal override Expression VisitInvocation(InvocationExpression node) {
- LambdaExpression lambda = node.LambdaOperand;
-
- // optimization: inline code for literal lambda's directly
- if (lambda != null) {
- // visit the lambda, but treat it more like a scope
- _scopes.Push(_tree.Scopes[lambda] = new CompilerScope(lambda, false));
- Visit(MergeScopes(lambda));
- _scopes.Pop();
- // visit the invoke's arguments
- Visit(node.Arguments);
- return node;
- }
-
- return base.VisitInvocation(node);
- }
-
- protected internal override Expression VisitBlock(BlockExpression node) {
- if (node.Variables.Count == 0) {
- Visit(node.Expressions);
- return node;
- }
- _scopes.Push(_tree.Scopes[node] = new CompilerScope(node, false));
- Visit(MergeScopes(node));
- _scopes.Pop();
- return node;
- }
-
- protected override CatchBlock VisitCatchBlock(CatchBlock node) {
- if (node.Variable == null) {
- Visit(node.Body);
- return node;
- }
- _scopes.Push(_tree.Scopes[node] = new CompilerScope(node, false));
- Visit(node.Body);
- _scopes.Pop();
- return node;
- }
-
- // If the immediate child is another scope, merge it into this one
- // This is an optimization to save environment allocations and
- // array accesses.
- private ReadOnlyCollection<Expression> MergeScopes(Expression node) {
- ReadOnlyCollection<Expression> body;
- var lambda = node as LambdaExpression;
- if (lambda != null) {
- body = new ReadOnlyCollection<Expression>(new[] { lambda.Body });
- } else {
- body = ((BlockExpression)node).Expressions;
- }
-
- var currentScope = _scopes.Peek();
-
- // A block body is mergeable if the body only contains one single block node containing variables,
- // and the child block has the same type as the parent block.
- while (body.Count == 1 && body[0].NodeType == ExpressionType.Block) {
- var block = (BlockExpression)body[0];
-
- if (block.Variables.Count > 0) {
- // Make sure none of the variables are shadowed. If any
- // are, we can't merge it.
- foreach (var v in block.Variables) {
- if (currentScope.Definitions.ContainsKey(v)) {
- return body;
- }
- }
-
- // Otherwise, merge it
- if (currentScope.MergedScopes == null) {
- currentScope.MergedScopes = new Set<object>(ReferenceEqualityComparer<object>.Instance);
- }
- currentScope.MergedScopes.Add(block);
- foreach (var v in block.Variables) {
- currentScope.Definitions.Add(v, VariableStorageKind.Local);
- }
- }
- node = block;
- body = block.Expressions;
- }
- return body;
- }
-
-
- protected internal override Expression VisitParameter(ParameterExpression node) {
- Reference(node, VariableStorageKind.Local);
-
- //
- // Track reference count so we can emit it in a more optimal way if
- // it is used a lot.
- //
- CompilerScope referenceScope = null;
- foreach (CompilerScope scope in _scopes) {
- //
- // There are two times we care about references:
- // 1. When we enter a lambda, we want to cache frequently
- // used variables
- // 2. When we enter a scope with closed-over variables, we
- // want to cache it immediately when we allocate the
- // closure slot for it
- //
- if (scope.IsMethod || scope.Definitions.ContainsKey(node)) {
- referenceScope = scope;
- break;
- }
- }
-
- Debug.Assert(referenceScope != null);
- if (referenceScope.ReferenceCount == null) {
- referenceScope.ReferenceCount = new Dictionary<ParameterExpression, int>();
- }
-
- Helpers.IncrementCount(node, referenceScope.ReferenceCount);
- return node;
- }
-
- protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) {
- foreach (var v in node.Variables) {
- // Force hoisting of these variables
- Reference(v, VariableStorageKind.Hoisted);
- }
- return node;
- }
-
- private void Reference(ParameterExpression node, VariableStorageKind storage) {
- CompilerScope definition = null;
- foreach (CompilerScope scope in _scopes) {
- if (scope.Definitions.ContainsKey(node)) {
- definition = scope;
- break;
- }
- scope.NeedsClosure = true;
- if (scope.IsMethod) {
- storage = VariableStorageKind.Hoisted;
- }
- }
- if (definition == null) {
- throw Error.UndefinedVariable(node.Name, node.Type, CurrentLambdaName);
- }
- if (storage == VariableStorageKind.Hoisted) {
- if (node.IsByRef) {
- throw Error.CannotCloseOverByRef(node.Name, CurrentLambdaName);
- }
- definition.Definitions[node] = VariableStorageKind.Hoisted;
- }
- }
-
- private string CurrentLambdaName {
- get {
- foreach (var scope in _scopes) {
- var lambda = scope.Node as LambdaExpression;
- if (lambda != null) {
- return lambda.Name;
- }
- }
- throw ContractUtils.Unreachable;
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/GlobalSuppressions.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/GlobalSuppressions.cs
deleted file mode 100644
index a21aeca06cf..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/GlobalSuppressions.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-// This file is used by Code Analysis to maintain SuppressMessage
-// attributes that are applied to this project.
-// Project-level suppressions either have no target or are given
-// a specific target and scoped to a namespace, type, member, etc.
-//
-// To add a suppression to this file, right-click the message in the
-// Error List, point to "Suppress Message(s)", and click
-// "In Project Suppression File".
-// You do not need to add suppressions to this file manually.
-
-//UnhandledExpressionType is used by System.Linq.Expressions.OldExpressionVisitor
-#if !FEATURE_CORE_DLR
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "Microsoft.Scripting.Ast.Error.#UnhandledExpressionType(System.Object)")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "Microsoft.Scripting.Ast.Strings.#UnhandledExpressionType(System.Object)")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "Microsoft.Scripting.Ast.Error.#InvalidNullValue(System.Object)")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "Microsoft.Scripting.Ast.Error.#InvalidObjectType(System.Object,System.Object)")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "Microsoft.Scripting.Ast.Error.#HomogenousAppDomainRequired()")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "Microsoft.Scripting.Ast.Strings.#HomogenousAppDomainRequired")]
-#endif
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Scope = "member", Target = "System.Runtime.CompilerServices.StrongBox`1.#System.Runtime.CompilerServices.IStrongBox.Value")]
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Microsoft.Scripting.Core.csproj b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Microsoft.Scripting.Core.csproj
deleted file mode 100644
index 05b0240151e..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Microsoft.Scripting.Core.csproj
+++ /dev/null
@@ -1,163 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
- <Import Project="$(ProjectDir)..\..\Solutions\Common.proj" />
- <PropertyGroup>
- <SchemaVersion>2.0</SchemaVersion>
- <ProjectGuid>{2AE75F5A-CD1F-4925-9647-AF4D1C282FB4}</ProjectGuid>
- <OutputType>Library</OutputType>
- <AppDesignerFolder>Properties</AppDesignerFolder>
- <RootNamespace>System.Scripting</RootNamespace>
- <AssemblyName>Microsoft.Scripting.Core</AssemblyName>
- <BaseAddress>855638016</BaseAddress>
- <CodeAnalysisRuleSet>$(AssemblyName).ruleset</CodeAnalysisRuleSet>
- <DocumentationFile>$(SolutionDir)..\bin\$(Configuration)\$(AssemblyName).xml</DocumentationFile>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'FxCop|AnyCPU' ">
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'v2Debug|AnyCPU' ">
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'v2Release|AnyCPU' ">
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'WP7Debug|AnyCPU' ">
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'WP7Release|AnyCPU' ">
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'AndroidDebug|AnyCPU' ">
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'AndroidRelease|AnyCPU' ">
- </PropertyGroup>
- <ItemGroup>
- <Compile Include="..\..\Hosts\Silverlight\SilverlightVersion.cs" Condition=" '$(IsSilverlight)' == 'true' ">
- <Link>Properties\SilverlightVersion.cs</Link>
- </Compile>
- <Compile Include="Actions\CallInfo.cs" />
- <Compile Include="Actions\CallSiteOps.cs" />
- <Compile Include="Actions\IInvokeOnGetBinder.cs" />
- <Compile Include="Actions\InvokeMemberBinder.cs" />
- <Compile Include="Actions\BinaryOperationBinder.cs" />
- <Compile Include="Actions\CallSite.cs" />
- <Compile Include="Actions\CallSiteBinder.cs" />
- <Compile Include="Actions\CallSiteHelpers.cs" />
- <Compile Include="Actions\ConvertBinder.cs" />
- <Compile Include="Actions\DeleteIndexBinder.cs" />
- <Compile Include="Actions\DynamicObject.cs" />
- <Compile Include="Actions\ExpandoObject.cs" />
- <Compile Include="Actions\ExpandoClass.cs" />
- <Compile Include="Actions\GetIndexBinder.cs" />
- <Compile Include="Actions\CreateInstanceBinder.cs" />
- <Compile Include="Actions\DeleteMemberBinder.cs" />
- <Compile Include="Actions\GetMemberBinder.cs" />
- <Compile Include="Actions\IDynamicMetaObjectProvider.cs" />
- <Compile Include="Actions\InvokeBinder.cs" />
- <Compile Include="Actions\DynamicMetaObject.cs" />
- <Compile Include="Actions\DynamicMetaObjectBinder.cs" />
- <Compile Include="Actions\BindingRestrictions.cs" />
- <Compile Include="Actions\RuleCache.cs" />
- <Compile Include="Actions\SetIndexBinder.cs" />
- <Compile Include="Actions\SetMemberBinder.cs" />
- <Compile Include="Ast\Expression.DebuggerProxy.cs" />
- <Compile Include="Ast\IArgumentProvider.cs" />
- <Compile Include="Ast\ListArgumentProvider.cs" />
- <Compile Include="Actions\UnaryOperationBinder.cs" />
- <Compile Include="Ast\ExpressionStringBuilder.cs" />
- <Compile Include="Compiler\BoundConstants.cs" />
- <Compile Include="Ast\DebugInfoExpression.cs" />
- <Compile Include="Ast\SymbolDocumentInfo.cs" />
- <Compile Include="Compiler\DelegateHelpers.cs" />
- <Compile Include="Compiler\DelegateHelpers.Generated.cs" />
- <Compile Include="Ast\GotoExpression.cs" />
- <Compile Include="Compiler\LabelInfo.cs" />
- <Compile Include="Compiler\AnalyzedTree.cs" />
- <Compile Include="Compiler\OffsetTrackingILGenerator.cs" />
- <Compile Include="Compiler\RuntimeVariableList.cs" />
- <Compile Include="Actions\UpdateDelegates.Generated.cs" />
- <Compile Include="Ast\DynamicExpression.cs" />
- <Compile Include="Ast\BinaryExpression.cs" />
- <Compile Include="Ast\BlockExpression.cs" />
- <Compile Include="Ast\CatchBlock.cs" />
- <Compile Include="Ast\ConditionalExpression.cs" />
- <Compile Include="Ast\ConstantExpression.cs" />
- <Compile Include="Ast\DefaultExpression.cs" />
- <Compile Include="Ast\ElementInit.cs" />
- <Compile Include="Ast\Expression.cs" />
- <Compile Include="Ast\ExpressionType.cs" />
- <Compile Include="Ast\IndexExpression.cs" />
- <Compile Include="Ast\InvocationExpression.cs" />
- <Compile Include="Ast\LabelTarget.cs" />
- <Compile Include="Ast\LabelExpression.cs" />
- <Compile Include="Ast\LambdaExpression.cs" />
- <Compile Include="Ast\ListInitExpression.cs" />
- <Compile Include="Ast\RuntimeVariablesExpression.cs" />
- <Compile Include="Ast\LoopExpression.cs" />
- <Compile Include="Ast\MemberAssignment.cs" />
- <Compile Include="Ast\MemberBinding.cs" />
- <Compile Include="Ast\MemberExpression.cs" />
- <Compile Include="Ast\MemberInitExpression.cs" />
- <Compile Include="Ast\MemberListBinding.cs" />
- <Compile Include="Ast\MemberMemberBinding.cs" />
- <Compile Include="Ast\MethodCallExpression.cs" />
- <Compile Include="Ast\NewArrayExpression.cs" />
- <Compile Include="Ast\NewExpression.cs" />
- <Compile Include="Ast\ParameterExpression.cs" />
- <Compile Include="Ast\SwitchCase.cs" />
- <Compile Include="Ast\SwitchExpression.cs" />
- <Compile Include="Ast\TryExpression.cs" />
- <Compile Include="Ast\TypeBinaryExpression.cs" />
- <Compile Include="Ast\TypeUtils.cs" />
- <Compile Include="Ast\UnaryExpression.cs" />
- <Compile Include="Compiler\Closure.cs" />
- <Compile Include="Compiler\CompilerScope.Storage.cs" />
- <Compile Include="Compiler\CompilerScope.cs" />
- <Compile Include="Compiler\ConstantCheck.cs" />
- <Compile Include="Compiler\ExpressionQuoter.cs" />
- <Compile Include="Ast\ExpressionVisitor.cs" />
- <Compile Include="Ast\DebugViewWriter.cs" />
- <Compile Include="Compiler\HoistedLocals.cs" />
- <Compile Include="Compiler\KeyedQueue.cs" />
- <Compile Include="Compiler\LambdaCompiler.Address.cs" />
- <Compile Include="Compiler\LambdaCompiler.Binary.cs" />
- <Compile Include="Compiler\LambdaCompiler.ControlFlow.cs" />
- <Compile Include="Compiler\LambdaCompiler.Expressions.cs" />
- <Compile Include="Compiler\LambdaCompiler.Generated.cs" />
- <Compile Include="Compiler\LambdaCompiler.Lambda.cs" />
- <Compile Include="Compiler\LambdaCompiler.Logical.cs" />
- <Compile Include="Compiler\LambdaCompiler.Statements.cs" />
- <Compile Include="Compiler\LambdaCompiler.Unary.cs" />
- <Compile Include="Compiler\LambdaCompiler.cs" />
- <Compile Include="Compiler\DebugInfoGenerator.cs" />
- <Compile Include="Compiler\Set.cs" />
- <Compile Include="Compiler\StackSpiller.Bindings.cs" />
- <Compile Include="Compiler\StackSpiller.Generated.cs" />
- <Compile Include="Compiler\StackSpiller.Temps.cs" />
- <Compile Include="Compiler\StackSpiller.cs" />
- <Compile Include="Compiler\SymbolDocumentGenerator.cs" />
- <Compile Include="Compiler\SymbolGuids.cs" />
- <Compile Include="Compiler\VariableBinder.cs" />
- <Compile Include="Compiler\AssemblyGen.cs" />
- <Compile Include="Compiler\ILGen.cs" />
- <Compile Include="GlobalSuppressions.cs" />
- <Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="Utils\Action.cs" />
- <Compile Include="Utils\CacheDict.cs" />
- <Compile Include="Utils\CollectionExtensions.cs" />
- <Compile Include="Utils\ContractUtils.cs" />
- <Compile Include="Utils\ExceptionFactory.Generated.cs" />
- <Compile Include="Utils\Function.cs" />
- <Compile Include="Utils\Helpers.cs" />
- <Compile Include="Utils\IRuntimeVariables.cs" />
- <Compile Include="Utils\ReadOnlyCollectionBuilder.cs" />
- <Compile Include="Utils\ReadOnlyDictionary.cs" />
- <Compile Include="Utils\ReferenceEqualityComparer.cs" />
- <Compile Include="Utils\ReflectionUtils.cs" />
- <Compile Include="Utils\TrueReadOnlyCollection.cs" />
- <Compile Include="Utils\TypeExtensions.cs" />
- <Compile Include="Stubs.cs" />
- </ItemGroup>
- <ItemGroup>
- <None Include="Microsoft.Scripting.Core.ruleset" />
- </ItemGroup>
- <ItemGroup Condition=" '$(IsFullFramework)' == 'true' ">
- <Reference Include="System.Configuration" />
- </ItemGroup>
- <Import Project="$(CSharpTargets)" />
-</Project>
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Microsoft.Scripting.ExtensionAttribute.csproj b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Microsoft.Scripting.ExtensionAttribute.csproj
deleted file mode 100644
index 27331e55160..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Microsoft.Scripting.ExtensionAttribute.csproj
+++ /dev/null
@@ -1,104 +0,0 @@
-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
-
-
- <PropertyGroup>
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
- <ProductVersion>10.0.20624</ProductVersion>
- <SchemaVersion>2.0</SchemaVersion>
- <ProjectGuid>{8B0F1074-750E-4D64-BF23-A1E0F54261E5}</ProjectGuid>
- <OutputType>Library</OutputType>
- <AppDesignerFolder>Properties</AppDesignerFolder>
- <RootNamespace>Microsoft.Scripting.ExtensionAttribute</RootNamespace>
- <AssemblyName>Microsoft.Scripting.ExtensionAttribute</AssemblyName>
-<AssemblyOriginatorKeyFile>$(SolutionDir)Runtime\MSSharedLibKey.snk</AssemblyOriginatorKeyFile>
- <SignAssembly Condition="'$(SignAssembly)' == '' And Exists('$(AssemblyOriginatorKeyFile)')">true</SignAssembly>
- <SignedSym Condition="'$(SignAssembly)' == 'true'">SIGNED</SignedSym>
- <DelaySign>true</DelaySign>
- <BaseAddress>866123776</BaseAddress>
- <SilverlightPath Condition="'$(SilverlightPath)' == ''">$(ProgramFiles)\Microsoft Silverlight\3.0.40818.0\</SilverlightPath>
- <TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'FxCop|AnyCPU' ">
- <DebugType>pdbonly</DebugType>
- <Optimize>true</Optimize>
-<OutputPath>$(SolutionDir)..\Bin\fxcop\</OutputPath>
- <DefineConstants>TRACE;$(SignedSym)</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <RunCodeAnalysis>true</RunCodeAnalysis>
- <CodeAnalysisRules>-Microsoft.Usage#CA2209;+!Microsoft.Design#CA1012;-!Microsoft.Design#CA2210;+!Microsoft.Design#CA1040;+!Microsoft.Design#CA1005;+!Microsoft.Design#CA1020;-!Microsoft.Design#CA1021;+!Microsoft.Design#CA1010;+!Microsoft.Design#CA1011;+!Microsoft.Design#CA1009;+!Microsoft.Design#CA1050;+!Microsoft.Design#CA1026;+!Microsoft.Design#CA1019;+!Microsoft.Design#CA1031;+!Microsoft.Design#CA1047;+!Microsoft.Design#CA1000;+!Microsoft.Design#CA1048;+!Microsoft.Design#CA1051;+!Microsoft.Design#CA1002;+!Microsoft.Design#CA1061;+!Microsoft.Design#CA1006;+!Microsoft.Design#CA1046;+!Microsoft.Design#CA1045;+!Microsoft.Design#CA1065;+!Microsoft.Design#CA1038;+!Microsoft.Design#CA1008;+!Microsoft.Design#CA1028;+!Microsoft.Design#CA1064;-!Microsoft.Design#CA1004;+!Microsoft.Design#CA1035;+!Microsoft.Design#CA1063;+!Microsoft.Design#CA1032;+!Microsoft.Design#CA1023;+!Microsoft.Design#CA1033;+!Microsoft.Design#CA1039;+!Microsoft.Design#CA1016;+!Microsoft.Design#CA1014;+!Microsoft.Design#CA1017;+!Microsoft.Design#CA1018;+!Microsoft.Design#CA1027;+!Microsoft.Design#CA1059;+!Microsoft.Design#CA1060;+!Microsoft.Design#CA1034;+!Microsoft.Design#CA1013;+!Microsoft.Design#CA1036;+!Microsoft.Design#CA1044;+!Microsoft.Design#CA1041;+!Microsoft.Design#CA1025;+!Microsoft.Design#CA1052;+!Microsoft.Design#CA1053;+!Microsoft.Design#CA1057;+!Microsoft.Design#CA1058;+!Microsoft.Design#CA1001;+!Microsoft.Design#CA1049;+!Microsoft.Design#CA1054;+!Microsoft.Design#CA1056;+!Microsoft.Design#CA1055;+!Microsoft.Design#CA1030;+!Microsoft.Design#CA1003;+!Microsoft.Design#CA1007;+!Microsoft.Design#CA1043;+!Microsoft.Design#CA1024;+!Microsoft.Globalization#CA1301;+!Microsoft.Globalization#CA1302;+!Microsoft.Globalization#CA1308;+!Microsoft.Globalization#CA1306;+!Microsoft.Globalization#CA1304;+!Microsoft.Globalization#CA1305;+!Microsoft.Globalization#CA2101;+!Microsoft.Globalization#CA1300;+!Microsoft.Globalization#CA1307;+!Microsoft.Globalization#CA1309;+!Microsoft.Interoperability#CA1403;+!Microsoft.Interoperability#CA1406;+!Microsoft.Interoperability#CA1413;+!Microsoft.Interoperability#CA1402;+!Microsoft.Interoperability#CA1407;+!Microsoft.Interoperability#CA1404;+!Microsoft.Interoperability#CA1410;+!Microsoft.Interoperability#CA1411;+!Microsoft.Interoperability#CA1405;+!Microsoft.Interoperability#CA1409;+!Microsoft.Interoperability#CA1415;+!Microsoft.Interoperability#CA1408;+!Microsoft.Interoperability#CA1414;+!Microsoft.Interoperability#CA1412;+!Microsoft.Interoperability#CA1400;+!Microsoft.Interoperability#CA1401;+!Microsoft.Maintainability#CA1506;+!Microsoft.Maintainability#CA1502;+!Microsoft.Maintainability#CA1501;+!Microsoft.Maintainability#CA1505;+!Microsoft.Maintainability#CA1504;+!Microsoft.Maintainability#CA1500;+!Microsoft.Mobility#CA1600;+!Microsoft.Mobility#CA1601;-!Microsoft.Naming#CA1702;+!Microsoft.Naming#CA1700;+!Microsoft.Naming#CA1712;+!Microsoft.Naming#CA1713;+!Microsoft.Naming#CA1714;+!Microsoft.Naming#CA1709;-!Microsoft.Naming#CA1704;+!Microsoft.Naming#CA1708;+!Microsoft.Naming#CA1715;-!Microsoft.Naming#CA1710;-!Microsoft.Naming#CA1720;+!Microsoft.Naming#CA1707;+!Microsoft.Naming#CA1722;-!Microsoft.Naming#CA1711;+!Microsoft.Naming#CA1716;+!Microsoft.Naming#CA1717;+!Microsoft.Naming#CA1725;+!Microsoft.Naming#CA1719;+!Microsoft.Naming#CA1721;+!Microsoft.Naming#CA1701;+!Microsoft.Naming#CA1703;+!Microsoft.Naming#CA1724;-!Microsoft.Naming#CA1726;+!Microsoft.Performance#CA1809;+!Microsoft.Performance#CA1811;+!Microsoft.Performance#CA1812;+!Microsoft.Performance#CA1813;+!Microsoft.Performance#CA1823;+!Microsoft.Performance#CA1800;+!Microsoft.Performance#CA1805;+!Microsoft.Performance#CA1810;+!Microsoft.Performance#CA1824;+!Microsoft.Performance#CA1822;+!Microsoft.Performance#CA1815;+!Microsoft.Performance#CA1814;+!Microsoft.Performance#CA1819;+!Microsoft.Performance#CA1821;+!Microsoft.Performance#CA1804;+!Microsoft.Performance#CA1820;+!Microsoft.Performance#CA1802;+!Microsoft.Portability#CA1901;+!Microsoft.Portability#CA1900;+!Microsoft.Reliability#CA2001;+!Microsoft.Reliability#CA2002;+!Microsoft.Reliability#CA2003;+!Microsoft.Reliability#CA2004;+!Microsoft.Reliability#CA2006;+!Microsoft.Security#CA2116;+!Microsoft.Security#CA2117;+!Microsoft.Security#CA2105;+!Microsoft.Security#CA2115;+!Microsoft.Security#CA2102;+!Microsoft.Security#CA2104;+!Microsoft.Security#CA2122;+!Microsoft.Security#CA2114;+!Microsoft.Security#CA2123;+!Microsoft.Security#CA2111;+!Microsoft.Security#CA2108;+!Microsoft.Security#CA2107;+!Microsoft.Security#CA2103;+!Microsoft.Security#CA2118;+!Microsoft.Security#CA2109;+!Microsoft.Security#CA2119;+!Microsoft.Security#CA2106;+!Microsoft.Security#CA2112;+!Microsoft.Security#CA2120;+!Microsoft.Security#CA2121;+!Microsoft.Security#CA2126;+!Microsoft.Security#CA2124;+!Microsoft.Security#CA2127;+!Microsoft.Security#CA2128;+!Microsoft.Security#CA2129;+!Microsoft.Usage#CA2243;+!Microsoft.Usage#CA2236;+!Microsoft.Usage#CA1816;+!Microsoft.Usage#CA2227;+!Microsoft.Usage#CA2213;+!Microsoft.Usage#CA2216;+!Microsoft.Usage#CA2214;+!Microsoft.Usage#CA2222;+!Microsoft.Usage#CA1806;+!Microsoft.Usage#CA2217;+!Microsoft.Usage#CA2212;+!Microsoft.Usage#CA2219;+!Microsoft.Usage#CA2201;+!Microsoft.Usage#CA2228;+!Microsoft.Usage#CA2221;+!Microsoft.Usage#CA2220;+!Microsoft.Usage#CA2240;+!Microsoft.Usage#CA2229;+!Microsoft.Usage#CA2238;+!Microsoft.Usage#CA2207;+!Microsoft.Usage#CA2208;+!Microsoft.Usage#CA2235;+!Microsoft.Usage#CA2237;+!Microsoft.Usage#CA2232;+!Microsoft.Usage#CA2223;+!Microsoft.Usage#CA2211;+!Microsoft.Usage#CA2233;+!Microsoft.Usage#CA2225;+!Microsoft.Usage#CA2226;+!Microsoft.Usage#CA2231;+!Microsoft.Usage#CA2224;+!Microsoft.Usage#CA2218;+!Microsoft.Usage#CA2234;+!Microsoft.Usage#CA2239;+!Microsoft.Usage#CA2200;+!Microsoft.Usage#CA1801;+!Microsoft.Usage#CA2242;+!Microsoft.Usage#CA2205;+!Microsoft.Usage#CA2230</CodeAnalysisRules>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
- <DebugSymbols>true</DebugSymbols>
- <DebugType>full</DebugType>
- <Optimize>false</Optimize>
-<OutputPath>$(SolutionDir)..\Bin\Debug\</OutputPath>
- <DefineConstants>DEBUG;TRACE;$(SignedSym)</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <RunCodeAnalysis>false</RunCodeAnalysis>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
- <DebugType>pdbonly</DebugType>
- <Optimize>true</Optimize>
-<OutputPath>$(SolutionDir)..\Bin\Release\</OutputPath>
- <DefineConstants>TRACE;$(SignedSym)</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <RunCodeAnalysis>false</RunCodeAnalysis>
- <BaseAddress>1929379840</BaseAddress>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Silverlight Debug|AnyCPU' ">
- <DebugSymbols>true</DebugSymbols>
-<OutputPath>$(SolutionDir)..\Bin\Silverlight Debug\</OutputPath>
- <DefineConstants>TRACE;DEBUG;SILVERLIGHT</DefineConstants>
- <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <DebugType>full</DebugType>
- <PlatformTarget>AnyCPU</PlatformTarget>
- <RunCodeAnalysis>false</RunCodeAnalysis>
- <ErrorReport>prompt</ErrorReport>
- <NoStdLib>true</NoStdLib>
- <NoWarn>1591,618</NoWarn>
- <SilverlightBuild>true</SilverlightBuild>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Silverlight Release|AnyCPU' ">
-<OutputPath>$(SolutionDir)..\Bin\Silverlight Release\</OutputPath>
- <DefineConstants>TRACE;SILVERLIGHT</DefineConstants>
- <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <NoWarn>1591,618</NoWarn>
- <NoStdLib>true</NoStdLib>
- <DebugType>pdbonly</DebugType>
- <PlatformTarget>AnyCPU</PlatformTarget>
- <ErrorReport>prompt</ErrorReport>
- <SilverlightBuild>true</SilverlightBuild>
- </PropertyGroup>
- <ItemGroup>
- <Reference Include="System" Condition=" '$(SilverlightBuild)' != 'true' " />
- <Reference Include="mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e" Condition=" '$(SilverlightBuild)' == 'true' ">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>$(SilverlightPath)\mscorlib.dll</HintPath>
- </Reference>
- <Reference Include="System, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e" Condition=" '$(SilverlightBuild)' == 'true' ">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>$(SilverlightPath)\System.dll</HintPath>
- </Reference>
- </ItemGroup>
- <ItemGroup>
- <Compile Include="..\..\Hosts\Silverlight\SilverlightVersion.cs" Condition=" '$(SilverlightBuild)' == 'true' ">
- <Link>Properties\SilverlightVersion.cs</Link>
- </Compile>
- <Compile Include="Properties\ExtensionAssemblyInfo.cs" />
- <Compile Include="Utils\Extension.cs" />
- </ItemGroup>
- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" Condition=" '$(SilverlightTreeBuild)' != 'true' " />
- <!-- This task produces a list of Compile items. -->
- <Target Name="GetCompileItems" Outputs="@(CompileItems)">
- <CreateItem Include="%(Compile.Identity)">
- <Output TaskParameter="Include" ItemName="CompileItems" />
- </CreateItem>
- </Target>
-</Project>
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Properties/AssemblyInfo.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Properties/AssemblyInfo.cs
deleted file mode 100644
index ef2378f2ce3..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Security;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("Microsoft.Scripting")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Microsoft")]
-[assembly: AssemblyProduct("Microsoft.Scripting")]
-[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-[assembly: CLSCompliant(true)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("cabb8088-1370-43ca-ad47-1c32d3f7bd10")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Revision and Build Numbers
-// by using the '*' as shown below:
-[assembly: SecurityTransparent]
-
-[assembly: System.Resources.NeutralResourcesLanguage("en-US")]
-
-#if !SILVERLIGHT
-[assembly: AssemblyVersion("1.1.0.30")]
-[assembly: AssemblyFileVersion("1.1.0.30")]
-[assembly: AssemblyInformationalVersion("1.1")]
-#endif
-
-#if !SILVERLIGHT && !WP75
-[assembly: AllowPartiallyTrustedCallers]
-#endif
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Properties/ExtensionAssemblyInfo.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Properties/ExtensionAssemblyInfo.cs
deleted file mode 100644
index 2a2c1c0f76c..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Properties/ExtensionAssemblyInfo.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Microsoft Public License. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Microsoft Public License, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Microsoft Public License.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Security;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("Microsoft.Scripting.ExtensionAttribute")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Microsoft")]
-[assembly: AssemblyProduct("Microsoft.Scripting.ExtensionAttribute")]
-[assembly: AssemblyCopyright("� Microsoft Corporation. All rights reserved.")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-[assembly: CLSCompliant(true)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("b828a36d-f568-48a7-9bdd-412b0a1bfa32")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Revision and Build Numbers
-// by using the '*' as shown below:
-[assembly: SecurityTransparent]
-
-[assembly: System.Resources.NeutralResourcesLanguage("en-US")]
-
-#if !SILVERLIGHT
-[assembly: AssemblyVersion("2.0.0.0")] // shouldn't change, this assembly is unchanged. This is the version it originally shipped as.
-[assembly: AssemblyFileVersion("1.0.1.00")]
-[assembly: AssemblyInformationalVersion("1.0.1")]
-[assembly: AllowPartiallyTrustedCallers]
-#endif
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Stubs.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Stubs.cs
deleted file mode 100644
index 26ee3b4651b..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Stubs.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Diagnostics;
-
-namespace Microsoft.Scripting.Utils {
-
-}
-
-#if !FEATURE_SERIALIZATION
-
-namespace System {
- /// <summary>
- /// The serializable attribute.
- /// </summary>
- [Conditional("STUB")]
- internal class SerializableAttribute : Attribute {
- }
-
- /// <summary>
- /// Non serializable attribute.
- /// </summary>
- [Conditional("STUB")]
- internal class NonSerializedAttribute : Attribute {
- }
-
- namespace Runtime.Serialization {
- /// <summary>
- /// ISerializable interface.
- /// </summary>
- internal interface ISerializable {
- }
- }
-}
-
-#endif
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/System.Core.csproj b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/System.Core.csproj
deleted file mode 100644
index 87e0f80b87d..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/System.Core.csproj
+++ /dev/null
@@ -1,245 +0,0 @@
-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
-
-
-
- <PropertyGroup>
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
- <ProductVersion>10.0.20624</ProductVersion>
- <SchemaVersion>2.0</SchemaVersion>
- <ProjectGuid>{2AE75F5A-CD1F-4925-9647-AF4D1C282FB4}</ProjectGuid>
- <OutputType>Library</OutputType>
- <AppDesignerFolder>Properties</AppDesignerFolder>
- <RootNamespace>System.Scripting</RootNamespace>
- <AssemblyName>System.Core</AssemblyName>
-<DocumentationFile>$(OutputPath)\System.Core.XML</DocumentationFile>
- <NoWarn>1591</NoWarn>
- <OldToolsVersion>2.0</OldToolsVersion>
- <AssemblyOriginatorKeyFile>$(SolutionDir)..\Internal\MSSharedLibKey.snk</AssemblyOriginatorKeyFile>
- <SignAssembly Condition="'$(SignAssembly)' == '' And Exists('$(AssemblyOriginatorKeyFile)')">true</SignAssembly>
- <SignedSym Condition="'$(SignAssembly)' == 'true'">SIGNED</SignedSym>
- <DelaySign>true</DelaySign>
- <BaseAddress>855638016</BaseAddress>
- <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'FxCop|AnyCPU' ">
- <DebugType>pdbonly</DebugType>
- <Optimize>true</Optimize>
-<OutputPath>$(SolutionDir)..\bin\fxcop\</OutputPath>
- <DefineConstants>TRACE;$(SignedSym)</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <RunCodeAnalysis>true</RunCodeAnalysis>
- <CodeAnalysisRules>-Microsoft.Usage#CA2209;+!Microsoft.Design#CA1012;-!Microsoft.Design#CA2210;+!Microsoft.Design#CA1040;+!Microsoft.Design#CA1005;+!Microsoft.Design#CA1020;-!Microsoft.Design#CA1021;+!Microsoft.Design#CA1010;+!Microsoft.Design#CA1011;+!Microsoft.Design#CA1009;+!Microsoft.Design#CA1050;+!Microsoft.Design#CA1026;+!Microsoft.Design#CA1019;+!Microsoft.Design#CA1031;+!Microsoft.Design#CA1047;+!Microsoft.Design#CA1000;+!Microsoft.Design#CA1048;+!Microsoft.Design#CA1051;+!Microsoft.Design#CA1002;+!Microsoft.Design#CA1061;+!Microsoft.Design#CA1006;+!Microsoft.Design#CA1046;+!Microsoft.Design#CA1045;+!Microsoft.Design#CA1065;+!Microsoft.Design#CA1038;+!Microsoft.Design#CA1008;+!Microsoft.Design#CA1028;+!Microsoft.Design#CA1064;-!Microsoft.Design#CA1004;+!Microsoft.Design#CA1035;+!Microsoft.Design#CA1063;+!Microsoft.Design#CA1032;+!Microsoft.Design#CA1023;+!Microsoft.Design#CA1033;+!Microsoft.Design#CA1039;+!Microsoft.Design#CA1016;+!Microsoft.Design#CA1014;+!Microsoft.Design#CA1017;+!Microsoft.Design#CA1018;+!Microsoft.Design#CA1027;+!Microsoft.Design#CA1059;+!Microsoft.Design#CA1060;+!Microsoft.Design#CA1034;+!Microsoft.Design#CA1013;+!Microsoft.Design#CA1036;+!Microsoft.Design#CA1044;+!Microsoft.Design#CA1041;+!Microsoft.Design#CA1025;+!Microsoft.Design#CA1052;+!Microsoft.Design#CA1053;+!Microsoft.Design#CA1057;+!Microsoft.Design#CA1058;+!Microsoft.Design#CA1001;+!Microsoft.Design#CA1049;+!Microsoft.Design#CA1054;+!Microsoft.Design#CA1056;+!Microsoft.Design#CA1055;+!Microsoft.Design#CA1030;+!Microsoft.Design#CA1003;+!Microsoft.Design#CA1007;+!Microsoft.Design#CA1043;+!Microsoft.Design#CA1024;+!Microsoft.Globalization#CA1301;+!Microsoft.Globalization#CA1302;+!Microsoft.Globalization#CA1308;+!Microsoft.Globalization#CA1306;+!Microsoft.Globalization#CA1304;+!Microsoft.Globalization#CA1305;+!Microsoft.Globalization#CA2101;+!Microsoft.Globalization#CA1300;+!Microsoft.Globalization#CA1307;+!Microsoft.Globalization#CA1309;+!Microsoft.Interoperability#CA1403;+!Microsoft.Interoperability#CA1406;+!Microsoft.Interoperability#CA1413;+!Microsoft.Interoperability#CA1402;+!Microsoft.Interoperability#CA1407;+!Microsoft.Interoperability#CA1404;+!Microsoft.Interoperability#CA1410;+!Microsoft.Interoperability#CA1411;+!Microsoft.Interoperability#CA1405;+!Microsoft.Interoperability#CA1409;+!Microsoft.Interoperability#CA1415;+!Microsoft.Interoperability#CA1408;+!Microsoft.Interoperability#CA1414;+!Microsoft.Interoperability#CA1412;+!Microsoft.Interoperability#CA1400;+!Microsoft.Interoperability#CA1401;+!Microsoft.Maintainability#CA1506;+!Microsoft.Maintainability#CA1502;+!Microsoft.Maintainability#CA1501;+!Microsoft.Maintainability#CA1505;+!Microsoft.Maintainability#CA1504;+!Microsoft.Maintainability#CA1500;+!Microsoft.Mobility#CA1600;+!Microsoft.Mobility#CA1601;-!Microsoft.Naming#CA1702;+!Microsoft.Naming#CA1700;+!Microsoft.Naming#CA1712;+!Microsoft.Naming#CA1713;+!Microsoft.Naming#CA1714;+!Microsoft.Naming#CA1709;-!Microsoft.Naming#CA1704;+!Microsoft.Naming#CA1708;+!Microsoft.Naming#CA1715;-!Microsoft.Naming#CA1710;-!Microsoft.Naming#CA1720;+!Microsoft.Naming#CA1707;+!Microsoft.Naming#CA1722;-!Microsoft.Naming#CA1711;+!Microsoft.Naming#CA1716;+!Microsoft.Naming#CA1717;+!Microsoft.Naming#CA1725;+!Microsoft.Naming#CA1719;+!Microsoft.Naming#CA1721;+!Microsoft.Naming#CA1701;+!Microsoft.Naming#CA1703;+!Microsoft.Naming#CA1724;-!Microsoft.Naming#CA1726;+!Microsoft.Performance#CA1809;+!Microsoft.Performance#CA1811;+!Microsoft.Performance#CA1812;+!Microsoft.Performance#CA1813;+!Microsoft.Performance#CA1823;+!Microsoft.Performance#CA1800;+!Microsoft.Performance#CA1805;+!Microsoft.Performance#CA1810;+!Microsoft.Performance#CA1824;+!Microsoft.Performance#CA1822;+!Microsoft.Performance#CA1815;+!Microsoft.Performance#CA1814;+!Microsoft.Performance#CA1819;+!Microsoft.Performance#CA1821;+!Microsoft.Performance#CA1804;+!Microsoft.Performance#CA1820;+!Microsoft.Performance#CA1802;+!Microsoft.Portability#CA1901;+!Microsoft.Portability#CA1900;+!Microsoft.Reliability#CA2001;+!Microsoft.Reliability#CA2002;+!Microsoft.Reliability#CA2003;+!Microsoft.Reliability#CA2004;+!Microsoft.Reliability#CA2006;+!Microsoft.Security#CA2116;+!Microsoft.Security#CA2117;+!Microsoft.Security#CA2105;+!Microsoft.Security#CA2115;+!Microsoft.Security#CA2102;+!Microsoft.Security#CA2104;+!Microsoft.Security#CA2122;+!Microsoft.Security#CA2114;+!Microsoft.Security#CA2123;+!Microsoft.Security#CA2111;+!Microsoft.Security#CA2108;+!Microsoft.Security#CA2107;+!Microsoft.Security#CA2103;+!Microsoft.Security#CA2118;+!Microsoft.Security#CA2109;+!Microsoft.Security#CA2119;+!Microsoft.Security#CA2106;+!Microsoft.Security#CA2112;+!Microsoft.Security#CA2120;+!Microsoft.Security#CA2121;+!Microsoft.Security#CA2126;+!Microsoft.Security#CA2124;+!Microsoft.Security#CA2127;+!Microsoft.Security#CA2128;+!Microsoft.Security#CA2129;+!Microsoft.Usage#CA2243;+!Microsoft.Usage#CA2236;+!Microsoft.Usage#CA1816;+!Microsoft.Usage#CA2227;+!Microsoft.Usage#CA2213;+!Microsoft.Usage#CA2216;+!Microsoft.Usage#CA2214;+!Microsoft.Usage#CA2222;+!Microsoft.Usage#CA1806;+!Microsoft.Usage#CA2217;+!Microsoft.Usage#CA2212;+!Microsoft.Usage#CA2219;+!Microsoft.Usage#CA2201;+!Microsoft.Usage#CA2228;+!Microsoft.Usage#CA2221;+!Microsoft.Usage#CA2220;+!Microsoft.Usage#CA2240;+!Microsoft.Usage#CA2229;+!Microsoft.Usage#CA2238;+!Microsoft.Usage#CA2207;+!Microsoft.Usage#CA2208;+!Microsoft.Usage#CA2235;+!Microsoft.Usage#CA2237;+!Microsoft.Usage#CA2232;+!Microsoft.Usage#CA2223;+!Microsoft.Usage#CA2211;+!Microsoft.Usage#CA2233;+!Microsoft.Usage#CA2225;+!Microsoft.Usage#CA2226;+!Microsoft.Usage#CA2231;+!Microsoft.Usage#CA2224;+!Microsoft.Usage#CA2218;+!Microsoft.Usage#CA2234;+!Microsoft.Usage#CA2239;+!Microsoft.Usage#CA2200;+!Microsoft.Usage#CA1801;+!Microsoft.Usage#CA2242;+!Microsoft.Usage#CA2205;+!Microsoft.Usage#CA2230</CodeAnalysisRules>
- <NoWarn>
- </NoWarn>
- <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'v2Debug|AnyCPU' ">
- <DebugSymbols>true</DebugSymbols>
- <DebugType>full</DebugType>
- <Optimize>false</Optimize>
-<OutputPath>$(SolutionDir)..\bin\v2Debug\</OutputPath>
-<DocumentationFile>$(OutputPath)\System.Core.xml</DocumentationFile>
- <DefineConstants>DEBUG;TRACE;$(SignedSym)</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <RunCodeAnalysis>false</RunCodeAnalysis>
- <NoWarn>
- </NoWarn>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'v2Release|AnyCPU' ">
- <DebugType>pdbonly</DebugType>
- <Optimize>true</Optimize>
-<OutputPath>$(SolutionDir)..\Bin\v2Release\</OutputPath>
-<DocumentationFile>$(OutputPath)\System.Scripting.Core.xml</DocumentationFile>
- <DefineConstants>TRACE;$(SignedSym)</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <RunCodeAnalysis>false</RunCodeAnalysis>
- <NoWarn>
- </NoWarn>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Silverlight3Debug|AnyCPU' ">
- <DebugSymbols>true</DebugSymbols>
-<OutputPath>$(SolutionDir)..\bin\Silverlight3Debug\</OutputPath>
- <DefineConstants>TRACE;DEBUG;SILVERLIGHT</DefineConstants>
- <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <DebugType>full</DebugType>
- <PlatformTarget>AnyCPU</PlatformTarget>
- <RunCodeAnalysis>false</RunCodeAnalysis>
- <ErrorReport>prompt</ErrorReport>
- <NoStdLib>true</NoStdLib>
-<DocumentationFile>$(OutputPath)\System.Scripting.Core.xml</DocumentationFile>
- <NoWarn>618</NoWarn>
- <SilverlightBuild>true</SilverlightBuild>
- <SilverlightSdkPath>$(ProgramFiles)\Microsoft Silverlight\2.0.31005.0</SilverlightSdkPath>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Silverlight3Release|AnyCPU' ">
-<OutputPath>$(SolutionDir)..\bin\Silverlight3Release\</OutputPath>
- <DefineConstants>TRACE;SILVERLIGHT</DefineConstants>
-<DocumentationFile>$(OutputPath)\System.Scripting.Core.xml</DocumentationFile>
- <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <NoWarn>618</NoWarn>
- <NoStdLib>true</NoStdLib>
- <DebugType>pdbonly</DebugType>
- <PlatformTarget>AnyCPU</PlatformTarget>
- <ErrorReport>prompt</ErrorReport>
- <SilverlightBuild>true</SilverlightBuild>
- <SilverlightSdkPath>$(ProgramFiles)\Microsoft Silverlight\2.0.31005.0</SilverlightSdkPath>
- </PropertyGroup>
- <ItemGroup>
- <Reference Include="System" Condition=" $(SilverlightBuild) != 'true' " />
- <Reference Include="System.Configuration" Condition=" $(SilverlightBuild) != 'true' " />
- <Reference Include="mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e" Condition=" '$(SilverlightBuild)' == 'true' ">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>$(SilverlightSdkPath)\mscorlib.dll</HintPath>
- </Reference>
- <Reference Include="System, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e" Condition=" '$(SilverlightBuild)' == 'true' ">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>$(SilverlightSdkPath)\System.dll</HintPath>
- </Reference>
- <Reference Include="System.Data" Condition=" $(SilverlightBuild) != 'true' " />
- <Reference Include="System.Xml" Condition=" $(SilverlightBuild) != 'true' " />
- </ItemGroup>
- <ItemGroup>
- <Compile Include="..\..\Hosts\Silverlight\SilverlightVersion.cs" Condition=" '$(SilverlightBuild)' == 'true' ">
- <Link>Properties\SilverlightVersion.cs</Link>
- </Compile>
- <Compile Include="Actions\CallInfo.cs" />
- <Compile Include="Actions\CallSiteOps.cs" />
- <Compile Include="Actions\InvokeMemberBinder.cs" />
- <Compile Include="Actions\BinaryOperationBinder.cs" />
- <Compile Include="Actions\CallSite.cs" />
- <Compile Include="Actions\CallSiteBinder.cs" />
- <Compile Include="Actions\CallSiteHelpers.cs" />
- <Compile Include="Actions\ConvertBinder.cs" />
- <Compile Include="Actions\DeleteIndexBinder.cs" />
- <Compile Include="Actions\DynamicObject.cs" />
- <Compile Include="Actions\ExpandoObject.cs" />
- <Compile Include="Actions\ExpandoClass.cs" />
- <Compile Include="Actions\GetIndexBinder.cs" />
- <Compile Include="Actions\CreateInstanceBinder.cs" />
- <Compile Include="Actions\DeleteMemberBinder.cs" />
- <Compile Include="Actions\GetMemberBinder.cs" />
- <Compile Include="Actions\IDynamicMetaObjectProvider.cs" />
- <Compile Include="Actions\InvokeBinder.cs" />
- <Compile Include="Actions\DynamicMetaObject.cs" />
- <Compile Include="Actions\DynamicMetaObjectBinder.cs" />
- <Compile Include="Actions\BindingRestrictions.cs" />
- <Compile Include="Actions\RuleCache.cs" />
- <Compile Include="Actions\SetIndexBinder.cs" />
- <Compile Include="Actions\SetMemberBinder.cs" />
- <Compile Include="Ast\Expression.DebuggerProxy.cs" />
- <Compile Include="Ast\IArgumentProvider.cs" />
- <Compile Include="Ast\ListArgumentProvider.cs" />
- <Compile Include="Actions\UnaryOperationBinder.cs" />
- <Compile Include="Ast\ExpressionStringBuilder.cs" />
- <Compile Include="Compiler\BoundConstants.cs" />
- <Compile Include="Ast\DebugInfoExpression.cs" />
- <Compile Include="Ast\SymbolDocumentInfo.cs" />
- <Compile Include="Compiler\DelegateHelpers.cs" />
- <Compile Include="Compiler\DelegateHelpers.Generated.cs" />
- <Compile Include="Ast\GotoExpression.cs" />
- <Compile Include="Compiler\LabelInfo.cs" />
- <Compile Include="Compiler\AnalyzedTree.cs" />
- <Compile Include="Compiler\OffsetTrackingILGenerator.cs" />
- <Compile Include="Compiler\RuntimeVariableList.cs" />
- <Compile Include="Actions\UpdateDelegates.Generated.cs" />
- <Compile Include="Ast\DynamicExpression.cs" />
- <Compile Include="Ast\BinaryExpression.cs" />
- <Compile Include="Ast\BlockExpression.cs" />
- <Compile Include="Ast\CatchBlock.cs" />
- <Compile Include="Ast\ConditionalExpression.cs" />
- <Compile Include="Ast\ConstantExpression.cs" />
- <Compile Include="Ast\DefaultExpression.cs" />
- <Compile Include="Ast\ElementInit.cs" />
- <Compile Include="Ast\Expression.cs" />
- <Compile Include="Ast\ExpressionType.cs" />
- <Compile Include="Ast\IndexExpression.cs" />
- <Compile Include="Ast\InvocationExpression.cs" />
- <Compile Include="Ast\LabelTarget.cs" />
- <Compile Include="Ast\LabelExpression.cs" />
- <Compile Include="Ast\LambdaExpression.cs" />
- <Compile Include="Ast\ListInitExpression.cs" />
- <Compile Include="Ast\RuntimeVariablesExpression.cs" />
- <Compile Include="Ast\LoopExpression.cs" />
- <Compile Include="Ast\MemberAssignment.cs" />
- <Compile Include="Ast\MemberBinding.cs" />
- <Compile Include="Ast\MemberExpression.cs" />
- <Compile Include="Ast\MemberInitExpression.cs" />
- <Compile Include="Ast\MemberListBinding.cs" />
- <Compile Include="Ast\MemberMemberBinding.cs" />
- <Compile Include="Ast\MethodCallExpression.cs" />
- <Compile Include="Ast\NewArrayExpression.cs" />
- <Compile Include="Ast\NewExpression.cs" />
- <Compile Include="Ast\ParameterExpression.cs" />
- <Compile Include="Ast\SwitchCase.cs" />
- <Compile Include="Ast\SwitchExpression.cs" />
- <Compile Include="Ast\TryExpression.cs" />
- <Compile Include="Ast\TypeBinaryExpression.cs" />
- <Compile Include="Ast\TypeUtils.cs" />
- <Compile Include="Ast\UnaryExpression.cs" />
- <Compile Include="Compiler\Closure.cs" />
- <Compile Include="Compiler\CompilerScope.Storage.cs" />
- <Compile Include="Compiler\CompilerScope.cs" />
- <Compile Include="Compiler\ConstantCheck.cs" />
- <Compile Include="Compiler\ExpressionQuoter.cs" />
- <Compile Include="Ast\ExpressionVisitor.cs" />
- <Compile Include="Ast\DebugViewWriter.cs" />
- <Compile Include="Compiler\HoistedLocals.cs" />
- <Compile Include="Compiler\KeyedQueue.cs" />
- <Compile Include="Compiler\LambdaCompiler.Address.cs" />
- <Compile Include="Compiler\LambdaCompiler.Binary.cs" />
- <Compile Include="Compiler\LambdaCompiler.ControlFlow.cs" />
- <Compile Include="Compiler\LambdaCompiler.Expressions.cs" />
- <Compile Include="Compiler\LambdaCompiler.Generated.cs" />
- <Compile Include="Compiler\LambdaCompiler.Lambda.cs" />
- <Compile Include="Compiler\LambdaCompiler.Logical.cs" />
- <Compile Include="Compiler\LambdaCompiler.Statements.cs" />
- <Compile Include="Compiler\LambdaCompiler.Unary.cs" />
- <Compile Include="Compiler\LambdaCompiler.cs" />
- <Compile Include="Compiler\DebugInfoGenerator.cs" />
- <Compile Include="Compiler\Set.cs" />
- <Compile Include="Compiler\StackSpiller.Bindings.cs" />
- <Compile Include="Compiler\StackSpiller.Generated.cs" />
- <Compile Include="Compiler\StackSpiller.Temps.cs" />
- <Compile Include="Compiler\StackSpiller.cs" />
- <Compile Include="Compiler\SymbolDocumentGenerator.cs" />
- <Compile Include="Compiler\VariableBinder.cs" />
- <Compile Include="Compiler\AssemblyGen.cs" />
- <Compile Include="Compiler\ILGen.cs" />
- <Compile Include="GlobalSuppressions.cs" />
- <Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="Utils\Action.cs" />
- <Compile Include="Utils\CacheDict.cs" />
- <Compile Include="Utils\CollectionExtensions.cs" />
- <Compile Include="Utils\ContractUtils.cs" />
- <Compile Include="Utils\ExceptionFactory.Generated.cs" />
- <Compile Include="Utils\Function.cs" />
- <Compile Include="Utils\Helpers.cs" />
- <Compile Include="Utils\IRuntimeVariables.cs" />
- <Compile Include="Utils\ReadOnlyCollectionBuilder.cs" />
- <Compile Include="Utils\ReadOnlyDictionary.cs" />
- <Compile Include="Utils\ReferenceEqualityComparer.cs" />
- <Compile Include="Utils\StrongBox.cs" />
- <Compile Include="Utils\TrueReadOnlyCollection.cs" />
- <Compile Include="Utils\TypeExtensions.cs" />
- <Compile Include="Stubs.cs" />
- </ItemGroup>
- <ItemGroup>
- <Content Include="..\..\System\Linq\Expressions\System.Linq.Expressions.txt">
- <Link>Ast\System.Linq.Expressions.txt</Link>
- </Content>
- </ItemGroup>
- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" Condition=" '$(SilverlightTreeBuild)' != 'true' " />
- <!-- This task produces a list of Compile items. -->
- <Target Name="GetCompileItems" Outputs="@(CompileItems)">
- <CreateItem Include="%(Compile.Identity)">
- <Output TaskParameter="Include" ItemName="CompileItems" />
- </CreateItem>
- </Target>
-</Project>
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Action.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Action.cs
deleted file mode 100644
index 3f1c1540564..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Action.cs
+++ /dev/null
@@ -1,609 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_FUNCS_5_16
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Utils {
-#else
-namespace System {
-#endif
-
- #region Generated Action Types
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_action_types from: generate_dynsites.py
-
-#if !FEATURE_VARIANCE
-
- /// <summary>
- /// Encapsulates a method that takes five parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<T1, T2, T3, T4, T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
-
- /// <summary>
- /// Encapsulates a method that takes six parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<T1, T2, T3, T4, T5, T6>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
-
- /// <summary>
- /// Encapsulates a method that takes seven parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<T1, T2, T3, T4, T5, T6, T7>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
-
- /// <summary>
- /// Encapsulates a method that takes eight parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<T1, T2, T3, T4, T5, T6, T7, T8>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
-
- /// <summary>
- /// Encapsulates a method that takes nine parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<T1, T2, T3, T4, T5, T6, T7, T8, T9>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9);
-
- /// <summary>
- /// Encapsulates a method that takes ten parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10);
-
- /// <summary>
- /// Encapsulates a method that takes eleven parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11);
-
- /// <summary>
- /// Encapsulates a method that takes twelve parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12);
-
- /// <summary>
- /// Encapsulates a method that takes thirteen parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13);
-
- /// <summary>
- /// Encapsulates a method that takes fourteen parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T14">The type of the fourteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg14">The fourteenth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14);
-
- /// <summary>
- /// Encapsulates a method that takes fifteen parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T14">The type of the fourteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T15">The type of the fifteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg14">The fourteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg15">The fifteenth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15);
-
- /// <summary>
- /// Encapsulates a method that takes sixteen parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T14">The type of the fourteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T15">The type of the fifteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T16">The type of the sixteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg14">The fourteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg15">The fifteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg16">The sixteenth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);
-#else
-
- /// <summary>
- /// Encapsulates a method that takes nine parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9);
-
- /// <summary>
- /// Encapsulates a method that takes ten parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10);
-
- /// <summary>
- /// Encapsulates a method that takes eleven parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11);
-
- /// <summary>
- /// Encapsulates a method that takes twelve parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12);
-
- /// <summary>
- /// Encapsulates a method that takes thirteen parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13);
-
- /// <summary>
- /// Encapsulates a method that takes fourteen parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T14">The type of the fourteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg14">The fourteenth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14);
-
- /// <summary>
- /// Encapsulates a method that takes fifteen parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T14">The type of the fourteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T15">The type of the fifteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg14">The fourteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg15">The fifteenth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15);
-
- /// <summary>
- /// Encapsulates a method that takes sixteen parameters and does not return a value.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T14">The type of the fourteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T15">The type of the fifteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T16">The type of the sixteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg14">The fourteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg15">The fifteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg16">The sixteenth parameter of the method that this delegate encapsulates.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);
-
-#endif
-
- // *** END GENERATED CODE ***
-
- #endregion
-}
-#endif
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/CacheDict.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/CacheDict.cs
deleted file mode 100644
index 81371c66e28..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/CacheDict.cs
+++ /dev/null
@@ -1,113 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Diagnostics;
-
-namespace System.Dynamic.Utils {
- /// <summary>
- /// Provides a dictionary-like object used for caches which holds onto a maximum
- /// number of elements specified at construction time.
- ///
- /// This class is not thread safe.
- /// </summary>
- internal class CacheDict<TKey, TValue> {
- private readonly Dictionary<TKey, KeyInfo> _dict = new Dictionary<TKey, KeyInfo>();
- private readonly LinkedList<TKey> _list = new LinkedList<TKey>();
- private readonly int _maxSize;
-
- /// <summary>
- /// Creates a dictionary-like object used for caches.
- /// </summary>
- /// <param name="maxSize">The maximum number of elements to store.</param>
- internal CacheDict(int maxSize) {
- _maxSize = maxSize;
- }
-
- /// <summary>
- /// Tries to get the value associated with 'key', returning true if it's found and
- /// false if it's not present.
- /// </summary>
- internal bool TryGetValue(TKey key, out TValue value) {
- KeyInfo storedValue;
- if (_dict.TryGetValue(key, out storedValue)) {
- LinkedListNode<TKey> node = storedValue.List;
- if (node.Previous != null) {
- // move us to the head of the list...
- _list.Remove(node);
- _list.AddFirst(node);
- }
-
- value = storedValue.Value;
- return true;
- }
-
- value = default(TValue);
- return false;
- }
-
- /// <summary>
- /// Adds a new element to the cache, replacing and moving it to the front if the
- /// element is already present.
- /// </summary>
- internal void Add(TKey key, TValue value) {
- KeyInfo keyInfo;
- if (_dict.TryGetValue(key, out keyInfo)) {
- // remove original entry from the linked list
- _list.Remove(keyInfo.List);
- } else if (_list.Count == _maxSize) {
- // we've reached capacity, remove the last used element...
- LinkedListNode<TKey> node = _list.Last;
- _list.RemoveLast();
- bool res = _dict.Remove(node.Value);
- Debug.Assert(res);
- }
-
- // add the new entry to the head of the list and into the dictionary
- LinkedListNode<TKey> listNode = new LinkedListNode<TKey>(key);
- _list.AddFirst(listNode);
- _dict[key] = new CacheDict<TKey, TValue>.KeyInfo(value, listNode);
- }
-
- /// <summary>
- /// Returns the value associated with the given key, or throws KeyNotFoundException
- /// if the key is not present.
- /// </summary>
- internal TValue this[TKey key] {
- get {
- TValue res;
- if (TryGetValue(key, out res)) {
- return res;
- }
- throw new KeyNotFoundException();
- }
- set {
- Add(key, value);
- }
- }
-
- private struct KeyInfo {
- internal readonly TValue Value;
- internal readonly LinkedListNode<TKey> List;
-
- internal KeyInfo(TValue value, LinkedListNode<TKey> list) {
- Value = value;
- List = list;
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/CollectionExtensions.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/CollectionExtensions.cs
deleted file mode 100644
index d9dcd196ae9..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/CollectionExtensions.cs
+++ /dev/null
@@ -1,202 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Utils;
-using Microsoft.Scripting.Ast;
-#else
-using System.Diagnostics.Contracts;
-using System.Linq.Expressions;
-#endif
-
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Runtime.CompilerServices;
-
-namespace System.Dynamic.Utils {
- internal static class CollectionExtensions {
- /// <summary>
- /// Wraps the provided enumerable into a ReadOnlyCollection{T}
- ///
- /// Copies all of the data into a new array, so the data can't be
- /// changed after creation. The exception is if the enumerable is
- /// already a ReadOnlyCollection{T}, in which case we just return it.
- /// </summary>
- internal static ReadOnlyCollection<T> ToReadOnly<T>(this IEnumerable<T> enumerable) {
- if (enumerable == null) {
- return EmptyReadOnlyCollection<T>.Instance;
- }
-
-#if SILVERLIGHT
- if (Expression.SilverlightQuirks) {
- // Allow any ReadOnlyCollection to be stored directly
- // (even though this is not safe)
- var r = enumerable as ReadOnlyCollection<T>;
- if (r != null) {
- return r;
- }
- }
-#endif
-
- var troc = enumerable as TrueReadOnlyCollection<T>;
- if (troc != null) {
- return troc;
- }
-
- var builder = enumerable as ReadOnlyCollectionBuilder<T>;
- if (builder != null) {
- return builder.ToReadOnlyCollection();
- }
-
- var collection = enumerable as ICollection<T>;
- if (collection != null) {
- int count = collection.Count;
- if (count == 0) {
- return EmptyReadOnlyCollection<T>.Instance;
- }
-
- T[] clone = new T[count];
- collection.CopyTo(clone, 0);
- return new TrueReadOnlyCollection<T>(clone);
- }
-
- // ToArray trims the excess space and speeds up access
- return new TrueReadOnlyCollection<T>(new List<T>(enumerable).ToArray());
- }
-
- // We could probably improve the hashing here
- internal static int ListHashCode<T>(this IEnumerable<T> list) {
- var cmp = EqualityComparer<T>.Default;
- int h = 6551;
- foreach (T t in list) {
- h ^= (h << 5) ^ cmp.GetHashCode(t);
- }
- return h;
- }
-
- internal static bool ListEquals<T>(this ICollection<T> first, ICollection<T> second) {
- if (first.Count != second.Count) {
- return false;
- }
- var cmp = EqualityComparer<T>.Default;
- var f = first.GetEnumerator();
- var s = second.GetEnumerator();
- while (f.MoveNext()) {
- s.MoveNext();
-
- if (!cmp.Equals(f.Current, s.Current)) {
- return false;
- }
- }
- return true;
- }
-
- internal static IEnumerable<U> Select<T, U>(this IEnumerable<T> enumerable, Func<T, U> select) {
- foreach (T t in enumerable) {
- yield return select(t);
- }
- }
-
- // Name needs to be different so it doesn't conflict with Enumerable.Select
- internal static U[] Map<T, U>(this ICollection<T> collection, Func<T, U> select) {
- int count = collection.Count;
- U[] result = new U[count];
- count = 0;
- foreach (T t in collection) {
- result[count++] = select(t);
- }
- return result;
- }
-
- internal static IEnumerable<T> Where<T>(this IEnumerable<T> enumerable, Func<T, bool> where) {
- foreach (T t in enumerable) {
- if (where(t)) {
- yield return t;
- }
- }
- }
-
- internal static bool Any<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
- foreach (T element in source) {
- if (predicate(element)) {
- return true;
- }
- }
- return false;
- }
-
- internal static bool All<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
- foreach (T element in source) {
- if (!predicate(element)) {
- return false;
- }
- }
- return true;
- }
-
- internal static T[] RemoveFirst<T>(this T[] array) {
- T[] result = new T[array.Length - 1];
- Array.Copy(array, 1, result, 0, result.Length);
- return result;
- }
-
- internal static T[] RemoveLast<T>(this T[] array) {
- T[] result = new T[array.Length - 1];
- Array.Copy(array, 0, result, 0, result.Length);
- return result;
- }
-
- internal static T[] AddFirst<T>(this IList<T> list, T item) {
- T[] res = new T[list.Count + 1];
- res[0] = item;
- list.CopyTo(res, 1);
- return res;
- }
-
- internal static T[] AddLast<T>(this IList<T> list, T item) {
- T[] res = new T[list.Count + 1];
- list.CopyTo(res, 0);
- res[list.Count] = item;
- return res;
- }
-
- internal static T First<T>(this IEnumerable<T> source) {
- var list = source as IList<T>;
- if (list != null) {
- return list[0];
- }
- using (var e = source.GetEnumerator()) {
- if (e.MoveNext()) return e.Current;
- }
- throw new InvalidOperationException();
- }
-
- internal static T Last<T>(this IList<T> list) {
- return list[list.Count - 1];
- }
-
- internal static T[] Copy<T>(this T[] array) {
- T[] copy = new T[array.Length];
- Array.Copy(array, copy, array.Length);
- return copy;
- }
- }
-
-
- internal static class EmptyReadOnlyCollection<T> {
- internal static ReadOnlyCollection<T> Instance = new TrueReadOnlyCollection<T>(new T[0]);
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ContractUtils.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ContractUtils.cs
deleted file mode 100644
index 26f809e0359..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ContractUtils.cs
+++ /dev/null
@@ -1,97 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-#else
-using System.Linq.Expressions;
-#endif
-#if SILVERLIGHT
-using System.Core;
-#endif
-
-using System.Collections.Generic;
-using System.Diagnostics;
-
-namespace System.Dynamic.Utils {
-
- // Will be replaced with CLRv4 managed contracts
- internal static class ContractUtils {
-
- internal static Exception Unreachable {
- get {
- Debug.Assert(false, "Unreachable");
- return new InvalidOperationException("Code supposed to be unreachable");
- }
- }
-
- internal static void Requires(bool precondition) {
- if (!precondition) {
- throw new ArgumentException(Strings.MethodPreconditionViolated);
- }
- }
-
- internal static void Requires(bool precondition, string paramName) {
- Debug.Assert(!string.IsNullOrEmpty(paramName));
-
- if (!precondition) {
- throw new ArgumentException(Strings.InvalidArgumentValue, paramName);
- }
- }
-
- internal static void RequiresNotNull(object value, string paramName) {
- Debug.Assert(!string.IsNullOrEmpty(paramName));
-
- if (value == null) {
- throw new ArgumentNullException(paramName);
- }
- }
-
- internal static void RequiresNotEmpty<T>(ICollection<T> collection, string paramName) {
- RequiresNotNull(collection, paramName);
- if (collection.Count == 0) {
- throw new ArgumentException(Strings.NonEmptyCollectionRequired, paramName);
- }
- }
-
- /// <summary>
- /// Requires the range [offset, offset + count] to be a subset of [0, array.Count].
- /// </summary>
- /// <exception cref="ArgumentNullException">Array is <c>null</c>.</exception>
- /// <exception cref="ArgumentOutOfRangeException">Offset or count are out of range.</exception>
- internal static void RequiresArrayRange<T>(IList<T> array, int offset, int count, string offsetName, string countName) {
- Debug.Assert(!string.IsNullOrEmpty(offsetName));
- Debug.Assert(!string.IsNullOrEmpty(countName));
- Debug.Assert(array != null);
-
- if (count < 0) throw new ArgumentOutOfRangeException(countName);
- if (offset < 0 || array.Count - offset < count) throw new ArgumentOutOfRangeException(offsetName);
- }
-
- /// <summary>
- /// Requires the array and all its items to be non-null.
- /// </summary>
- internal static void RequiresNotNullItems<T>(IList<T> array, string arrayName) {
- Debug.Assert(arrayName != null);
- RequiresNotNull(array, arrayName);
-
- for (int i = 0; i < array.Count; i++) {
- if (array[i] == null) {
- throw new ArgumentNullException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}[{1}]", arrayName, i));
- }
- }
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ExceptionFactory.Generated.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ExceptionFactory.Generated.cs
deleted file mode 100644
index 5cc9f88a4e5..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ExceptionFactory.Generated.cs
+++ /dev/null
@@ -1,2729 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Ast {
-#else
-namespace System.Linq.Expressions {
-#endif
-
- internal static partial class Strings {
- private static string FormatString(string format, params object[] args) {
- return string.Format(System.Globalization.CultureInfo.CurrentCulture, format, args);
- }
- }
-
- #region Generated Exception Factory
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_expr_factory_core from: generate_exception_factory.py
-
- /// <summary>
- /// Strongly-typed and parameterized string factory.
- /// </summary>
-
- internal static partial class Strings {
- /// <summary>
- /// A string like "Method precondition violated"
- /// </summary>
- internal static string MethodPreconditionViolated {
- get {
- return "Method precondition violated";
- }
- }
-
- /// <summary>
- /// A string like "Invalid argument value"
- /// </summary>
- internal static string InvalidArgumentValue {
- get {
- return "Invalid argument value";
- }
- }
-
- /// <summary>
- /// A string like "Non-empty collection required"
- /// </summary>
- internal static string NonEmptyCollectionRequired {
- get {
- return "Non-empty collection required";
- }
- }
-
- /// <summary>
- /// A string like "Argument count must be greater than number of named arguments."
- /// </summary>
- internal static string ArgCntMustBeGreaterThanNameCnt {
- get {
- return "Argument count must be greater than number of named arguments.";
- }
- }
-
- /// <summary>
- /// A string like "reducible nodes must override Expression.Reduce()"
- /// </summary>
- internal static string ReducibleMustOverrideReduce {
- get {
- return "reducible nodes must override Expression.Reduce()";
- }
- }
-
- /// <summary>
- /// A string like "node cannot reduce to itself or null"
- /// </summary>
- internal static string MustReduceToDifferent {
- get {
- return "node cannot reduce to itself or null";
- }
- }
-
- /// <summary>
- /// A string like "cannot assign from the reduced node type to the original node type"
- /// </summary>
- internal static string ReducedNotCompatible {
- get {
- return "cannot assign from the reduced node type to the original node type";
- }
- }
-
- /// <summary>
- /// A string like "Setter must have parameters."
- /// </summary>
- internal static string SetterHasNoParams {
- get {
- return "Setter must have parameters.";
- }
- }
-
- /// <summary>
- /// A string like "Property cannot have a managed pointer type."
- /// </summary>
- internal static string PropertyCannotHaveRefType {
- get {
- return "Property cannot have a managed pointer type.";
- }
- }
-
- /// <summary>
- /// A string like "Indexing parameters of getter and setter must match."
- /// </summary>
- internal static string IndexesOfSetGetMustMatch {
- get {
- return "Indexing parameters of getter and setter must match.";
- }
- }
-
- /// <summary>
- /// A string like "Accessor method should not have VarArgs."
- /// </summary>
- internal static string AccessorsCannotHaveVarArgs {
- get {
- return "Accessor method should not have VarArgs.";
- }
- }
-
- /// <summary>
- /// A string like "Accessor indexes cannot be passed ByRef."
- /// </summary>
- internal static string AccessorsCannotHaveByRefArgs {
- get {
- return "Accessor indexes cannot be passed ByRef.";
- }
- }
-
- /// <summary>
- /// A string like "Bounds count cannot be less than 1"
- /// </summary>
- internal static string BoundsCannotBeLessThanOne {
- get {
- return "Bounds count cannot be less than 1";
- }
- }
-
- /// <summary>
- /// A string like "type must not be ByRef"
- /// </summary>
- internal static string TypeMustNotBeByRef {
- get {
- return "type must not be ByRef";
- }
- }
-
- /// <summary>
- /// A string like "Type doesn't have constructor with a given signature"
- /// </summary>
- internal static string TypeDoesNotHaveConstructorForTheSignature {
- get {
- return "Type doesn't have constructor with a given signature";
- }
- }
-
- /// <summary>
- /// A string like "Count must be non-negative."
- /// </summary>
- internal static string CountCannotBeNegative {
- get {
- return "Count must be non-negative.";
- }
- }
-
- /// <summary>
- /// A string like "arrayType must be an array type"
- /// </summary>
- internal static string ArrayTypeMustBeArray {
- get {
- return "arrayType must be an array type";
- }
- }
-
- /// <summary>
- /// A string like "Setter should have void type."
- /// </summary>
- internal static string SetterMustBeVoid {
- get {
- return "Setter should have void type.";
- }
- }
-
- /// <summary>
- /// A string like "Property type must match the value type of setter"
- /// </summary>
- internal static string PropertyTyepMustMatchSetter {
- get {
- return "Property type must match the value type of setter";
- }
- }
-
- /// <summary>
- /// A string like "Both accessors must be static."
- /// </summary>
- internal static string BothAccessorsMustBeStatic {
- get {
- return "Both accessors must be static.";
- }
- }
-
- /// <summary>
- /// A string like "Static field requires null instance, non-static field requires non-null instance."
- /// </summary>
- internal static string OnlyStaticFieldsHaveNullInstance {
- get {
- return "Static field requires null instance, non-static field requires non-null instance.";
- }
- }
-
- /// <summary>
- /// A string like "Static property requires null instance, non-static property requires non-null instance."
- /// </summary>
- internal static string OnlyStaticPropertiesHaveNullInstance {
- get {
- return "Static property requires null instance, non-static property requires non-null instance.";
- }
- }
-
- /// <summary>
- /// A string like "Static method requires null instance, non-static method requires non-null instance."
- /// </summary>
- internal static string OnlyStaticMethodsHaveNullInstance {
- get {
- return "Static method requires null instance, non-static method requires non-null instance.";
- }
- }
-
- /// <summary>
- /// A string like "Property cannot have a void type."
- /// </summary>
- internal static string PropertyTypeCannotBeVoid {
- get {
- return "Property cannot have a void type.";
- }
- }
-
- /// <summary>
- /// A string like "Can only unbox from an object or interface type to a value type."
- /// </summary>
- internal static string InvalidUnboxType {
- get {
- return "Can only unbox from an object or interface type to a value type.";
- }
- }
-
- /// <summary>
- /// A string like "Expression must be readable"
- /// </summary>
- internal static string ExpressionMustBeReadable {
- get {
- return "Expression must be readable";
- }
- }
-
- /// <summary>
- /// A string like "Expression must be writeable"
- /// </summary>
- internal static string ExpressionMustBeWriteable {
- get {
- return "Expression must be writeable";
- }
- }
-
- /// <summary>
- /// A string like "Argument must not have a value type."
- /// </summary>
- internal static string ArgumentMustNotHaveValueType {
- get {
- return "Argument must not have a value type.";
- }
- }
-
- /// <summary>
- /// A string like "must be reducible node"
- /// </summary>
- internal static string MustBeReducible {
- get {
- return "must be reducible node";
- }
- }
-
- /// <summary>
- /// A string like "All test values must have the same type."
- /// </summary>
- internal static string AllTestValuesMustHaveSameType {
- get {
- return "All test values must have the same type.";
- }
- }
-
- /// <summary>
- /// A string like "All case bodies and the default body must have the same type."
- /// </summary>
- internal static string AllCaseBodiesMustHaveSameType {
- get {
- return "All case bodies and the default body must have the same type.";
- }
- }
-
- /// <summary>
- /// A string like "Default body must be supplied if case bodies are not System.Void."
- /// </summary>
- internal static string DefaultBodyMustBeSupplied {
- get {
- return "Default body must be supplied if case bodies are not System.Void.";
- }
- }
-
- /// <summary>
- /// A string like "MethodBuilder does not have a valid TypeBuilder"
- /// </summary>
- internal static string MethodBuilderDoesNotHaveTypeBuilder {
- get {
- return "MethodBuilder does not have a valid TypeBuilder";
- }
- }
-
- /// <summary>
- /// A string like "Type must be derived from System.Delegate"
- /// </summary>
- internal static string TypeMustBeDerivedFromSystemDelegate {
- get {
- return "Type must be derived from System.Delegate";
- }
- }
-
- /// <summary>
- /// A string like "Argument type cannot be void"
- /// </summary>
- internal static string ArgumentTypeCannotBeVoid {
- get {
- return "Argument type cannot be void";
- }
- }
-
- /// <summary>
- /// A string like "Label type must be System.Void if an expression is not supplied"
- /// </summary>
- internal static string LabelMustBeVoidOrHaveExpression {
- get {
- return "Label type must be System.Void if an expression is not supplied";
- }
- }
-
- /// <summary>
- /// A string like "Type must be System.Void for this label argument"
- /// </summary>
- internal static string LabelTypeMustBeVoid {
- get {
- return "Type must be System.Void for this label argument";
- }
- }
-
- /// <summary>
- /// A string like "Quoted expression must be a lambda"
- /// </summary>
- internal static string QuotedExpressionMustBeLambda {
- get {
- return "Quoted expression must be a lambda";
- }
- }
-
- /// <summary>
- /// A string like "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables."
- /// </summary>
- internal static string VariableMustNotBeByRef(object p0, object p1) {
- return FormatString("Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables.", p0, p1);
- }
-
- /// <summary>
- /// A string like "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object."
- /// </summary>
- internal static string DuplicateVariable(object p0) {
- return FormatString("Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object.", p0);
- }
-
- /// <summary>
- /// A string like "Start and End must be well ordered"
- /// </summary>
- internal static string StartEndMustBeOrdered {
- get {
- return "Start and End must be well ordered";
- }
- }
-
- /// <summary>
- /// A string like "fault cannot be used with catch or finally clauses"
- /// </summary>
- internal static string FaultCannotHaveCatchOrFinally {
- get {
- return "fault cannot be used with catch or finally clauses";
- }
- }
-
- /// <summary>
- /// A string like "try must have at least one catch, finally, or fault clause"
- /// </summary>
- internal static string TryMustHaveCatchFinallyOrFault {
- get {
- return "try must have at least one catch, finally, or fault clause";
- }
- }
-
- /// <summary>
- /// A string like "Body of catch must have the same type as body of try."
- /// </summary>
- internal static string BodyOfCatchMustHaveSameTypeAsBodyOfTry {
- get {
- return "Body of catch must have the same type as body of try.";
- }
- }
-
- /// <summary>
- /// A string like "Extension node must override the property {0}."
- /// </summary>
- internal static string ExtensionNodeMustOverrideProperty(object p0) {
- return FormatString("Extension node must override the property {0}.", p0);
- }
-
- /// <summary>
- /// A string like "User-defined operator method '{0}' must be static."
- /// </summary>
- internal static string UserDefinedOperatorMustBeStatic(object p0) {
- return FormatString("User-defined operator method '{0}' must be static.", p0);
- }
-
- /// <summary>
- /// A string like "User-defined operator method '{0}' must not be void."
- /// </summary>
- internal static string UserDefinedOperatorMustNotBeVoid(object p0) {
- return FormatString("User-defined operator method '{0}' must not be void.", p0);
- }
-
- /// <summary>
- /// A string like "No coercion operator is defined between types '{0}' and '{1}'."
- /// </summary>
- internal static string CoercionOperatorNotDefined(object p0, object p1) {
- return FormatString("No coercion operator is defined between types '{0}' and '{1}'.", p0, p1);
- }
-
- /// <summary>
- /// A string like "The result type '{0}' of the dynamic binding produced by binder '{1}' is not compatible with the result type '{2}' expected by the call site."
- /// </summary>
- internal static string DynamicBinderResultNotAssignable(object p0, object p1, object p2) {
- return FormatString("The result type '{0}' of the dynamic binding produced by binder '{1}' is not compatible with the result type '{2}' expected by the call site.", p0, p1, p2);
- }
-
- /// <summary>
- /// A string like "The result type '{0}' of the dynamic binding produced by the object with type '{1}' for the binder '{2}' is not compatible with the result type '{3}' expected by the call site."
- /// </summary>
- internal static string DynamicObjectResultNotAssignable(object p0, object p1, object p2, object p3) {
- return FormatString("The result type '{0}' of the dynamic binding produced by the object with type '{1}' for the binder '{2}' is not compatible with the result type '{3}' expected by the call site.", p0, p1, p2, p3);
- }
-
- /// <summary>
- /// A string like "The result of the dynamic binding produced by the object with type '{0}' for the binder '{1}' needs at least one restriction."
- /// </summary>
- internal static string DynamicBindingNeedsRestrictions(object p0, object p1) {
- return FormatString("The result of the dynamic binding produced by the object with type '{0}' for the binder '{1}' needs at least one restriction.", p0, p1);
- }
-
- /// <summary>
- /// A string like "The result type '{0}' of the binder '{1}' is not compatible with the result type '{2}' expected by the call site."
- /// </summary>
- internal static string BinderNotCompatibleWithCallSite(object p0, object p1, object p2) {
- return FormatString("The result type '{0}' of the binder '{1}' is not compatible with the result type '{2}' expected by the call site.", p0, p1, p2);
- }
-
- /// <summary>
- /// A string like "The unary operator {0} is not defined for the type '{1}'."
- /// </summary>
- internal static string UnaryOperatorNotDefined(object p0, object p1) {
- return FormatString("The unary operator {0} is not defined for the type '{1}'.", p0, p1);
- }
-
- /// <summary>
- /// A string like "The binary operator {0} is not defined for the types '{1}' and '{2}'."
- /// </summary>
- internal static string BinaryOperatorNotDefined(object p0, object p1, object p2) {
- return FormatString("The binary operator {0} is not defined for the types '{1}' and '{2}'.", p0, p1, p2);
- }
-
- /// <summary>
- /// A string like "Reference equality is not defined for the types '{0}' and '{1}'."
- /// </summary>
- internal static string ReferenceEqualityNotDefined(object p0, object p1) {
- return FormatString("Reference equality is not defined for the types '{0}' and '{1}'.", p0, p1);
- }
-
- /// <summary>
- /// A string like "The operands for operator '{0}' do not match the parameters of method '{1}'."
- /// </summary>
- internal static string OperandTypesDoNotMatchParameters(object p0, object p1) {
- return FormatString("The operands for operator '{0}' do not match the parameters of method '{1}'.", p0, p1);
- }
-
- /// <summary>
- /// A string like "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'."
- /// </summary>
- internal static string OverloadOperatorTypeDoesNotMatchConversionType(object p0, object p1) {
- return FormatString("The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'.", p0, p1);
- }
-
- /// <summary>
- /// A string like "Conversion is not supported for arithmetic types without operator overloading."
- /// </summary>
- internal static string ConversionIsNotSupportedForArithmeticTypes {
- get {
- return "Conversion is not supported for arithmetic types without operator overloading.";
- }
- }
-
- /// <summary>
- /// A string like "Argument must be array"
- /// </summary>
- internal static string ArgumentMustBeArray {
- get {
- return "Argument must be array";
- }
- }
-
- /// <summary>
- /// A string like "Argument must be boolean"
- /// </summary>
- internal static string ArgumentMustBeBoolean {
- get {
- return "Argument must be boolean";
- }
- }
-
- /// <summary>
- /// A string like "The user-defined equality method '{0}' must return a boolean value."
- /// </summary>
- internal static string EqualityMustReturnBoolean(object p0) {
- return FormatString("The user-defined equality method '{0}' must return a boolean value.", p0);
- }
-
- /// <summary>
- /// A string like "Argument must be either a FieldInfo or PropertyInfo"
- /// </summary>
- internal static string ArgumentMustBeFieldInfoOrPropertInfo {
- get {
- return "Argument must be either a FieldInfo or PropertyInfo";
- }
- }
-
- /// <summary>
- /// A string like "Argument must be either a FieldInfo, PropertyInfo or MethodInfo"
- /// </summary>
- internal static string ArgumentMustBeFieldInfoOrPropertInfoOrMethod {
- get {
- return "Argument must be either a FieldInfo, PropertyInfo or MethodInfo";
- }
- }
-
- /// <summary>
- /// A string like "Argument must be an instance member"
- /// </summary>
- internal static string ArgumentMustBeInstanceMember {
- get {
- return "Argument must be an instance member";
- }
- }
-
- /// <summary>
- /// A string like "Argument must be of an integer type"
- /// </summary>
- internal static string ArgumentMustBeInteger {
- get {
- return "Argument must be of an integer type";
- }
- }
-
- /// <summary>
- /// A string like "Argument for array index must be of type Int32"
- /// </summary>
- internal static string ArgumentMustBeArrayIndexType {
- get {
- return "Argument for array index must be of type Int32";
- }
- }
-
- /// <summary>
- /// A string like "Argument must be single dimensional array type"
- /// </summary>
- internal static string ArgumentMustBeSingleDimensionalArrayType {
- get {
- return "Argument must be single dimensional array type";
- }
- }
-
- /// <summary>
- /// A string like "Argument types do not match"
- /// </summary>
- internal static string ArgumentTypesMustMatch {
- get {
- return "Argument types do not match";
- }
- }
-
- /// <summary>
- /// A string like "Cannot auto initialize elements of value type through property '{0}', use assignment instead"
- /// </summary>
- internal static string CannotAutoInitializeValueTypeElementThroughProperty(object p0) {
- return FormatString("Cannot auto initialize elements of value type through property '{0}', use assignment instead", p0);
- }
-
- /// <summary>
- /// A string like "Cannot auto initialize members of value type through property '{0}', use assignment instead"
- /// </summary>
- internal static string CannotAutoInitializeValueTypeMemberThroughProperty(object p0) {
- return FormatString("Cannot auto initialize members of value type through property '{0}', use assignment instead", p0);
- }
-
- /// <summary>
- /// A string like "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither"
- /// </summary>
- internal static string IncorrectTypeForTypeAs(object p0) {
- return FormatString("The type used in TypeAs Expression must be of reference or nullable type, {0} is neither", p0);
- }
-
- /// <summary>
- /// A string like "Coalesce used with type that cannot be null"
- /// </summary>
- internal static string CoalesceUsedOnNonNullType {
- get {
- return "Coalesce used with type that cannot be null";
- }
- }
-
- /// <summary>
- /// A string like "An expression of type '{0}' cannot be used to initialize an array of type '{1}'"
- /// </summary>
- internal static string ExpressionTypeCannotInitializeArrayType(object p0, object p1) {
- return FormatString("An expression of type '{0}' cannot be used to initialize an array of type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "Expression of type '{0}' cannot be used for constructor parameter of type '{1}'"
- /// </summary>
- internal static string ExpressionTypeDoesNotMatchConstructorParameter(object p0, object p1) {
- return FormatString("Expression of type '{0}' cannot be used for constructor parameter of type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like " Argument type '{0}' does not match the corresponding member type '{1}'"
- /// </summary>
- internal static string ArgumentTypeDoesNotMatchMember(object p0, object p1) {
- return FormatString(" Argument type '{0}' does not match the corresponding member type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like " The member '{0}' is not declared on type '{1}' being created"
- /// </summary>
- internal static string ArgumentMemberNotDeclOnType(object p0, object p1) {
- return FormatString(" The member '{0}' is not declared on type '{1}' being created", p0, p1);
- }
-
- /// <summary>
- /// A string like "Expression of type '{0}' cannot be used for parameter of type '{1}' of method '{2}'"
- /// </summary>
- internal static string ExpressionTypeDoesNotMatchMethodParameter(object p0, object p1, object p2) {
- return FormatString("Expression of type '{0}' cannot be used for parameter of type '{1}' of method '{2}'", p0, p1, p2);
- }
-
- /// <summary>
- /// A string like "Expression of type '{0}' cannot be used for parameter of type '{1}'"
- /// </summary>
- internal static string ExpressionTypeDoesNotMatchParameter(object p0, object p1) {
- return FormatString("Expression of type '{0}' cannot be used for parameter of type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "Expression of type '{0}' cannot be used for return type '{1}'"
- /// </summary>
- internal static string ExpressionTypeDoesNotMatchReturn(object p0, object p1) {
- return FormatString("Expression of type '{0}' cannot be used for return type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "Expression of type '{0}' cannot be used for assignment to type '{1}'"
- /// </summary>
- internal static string ExpressionTypeDoesNotMatchAssignment(object p0, object p1) {
- return FormatString("Expression of type '{0}' cannot be used for assignment to type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "Expression of type '{0}' cannot be used for label of type '{1}'"
- /// </summary>
- internal static string ExpressionTypeDoesNotMatchLabel(object p0, object p1) {
- return FormatString("Expression of type '{0}' cannot be used for label of type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "Expression of type '{0}' cannot be invoked"
- /// </summary>
- internal static string ExpressionTypeNotInvocable(object p0) {
- return FormatString("Expression of type '{0}' cannot be invoked", p0);
- }
-
- /// <summary>
- /// A string like "Field '{0}' is not defined for type '{1}'"
- /// </summary>
- internal static string FieldNotDefinedForType(object p0, object p1) {
- return FormatString("Field '{0}' is not defined for type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "Instance field '{0}' is not defined for type '{1}'"
- /// </summary>
- internal static string InstanceFieldNotDefinedForType(object p0, object p1) {
- return FormatString("Instance field '{0}' is not defined for type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "Field '{0}.{1}' is not defined for type '{2}'"
- /// </summary>
- internal static string FieldInfoNotDefinedForType(object p0, object p1, object p2) {
- return FormatString("Field '{0}.{1}' is not defined for type '{2}'", p0, p1, p2);
- }
-
- /// <summary>
- /// A string like "Incorrect number of indexes"
- /// </summary>
- internal static string IncorrectNumberOfIndexes {
- get {
- return "Incorrect number of indexes";
- }
- }
-
- /// <summary>
- /// A string like "Incorrect number of arguments supplied for lambda invocation"
- /// </summary>
- internal static string IncorrectNumberOfLambdaArguments {
- get {
- return "Incorrect number of arguments supplied for lambda invocation";
- }
- }
-
- /// <summary>
- /// A string like "Incorrect number of parameters supplied for lambda declaration"
- /// </summary>
- internal static string IncorrectNumberOfLambdaDeclarationParameters {
- get {
- return "Incorrect number of parameters supplied for lambda declaration";
- }
- }
-
- /// <summary>
- /// A string like "Incorrect number of arguments supplied for call to method '{0}'"
- /// </summary>
- internal static string IncorrectNumberOfMethodCallArguments(object p0) {
- return FormatString("Incorrect number of arguments supplied for call to method '{0}'", p0);
- }
-
- /// <summary>
- /// A string like "Incorrect number of arguments for constructor"
- /// </summary>
- internal static string IncorrectNumberOfConstructorArguments {
- get {
- return "Incorrect number of arguments for constructor";
- }
- }
-
- /// <summary>
- /// A string like " Incorrect number of members for constructor"
- /// </summary>
- internal static string IncorrectNumberOfMembersForGivenConstructor {
- get {
- return " Incorrect number of members for constructor";
- }
- }
-
- /// <summary>
- /// A string like "Incorrect number of arguments for the given members "
- /// </summary>
- internal static string IncorrectNumberOfArgumentsForMembers {
- get {
- return "Incorrect number of arguments for the given members ";
- }
- }
-
- /// <summary>
- /// A string like "Lambda type parameter must be derived from System.Delegate"
- /// </summary>
- internal static string LambdaTypeMustBeDerivedFromSystemDelegate {
- get {
- return "Lambda type parameter must be derived from System.Delegate";
- }
- }
-
- /// <summary>
- /// A string like "Member '{0}' not field or property"
- /// </summary>
- internal static string MemberNotFieldOrProperty(object p0) {
- return FormatString("Member '{0}' not field or property", p0);
- }
-
- /// <summary>
- /// A string like "Method {0} contains generic parameters"
- /// </summary>
- internal static string MethodContainsGenericParameters(object p0) {
- return FormatString("Method {0} contains generic parameters", p0);
- }
-
- /// <summary>
- /// A string like "Method {0} is a generic method definition"
- /// </summary>
- internal static string MethodIsGeneric(object p0) {
- return FormatString("Method {0} is a generic method definition", p0);
- }
-
- /// <summary>
- /// A string like "The method '{0}.{1}' is not a property accessor"
- /// </summary>
- internal static string MethodNotPropertyAccessor(object p0, object p1) {
- return FormatString("The method '{0}.{1}' is not a property accessor", p0, p1);
- }
-
- /// <summary>
- /// A string like "The property '{0}' has no 'get' accessor"
- /// </summary>
- internal static string PropertyDoesNotHaveGetter(object p0) {
- return FormatString("The property '{0}' has no 'get' accessor", p0);
- }
-
- /// <summary>
- /// A string like "The property '{0}' has no 'set' accessor"
- /// </summary>
- internal static string PropertyDoesNotHaveSetter(object p0) {
- return FormatString("The property '{0}' has no 'set' accessor", p0);
- }
-
- /// <summary>
- /// A string like "The property '{0}' has no 'get' or 'set' accessors"
- /// </summary>
- internal static string PropertyDoesNotHaveAccessor(object p0) {
- return FormatString("The property '{0}' has no 'get' or 'set' accessors", p0);
- }
-
- /// <summary>
- /// A string like "'{0}' is not a member of type '{1}'"
- /// </summary>
- internal static string NotAMemberOfType(object p0, object p1) {
- return FormatString("'{0}' is not a member of type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "The operator '{0}' is not implemented for type '{1}'"
- /// </summary>
- internal static string OperatorNotImplementedForType(object p0, object p1) {
- return FormatString("The operator '{0}' is not implemented for type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'"
- /// </summary>
- internal static string ParameterExpressionNotValidAsDelegate(object p0, object p1) {
- return FormatString("ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "Property '{0}' is not defined for type '{1}'"
- /// </summary>
- internal static string PropertyNotDefinedForType(object p0, object p1) {
- return FormatString("Property '{0}' is not defined for type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "Instance property '{0}' is not defined for type '{1}'"
- /// </summary>
- internal static string InstancePropertyNotDefinedForType(object p0, object p1) {
- return FormatString("Instance property '{0}' is not defined for type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "Instance property '{0}' that takes no argument is not defined for type '{1}'"
- /// </summary>
- internal static string InstancePropertyWithoutParameterNotDefinedForType(object p0, object p1) {
- return FormatString("Instance property '{0}' that takes no argument is not defined for type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "Instance property '{0}{1}' is not defined for type '{2}'"
- /// </summary>
- internal static string InstancePropertyWithSpecifiedParametersNotDefinedForType(object p0, object p1, object p2) {
- return FormatString("Instance property '{0}{1}' is not defined for type '{2}'", p0, p1, p2);
- }
-
- /// <summary>
- /// A string like "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'"
- /// </summary>
- internal static string InstanceAndMethodTypeMismatch(object p0, object p1, object p2) {
- return FormatString("Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'", p0, p1, p2);
- }
-
- /// <summary>
- /// A string like "Type {0} contains generic parameters"
- /// </summary>
- internal static string TypeContainsGenericParameters(object p0) {
- return FormatString("Type {0} contains generic parameters", p0);
- }
-
- /// <summary>
- /// A string like "Type {0} is a generic type definition"
- /// </summary>
- internal static string TypeIsGeneric(object p0) {
- return FormatString("Type {0} is a generic type definition", p0);
- }
-
- /// <summary>
- /// A string like "Type '{0}' does not have a default constructor"
- /// </summary>
- internal static string TypeMissingDefaultConstructor(object p0) {
- return FormatString("Type '{0}' does not have a default constructor", p0);
- }
-
- /// <summary>
- /// A string like "List initializers must contain at least one initializer"
- /// </summary>
- internal static string ListInitializerWithZeroMembers {
- get {
- return "List initializers must contain at least one initializer";
- }
- }
-
- /// <summary>
- /// A string like "Element initializer method must be named 'Add'"
- /// </summary>
- internal static string ElementInitializerMethodNotAdd {
- get {
- return "Element initializer method must be named 'Add'";
- }
- }
-
- /// <summary>
- /// A string like "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter"
- /// </summary>
- internal static string ElementInitializerMethodNoRefOutParam(object p0, object p1) {
- return FormatString("Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter", p0, p1);
- }
-
- /// <summary>
- /// A string like "Element initializer method must have at least 1 parameter"
- /// </summary>
- internal static string ElementInitializerMethodWithZeroArgs {
- get {
- return "Element initializer method must have at least 1 parameter";
- }
- }
-
- /// <summary>
- /// A string like "Element initializer method must be an instance method"
- /// </summary>
- internal static string ElementInitializerMethodStatic {
- get {
- return "Element initializer method must be an instance method";
- }
- }
-
- /// <summary>
- /// A string like "Type '{0}' is not IEnumerable"
- /// </summary>
- internal static string TypeNotIEnumerable(object p0) {
- return FormatString("Type '{0}' is not IEnumerable", p0);
- }
-
- /// <summary>
- /// A string like "Type parameter is {0}. Expected a delegate."
- /// </summary>
- internal static string TypeParameterIsNotDelegate(object p0) {
- return FormatString("Type parameter is {0}. Expected a delegate.", p0);
- }
-
- /// <summary>
- /// A string like "Unexpected coalesce operator."
- /// </summary>
- internal static string UnexpectedCoalesceOperator {
- get {
- return "Unexpected coalesce operator.";
- }
- }
-
- /// <summary>
- /// A string like "Cannot cast from type '{0}' to type '{1}"
- /// </summary>
- internal static string InvalidCast(object p0, object p1) {
- return FormatString("Cannot cast from type '{0}' to type '{1}", p0, p1);
- }
-
- /// <summary>
- /// A string like "Unhandled binary: {0}"
- /// </summary>
- internal static string UnhandledBinary(object p0) {
- return FormatString("Unhandled binary: {0}", p0);
- }
-
- /// <summary>
- /// A string like "Unhandled binding "
- /// </summary>
- internal static string UnhandledBinding {
- get {
- return "Unhandled binding ";
- }
- }
-
- /// <summary>
- /// A string like "Unhandled Binding Type: {0}"
- /// </summary>
- internal static string UnhandledBindingType(object p0) {
- return FormatString("Unhandled Binding Type: {0}", p0);
- }
-
- /// <summary>
- /// A string like "Unhandled convert: {0}"
- /// </summary>
- internal static string UnhandledConvert(object p0) {
- return FormatString("Unhandled convert: {0}", p0);
- }
-
- /// <summary>
- /// A string like "Unhandled Expression Type: {0}"
- /// </summary>
- internal static string UnhandledExpressionType(object p0) {
- return FormatString("Unhandled Expression Type: {0}", p0);
- }
-
- /// <summary>
- /// A string like "Unhandled unary: {0}"
- /// </summary>
- internal static string UnhandledUnary(object p0) {
- return FormatString("Unhandled unary: {0}", p0);
- }
-
- /// <summary>
- /// A string like "Unknown binding type"
- /// </summary>
- internal static string UnknownBindingType {
- get {
- return "Unknown binding type";
- }
- }
-
- /// <summary>
- /// A string like "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types."
- /// </summary>
- internal static string UserDefinedOpMustHaveConsistentTypes(object p0, object p1) {
- return FormatString("The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types.", p0, p1);
- }
-
- /// <summary>
- /// A string like "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type."
- /// </summary>
- internal static string UserDefinedOpMustHaveValidReturnType(object p0, object p1) {
- return FormatString("The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type.", p0, p1);
- }
-
- /// <summary>
- /// A string like "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators."
- /// </summary>
- internal static string LogicalOperatorMustHaveBooleanOperators(object p0, object p1) {
- return FormatString("The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators.", p0, p1);
- }
-
- /// <summary>
- /// A string like "No method '{0}' exists on type '{1}'."
- /// </summary>
- internal static string MethodDoesNotExistOnType(object p0, object p1) {
- return FormatString("No method '{0}' exists on type '{1}'.", p0, p1);
- }
-
- /// <summary>
- /// A string like "No method '{0}' on type '{1}' is compatible with the supplied arguments."
- /// </summary>
- internal static string MethodWithArgsDoesNotExistOnType(object p0, object p1) {
- return FormatString("No method '{0}' on type '{1}' is compatible with the supplied arguments.", p0, p1);
- }
-
- /// <summary>
- /// A string like "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. "
- /// </summary>
- internal static string GenericMethodWithArgsDoesNotExistOnType(object p0, object p1) {
- return FormatString("No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. ", p0, p1);
- }
-
- /// <summary>
- /// A string like "More than one method '{0}' on type '{1}' is compatible with the supplied arguments."
- /// </summary>
- internal static string MethodWithMoreThanOneMatch(object p0, object p1) {
- return FormatString("More than one method '{0}' on type '{1}' is compatible with the supplied arguments.", p0, p1);
- }
-
- /// <summary>
- /// A string like "More than one property '{0}' on type '{1}' is compatible with the supplied arguments."
- /// </summary>
- internal static string PropertyWithMoreThanOneMatch(object p0, object p1) {
- return FormatString("More than one property '{0}' on type '{1}' is compatible with the supplied arguments.", p0, p1);
- }
-
- /// <summary>
- /// A string like "An incorrect number of type args were specified for the declaration of a Func type."
- /// </summary>
- internal static string IncorrectNumberOfTypeArgsForFunc {
- get {
- return "An incorrect number of type args were specified for the declaration of a Func type.";
- }
- }
-
- /// <summary>
- /// A string like "An incorrect number of type args were specified for the declaration of an Action type."
- /// </summary>
- internal static string IncorrectNumberOfTypeArgsForAction {
- get {
- return "An incorrect number of type args were specified for the declaration of an Action type.";
- }
- }
-
- /// <summary>
- /// A string like "Argument type cannot be System.Void."
- /// </summary>
- internal static string ArgumentCannotBeOfTypeVoid {
- get {
- return "Argument type cannot be System.Void.";
- }
- }
-
- /// <summary>
- /// A string like "More than one key matching '{0}' was found in the ExpandoObject."
- /// </summary>
- internal static string AmbiguousMatchInExpandoObject(object p0) {
- return FormatString("More than one key matching '{0}' was found in the ExpandoObject.", p0);
- }
-
- /// <summary>
- /// A string like "An element with the same key '{0}' already exists in the ExpandoObject."
- /// </summary>
- internal static string SameKeyExistsInExpando(object p0) {
- return FormatString("An element with the same key '{0}' already exists in the ExpandoObject.", p0);
- }
-
- /// <summary>
- /// A string like "The specified key '{0}' does not exist in the ExpandoObject."
- /// </summary>
- internal static string KeyDoesNotExistInExpando(object p0) {
- return FormatString("The specified key '{0}' does not exist in the ExpandoObject.", p0);
- }
-
- /// <summary>
- /// A string like "No or Invalid rule produced"
- /// </summary>
- internal static string NoOrInvalidRuleProduced {
- get {
- return "No or Invalid rule produced";
- }
- }
-
- /// <summary>
- /// A string like "First argument of delegate must be CallSite"
- /// </summary>
- internal static string FirstArgumentMustBeCallSite {
- get {
- return "First argument of delegate must be CallSite";
- }
- }
-
- /// <summary>
- /// A string like "Bind cannot return null."
- /// </summary>
- internal static string BindingCannotBeNull {
- get {
- return "Bind cannot return null.";
- }
- }
-
- /// <summary>
- /// A string like "Invalid operation: '{0}'"
- /// </summary>
- internal static string InvalidOperation(object p0) {
- return FormatString("Invalid operation: '{0}'", p0);
- }
-
- /// <summary>
- /// A string like "{0} must be greater than or equal to {1}"
- /// </summary>
- internal static string OutOfRange(object p0, object p1) {
- return FormatString("{0} must be greater than or equal to {1}", p0, p1);
- }
-
- /// <summary>
- /// A string like "Queue empty."
- /// </summary>
- internal static string QueueEmpty {
- get {
- return "Queue empty.";
- }
- }
-
- /// <summary>
- /// A string like "Cannot redefine label '{0}' in an inner block."
- /// </summary>
- internal static string LabelTargetAlreadyDefined(object p0) {
- return FormatString("Cannot redefine label '{0}' in an inner block.", p0);
- }
-
- /// <summary>
- /// A string like "Cannot jump to undefined label '{0}'."
- /// </summary>
- internal static string LabelTargetUndefined(object p0) {
- return FormatString("Cannot jump to undefined label '{0}'.", p0);
- }
-
- /// <summary>
- /// A string like "Control cannot leave a finally block."
- /// </summary>
- internal static string ControlCannotLeaveFinally {
- get {
- return "Control cannot leave a finally block.";
- }
- }
-
- /// <summary>
- /// A string like "Control cannot leave a filter test."
- /// </summary>
- internal static string ControlCannotLeaveFilterTest {
- get {
- return "Control cannot leave a filter test.";
- }
- }
-
- /// <summary>
- /// A string like "Cannot jump to ambiguous label '{0}'."
- /// </summary>
- internal static string AmbiguousJump(object p0) {
- return FormatString("Cannot jump to ambiguous label '{0}'.", p0);
- }
-
- /// <summary>
- /// A string like "Control cannot enter a try block."
- /// </summary>
- internal static string ControlCannotEnterTry {
- get {
- return "Control cannot enter a try block.";
- }
- }
-
- /// <summary>
- /// A string like "Control cannot enter an expression--only statements can be jumped into."
- /// </summary>
- internal static string ControlCannotEnterExpression {
- get {
- return "Control cannot enter an expression--only statements can be jumped into.";
- }
- }
-
- /// <summary>
- /// A string like "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values."
- /// </summary>
- internal static string NonLocalJumpWithValue(object p0) {
- return FormatString("Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values.", p0);
- }
-
- /// <summary>
- /// A string like "Extension should have been reduced."
- /// </summary>
- internal static string ExtensionNotReduced {
- get {
- return "Extension should have been reduced.";
- }
- }
-
- /// <summary>
- /// A string like "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value."
- /// </summary>
- internal static string CannotCompileConstant(object p0) {
- return FormatString("CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value.", p0);
- }
-
- /// <summary>
- /// A string like "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite."
- /// </summary>
- internal static string CannotCompileDynamic {
- get {
- return "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite.";
- }
- }
-
- /// <summary>
- /// A string like "Invalid lvalue for assignment: {0}."
- /// </summary>
- internal static string InvalidLvalue(object p0) {
- return FormatString("Invalid lvalue for assignment: {0}.", p0);
- }
-
- /// <summary>
- /// A string like "Invalid member type: {0}."
- /// </summary>
- internal static string InvalidMemberType(object p0) {
- return FormatString("Invalid member type: {0}.", p0);
- }
-
- /// <summary>
- /// A string like "unknown lift type: '{0}'."
- /// </summary>
- internal static string UnknownLiftType(object p0) {
- return FormatString("unknown lift type: '{0}'.", p0);
- }
-
- /// <summary>
- /// A string like "Invalid output directory."
- /// </summary>
- internal static string InvalidOutputDir {
- get {
- return "Invalid output directory.";
- }
- }
-
- /// <summary>
- /// A string like "Invalid assembly name or file extension."
- /// </summary>
- internal static string InvalidAsmNameOrExtension {
- get {
- return "Invalid assembly name or file extension.";
- }
- }
-
- /// <summary>
- /// A string like "Collection is read-only."
- /// </summary>
- internal static string CollectionReadOnly {
- get {
- return "Collection is read-only.";
- }
- }
-
- /// <summary>
- /// A string like "Cannot create instance of {0} because it contains generic parameters"
- /// </summary>
- internal static string IllegalNewGenericParams(object p0) {
- return FormatString("Cannot create instance of {0} because it contains generic parameters", p0);
- }
-
- /// <summary>
- /// A string like "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined"
- /// </summary>
- internal static string UndefinedVariable(object p0, object p1, object p2) {
- return FormatString("variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined", p0, p1, p2);
- }
-
- /// <summary>
- /// A string like "Cannot close over byref parameter '{0}' referenced in lambda '{1}'"
- /// </summary>
- internal static string CannotCloseOverByRef(object p0, object p1) {
- return FormatString("Cannot close over byref parameter '{0}' referenced in lambda '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "Unexpected VarArgs call to method '{0}'"
- /// </summary>
- internal static string UnexpectedVarArgsCall(object p0) {
- return FormatString("Unexpected VarArgs call to method '{0}'", p0);
- }
-
- /// <summary>
- /// A string like "Rethrow statement is valid only inside a Catch block."
- /// </summary>
- internal static string RethrowRequiresCatch {
- get {
- return "Rethrow statement is valid only inside a Catch block.";
- }
- }
-
- /// <summary>
- /// A string like "Try expression is not allowed inside a filter body."
- /// </summary>
- internal static string TryNotAllowedInFilter {
- get {
- return "Try expression is not allowed inside a filter body.";
- }
- }
-
- /// <summary>
- /// A string like "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type."
- /// </summary>
- internal static string MustRewriteToSameNode(object p0, object p1, object p2) {
- return FormatString("When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type.", p0, p1, p2);
- }
-
- /// <summary>
- /// A string like "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite."
- /// </summary>
- internal static string MustRewriteChildToSameType(object p0, object p1, object p2) {
- return FormatString("Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite.", p0, p1, p2);
- }
-
- /// <summary>
- /// A string like "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is is intentional, override '{1}' and change it to allow this rewrite."
- /// </summary>
- internal static string MustRewriteWithoutMethod(object p0, object p1) {
- return FormatString("Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is is intentional, override '{1}' and change it to allow this rewrite.", p0, p1);
- }
-
- /// <summary>
- /// A string like "The value null is not of type '{0}' and cannot be used in this collection."
- /// </summary>
- internal static string InvalidNullValue(object p0) {
- return FormatString("The value null is not of type '{0}' and cannot be used in this collection.", p0);
- }
-
- /// <summary>
- /// A string like "The value '{0}' is not of type '{1}' and cannot be used in this collection."
- /// </summary>
- internal static string InvalidObjectType(object p0, object p1) {
- return FormatString("The value '{0}' is not of type '{1}' and cannot be used in this collection.", p0, p1);
- }
-
- /// <summary>
- /// A string like "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression."
- /// </summary>
- internal static string TryNotSupportedForMethodsWithRefArgs(object p0) {
- return FormatString("TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression.", p0);
- }
-
- /// <summary>
- /// A string like "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression."
- /// </summary>
- internal static string TryNotSupportedForValueTypeInstances(object p0) {
- return FormatString("TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression.", p0);
- }
-
- /// <summary>
- /// A string like "Collection was modified; enumeration operation may not execute."
- /// </summary>
- internal static string CollectionModifiedWhileEnumerating {
- get {
- return "Collection was modified; enumeration operation may not execute.";
- }
- }
-
- /// <summary>
- /// A string like "Enumeration has either not started or has already finished."
- /// </summary>
- internal static string EnumerationIsDone {
- get {
- return "Enumeration has either not started or has already finished.";
- }
- }
-
- /// <summary>
- /// A string like "Dynamic operations can only be performed in homogenous AppDomain."
- /// </summary>
- internal static string HomogenousAppDomainRequired {
- get {
- return "Dynamic operations can only be performed in homogenous AppDomain.";
- }
- }
-
- /// <summary>
- /// A string like "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"
- /// </summary>
- internal static string TestValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) {
- return FormatString("Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"
- /// </summary>
- internal static string SwitchValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) {
- return FormatString("Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'", p0, p1);
- }
-
- /// <summary>
- /// A string like "An IDynamicMetaObjectProvider {0} created an invalid DynamicMetaObject instance."
- /// </summary>
- internal static string InvalidMetaObjectCreated(object p0) {
- return FormatString("An IDynamicMetaObjectProvider {0} created an invalid DynamicMetaObject instance.", p0);
- }
-
- /// <summary>
- /// A string like "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod."
- /// </summary>
- internal static string PdbGeneratorNeedsExpressionCompiler {
- get {
- return "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod.";
- }
- }
-
- }
- /// <summary>
- /// Strongly-typed and parameterized exception factory.
- /// </summary>
-
- internal static partial class Error {
- /// <summary>
- /// ArgumentException with message like "Argument count must be greater than number of named arguments."
- /// </summary>
- internal static Exception ArgCntMustBeGreaterThanNameCnt() {
- return new ArgumentException(Strings.ArgCntMustBeGreaterThanNameCnt);
- }
-
- /// <summary>
- /// ArgumentException with message like "reducible nodes must override Expression.Reduce()"
- /// </summary>
- internal static Exception ReducibleMustOverrideReduce() {
- return new ArgumentException(Strings.ReducibleMustOverrideReduce);
- }
-
- /// <summary>
- /// ArgumentException with message like "node cannot reduce to itself or null"
- /// </summary>
- internal static Exception MustReduceToDifferent() {
- return new ArgumentException(Strings.MustReduceToDifferent);
- }
-
- /// <summary>
- /// ArgumentException with message like "cannot assign from the reduced node type to the original node type"
- /// </summary>
- internal static Exception ReducedNotCompatible() {
- return new ArgumentException(Strings.ReducedNotCompatible);
- }
-
- /// <summary>
- /// ArgumentException with message like "Setter must have parameters."
- /// </summary>
- internal static Exception SetterHasNoParams() {
- return new ArgumentException(Strings.SetterHasNoParams);
- }
-
- /// <summary>
- /// ArgumentException with message like "Property cannot have a managed pointer type."
- /// </summary>
- internal static Exception PropertyCannotHaveRefType() {
- return new ArgumentException(Strings.PropertyCannotHaveRefType);
- }
-
- /// <summary>
- /// ArgumentException with message like "Indexing parameters of getter and setter must match."
- /// </summary>
- internal static Exception IndexesOfSetGetMustMatch() {
- return new ArgumentException(Strings.IndexesOfSetGetMustMatch);
- }
-
- /// <summary>
- /// ArgumentException with message like "Accessor method should not have VarArgs."
- /// </summary>
- internal static Exception AccessorsCannotHaveVarArgs() {
- return new ArgumentException(Strings.AccessorsCannotHaveVarArgs);
- }
-
- /// <summary>
- /// ArgumentException with message like "Accessor indexes cannot be passed ByRef."
- /// </summary>
- internal static Exception AccessorsCannotHaveByRefArgs() {
- return new ArgumentException(Strings.AccessorsCannotHaveByRefArgs);
- }
-
- /// <summary>
- /// ArgumentException with message like "Bounds count cannot be less than 1"
- /// </summary>
- internal static Exception BoundsCannotBeLessThanOne() {
- return new ArgumentException(Strings.BoundsCannotBeLessThanOne);
- }
-
- /// <summary>
- /// ArgumentException with message like "type must not be ByRef"
- /// </summary>
- internal static Exception TypeMustNotBeByRef() {
- return new ArgumentException(Strings.TypeMustNotBeByRef);
- }
-
- /// <summary>
- /// ArgumentException with message like "Type doesn't have constructor with a given signature"
- /// </summary>
- internal static Exception TypeDoesNotHaveConstructorForTheSignature() {
- return new ArgumentException(Strings.TypeDoesNotHaveConstructorForTheSignature);
- }
-
- /// <summary>
- /// ArgumentException with message like "Count must be non-negative."
- /// </summary>
- internal static Exception CountCannotBeNegative() {
- return new ArgumentException(Strings.CountCannotBeNegative);
- }
-
- /// <summary>
- /// ArgumentException with message like "arrayType must be an array type"
- /// </summary>
- internal static Exception ArrayTypeMustBeArray() {
- return new ArgumentException(Strings.ArrayTypeMustBeArray);
- }
-
- /// <summary>
- /// ArgumentException with message like "Setter should have void type."
- /// </summary>
- internal static Exception SetterMustBeVoid() {
- return new ArgumentException(Strings.SetterMustBeVoid);
- }
-
- /// <summary>
- /// ArgumentException with message like "Property type must match the value type of setter"
- /// </summary>
- internal static Exception PropertyTyepMustMatchSetter() {
- return new ArgumentException(Strings.PropertyTyepMustMatchSetter);
- }
-
- /// <summary>
- /// ArgumentException with message like "Both accessors must be static."
- /// </summary>
- internal static Exception BothAccessorsMustBeStatic() {
- return new ArgumentException(Strings.BothAccessorsMustBeStatic);
- }
-
- /// <summary>
- /// ArgumentException with message like "Static method requires null instance, non-static method requires non-null instance."
- /// </summary>
- internal static Exception OnlyStaticMethodsHaveNullInstance() {
- return new ArgumentException(Strings.OnlyStaticMethodsHaveNullInstance);
- }
-
- /// <summary>
- /// ArgumentException with message like "Property cannot have a void type."
- /// </summary>
- internal static Exception PropertyTypeCannotBeVoid() {
- return new ArgumentException(Strings.PropertyTypeCannotBeVoid);
- }
-
- /// <summary>
- /// ArgumentException with message like "Can only unbox from an object or interface type to a value type."
- /// </summary>
- internal static Exception InvalidUnboxType() {
- return new ArgumentException(Strings.InvalidUnboxType);
- }
-
- /// <summary>
- /// ArgumentException with message like "Argument must not have a value type."
- /// </summary>
- internal static Exception ArgumentMustNotHaveValueType() {
- return new ArgumentException(Strings.ArgumentMustNotHaveValueType);
- }
-
- /// <summary>
- /// ArgumentException with message like "must be reducible node"
- /// </summary>
- internal static Exception MustBeReducible() {
- return new ArgumentException(Strings.MustBeReducible);
- }
-
- /// <summary>
- /// ArgumentException with message like "Default body must be supplied if case bodies are not System.Void."
- /// </summary>
- internal static Exception DefaultBodyMustBeSupplied() {
- return new ArgumentException(Strings.DefaultBodyMustBeSupplied);
- }
-
- /// <summary>
- /// ArgumentException with message like "MethodBuilder does not have a valid TypeBuilder"
- /// </summary>
- internal static Exception MethodBuilderDoesNotHaveTypeBuilder() {
- return new ArgumentException(Strings.MethodBuilderDoesNotHaveTypeBuilder);
- }
-
- /// <summary>
- /// ArgumentException with message like "Type must be derived from System.Delegate"
- /// </summary>
- internal static Exception TypeMustBeDerivedFromSystemDelegate() {
- return new ArgumentException(Strings.TypeMustBeDerivedFromSystemDelegate);
- }
-
- /// <summary>
- /// ArgumentException with message like "Argument type cannot be void"
- /// </summary>
- internal static Exception ArgumentTypeCannotBeVoid() {
- return new ArgumentException(Strings.ArgumentTypeCannotBeVoid);
- }
-
- /// <summary>
- /// ArgumentException with message like "Label type must be System.Void if an expression is not supplied"
- /// </summary>
- internal static Exception LabelMustBeVoidOrHaveExpression() {
- return new ArgumentException(Strings.LabelMustBeVoidOrHaveExpression);
- }
-
- /// <summary>
- /// ArgumentException with message like "Type must be System.Void for this label argument"
- /// </summary>
- internal static Exception LabelTypeMustBeVoid() {
- return new ArgumentException(Strings.LabelTypeMustBeVoid);
- }
-
- /// <summary>
- /// ArgumentException with message like "Quoted expression must be a lambda"
- /// </summary>
- internal static Exception QuotedExpressionMustBeLambda() {
- return new ArgumentException(Strings.QuotedExpressionMustBeLambda);
- }
-
- /// <summary>
- /// ArgumentException with message like "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables."
- /// </summary>
- internal static Exception VariableMustNotBeByRef(object p0, object p1) {
- return new ArgumentException(Strings.VariableMustNotBeByRef(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object."
- /// </summary>
- internal static Exception DuplicateVariable(object p0) {
- return new ArgumentException(Strings.DuplicateVariable(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Start and End must be well ordered"
- /// </summary>
- internal static Exception StartEndMustBeOrdered() {
- return new ArgumentException(Strings.StartEndMustBeOrdered);
- }
-
- /// <summary>
- /// ArgumentException with message like "fault cannot be used with catch or finally clauses"
- /// </summary>
- internal static Exception FaultCannotHaveCatchOrFinally() {
- return new ArgumentException(Strings.FaultCannotHaveCatchOrFinally);
- }
-
- /// <summary>
- /// ArgumentException with message like "try must have at least one catch, finally, or fault clause"
- /// </summary>
- internal static Exception TryMustHaveCatchFinallyOrFault() {
- return new ArgumentException(Strings.TryMustHaveCatchFinallyOrFault);
- }
-
- /// <summary>
- /// ArgumentException with message like "Body of catch must have the same type as body of try."
- /// </summary>
- internal static Exception BodyOfCatchMustHaveSameTypeAsBodyOfTry() {
- return new ArgumentException(Strings.BodyOfCatchMustHaveSameTypeAsBodyOfTry);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Extension node must override the property {0}."
- /// </summary>
- internal static Exception ExtensionNodeMustOverrideProperty(object p0) {
- return new InvalidOperationException(Strings.ExtensionNodeMustOverrideProperty(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "User-defined operator method '{0}' must be static."
- /// </summary>
- internal static Exception UserDefinedOperatorMustBeStatic(object p0) {
- return new ArgumentException(Strings.UserDefinedOperatorMustBeStatic(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "User-defined operator method '{0}' must not be void."
- /// </summary>
- internal static Exception UserDefinedOperatorMustNotBeVoid(object p0) {
- return new ArgumentException(Strings.UserDefinedOperatorMustNotBeVoid(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "No coercion operator is defined between types '{0}' and '{1}'."
- /// </summary>
- internal static Exception CoercionOperatorNotDefined(object p0, object p1) {
- return new InvalidOperationException(Strings.CoercionOperatorNotDefined(p0, p1));
- }
-
- /// <summary>
- /// InvalidCastException with message like "The result type '{0}' of the dynamic binding produced by binder '{1}' is not compatible with the result type '{2}' expected by the call site."
- /// </summary>
- internal static Exception DynamicBinderResultNotAssignable(object p0, object p1, object p2) {
- return new InvalidCastException(Strings.DynamicBinderResultNotAssignable(p0, p1, p2));
- }
-
- /// <summary>
- /// InvalidCastException with message like "The result type '{0}' of the dynamic binding produced by the object with type '{1}' for the binder '{2}' is not compatible with the result type '{3}' expected by the call site."
- /// </summary>
- internal static Exception DynamicObjectResultNotAssignable(object p0, object p1, object p2, object p3) {
- return new InvalidCastException(Strings.DynamicObjectResultNotAssignable(p0, p1, p2, p3));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "The result of the dynamic binding produced by the object with type '{0}' for the binder '{1}' needs at least one restriction."
- /// </summary>
- internal static Exception DynamicBindingNeedsRestrictions(object p0, object p1) {
- return new InvalidOperationException(Strings.DynamicBindingNeedsRestrictions(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "The result type '{0}' of the binder '{1}' is not compatible with the result type '{2}' expected by the call site."
- /// </summary>
- internal static Exception BinderNotCompatibleWithCallSite(object p0, object p1, object p2) {
- return new InvalidOperationException(Strings.BinderNotCompatibleWithCallSite(p0, p1, p2));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "The unary operator {0} is not defined for the type '{1}'."
- /// </summary>
- internal static Exception UnaryOperatorNotDefined(object p0, object p1) {
- return new InvalidOperationException(Strings.UnaryOperatorNotDefined(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "The binary operator {0} is not defined for the types '{1}' and '{2}'."
- /// </summary>
- internal static Exception BinaryOperatorNotDefined(object p0, object p1, object p2) {
- return new InvalidOperationException(Strings.BinaryOperatorNotDefined(p0, p1, p2));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Reference equality is not defined for the types '{0}' and '{1}'."
- /// </summary>
- internal static Exception ReferenceEqualityNotDefined(object p0, object p1) {
- return new InvalidOperationException(Strings.ReferenceEqualityNotDefined(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "The operands for operator '{0}' do not match the parameters of method '{1}'."
- /// </summary>
- internal static Exception OperandTypesDoNotMatchParameters(object p0, object p1) {
- return new InvalidOperationException(Strings.OperandTypesDoNotMatchParameters(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'."
- /// </summary>
- internal static Exception OverloadOperatorTypeDoesNotMatchConversionType(object p0, object p1) {
- return new InvalidOperationException(Strings.OverloadOperatorTypeDoesNotMatchConversionType(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Conversion is not supported for arithmetic types without operator overloading."
- /// </summary>
- internal static Exception ConversionIsNotSupportedForArithmeticTypes() {
- return new InvalidOperationException(Strings.ConversionIsNotSupportedForArithmeticTypes);
- }
-
- /// <summary>
- /// ArgumentException with message like "Argument must be array"
- /// </summary>
- internal static Exception ArgumentMustBeArray() {
- return new ArgumentException(Strings.ArgumentMustBeArray);
- }
-
- /// <summary>
- /// ArgumentException with message like "Argument must be boolean"
- /// </summary>
- internal static Exception ArgumentMustBeBoolean() {
- return new ArgumentException(Strings.ArgumentMustBeBoolean);
- }
-
- /// <summary>
- /// ArgumentException with message like "The user-defined equality method '{0}' must return a boolean value."
- /// </summary>
- internal static Exception EqualityMustReturnBoolean(object p0) {
- return new ArgumentException(Strings.EqualityMustReturnBoolean(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Argument must be either a FieldInfo or PropertyInfo"
- /// </summary>
- internal static Exception ArgumentMustBeFieldInfoOrPropertInfo() {
- return new ArgumentException(Strings.ArgumentMustBeFieldInfoOrPropertInfo);
- }
-
- /// <summary>
- /// ArgumentException with message like "Argument must be either a FieldInfo, PropertyInfo or MethodInfo"
- /// </summary>
- internal static Exception ArgumentMustBeFieldInfoOrPropertInfoOrMethod() {
- return new ArgumentException(Strings.ArgumentMustBeFieldInfoOrPropertInfoOrMethod);
- }
-
- /// <summary>
- /// ArgumentException with message like "Argument must be an instance member"
- /// </summary>
- internal static Exception ArgumentMustBeInstanceMember() {
- return new ArgumentException(Strings.ArgumentMustBeInstanceMember);
- }
-
- /// <summary>
- /// ArgumentException with message like "Argument must be of an integer type"
- /// </summary>
- internal static Exception ArgumentMustBeInteger() {
- return new ArgumentException(Strings.ArgumentMustBeInteger);
- }
-
- /// <summary>
- /// ArgumentException with message like "Argument for array index must be of type Int32"
- /// </summary>
- internal static Exception ArgumentMustBeArrayIndexType() {
- return new ArgumentException(Strings.ArgumentMustBeArrayIndexType);
- }
-
- /// <summary>
- /// ArgumentException with message like "Argument must be single dimensional array type"
- /// </summary>
- internal static Exception ArgumentMustBeSingleDimensionalArrayType() {
- return new ArgumentException(Strings.ArgumentMustBeSingleDimensionalArrayType);
- }
-
- /// <summary>
- /// ArgumentException with message like "Argument types do not match"
- /// </summary>
- internal static Exception ArgumentTypesMustMatch() {
- return new ArgumentException(Strings.ArgumentTypesMustMatch);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Cannot auto initialize elements of value type through property '{0}', use assignment instead"
- /// </summary>
- internal static Exception CannotAutoInitializeValueTypeElementThroughProperty(object p0) {
- return new InvalidOperationException(Strings.CannotAutoInitializeValueTypeElementThroughProperty(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Cannot auto initialize members of value type through property '{0}', use assignment instead"
- /// </summary>
- internal static Exception CannotAutoInitializeValueTypeMemberThroughProperty(object p0) {
- return new InvalidOperationException(Strings.CannotAutoInitializeValueTypeMemberThroughProperty(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither"
- /// </summary>
- internal static Exception IncorrectTypeForTypeAs(object p0) {
- return new ArgumentException(Strings.IncorrectTypeForTypeAs(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Coalesce used with type that cannot be null"
- /// </summary>
- internal static Exception CoalesceUsedOnNonNullType() {
- return new InvalidOperationException(Strings.CoalesceUsedOnNonNullType);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "An expression of type '{0}' cannot be used to initialize an array of type '{1}'"
- /// </summary>
- internal static Exception ExpressionTypeCannotInitializeArrayType(object p0, object p1) {
- return new InvalidOperationException(Strings.ExpressionTypeCannotInitializeArrayType(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Expression of type '{0}' cannot be used for constructor parameter of type '{1}'"
- /// </summary>
- internal static Exception ExpressionTypeDoesNotMatchConstructorParameter(object p0, object p1) {
- return new ArgumentException(Strings.ExpressionTypeDoesNotMatchConstructorParameter(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like " Argument type '{0}' does not match the corresponding member type '{1}'"
- /// </summary>
- internal static Exception ArgumentTypeDoesNotMatchMember(object p0, object p1) {
- return new ArgumentException(Strings.ArgumentTypeDoesNotMatchMember(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like " The member '{0}' is not declared on type '{1}' being created"
- /// </summary>
- internal static Exception ArgumentMemberNotDeclOnType(object p0, object p1) {
- return new ArgumentException(Strings.ArgumentMemberNotDeclOnType(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Expression of type '{0}' cannot be used for parameter of type '{1}' of method '{2}'"
- /// </summary>
- internal static Exception ExpressionTypeDoesNotMatchMethodParameter(object p0, object p1, object p2) {
- return new ArgumentException(Strings.ExpressionTypeDoesNotMatchMethodParameter(p0, p1, p2));
- }
-
- /// <summary>
- /// ArgumentException with message like "Expression of type '{0}' cannot be used for parameter of type '{1}'"
- /// </summary>
- internal static Exception ExpressionTypeDoesNotMatchParameter(object p0, object p1) {
- return new ArgumentException(Strings.ExpressionTypeDoesNotMatchParameter(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Expression of type '{0}' cannot be used for return type '{1}'"
- /// </summary>
- internal static Exception ExpressionTypeDoesNotMatchReturn(object p0, object p1) {
- return new ArgumentException(Strings.ExpressionTypeDoesNotMatchReturn(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Expression of type '{0}' cannot be used for assignment to type '{1}'"
- /// </summary>
- internal static Exception ExpressionTypeDoesNotMatchAssignment(object p0, object p1) {
- return new ArgumentException(Strings.ExpressionTypeDoesNotMatchAssignment(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Expression of type '{0}' cannot be used for label of type '{1}'"
- /// </summary>
- internal static Exception ExpressionTypeDoesNotMatchLabel(object p0, object p1) {
- return new ArgumentException(Strings.ExpressionTypeDoesNotMatchLabel(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Expression of type '{0}' cannot be invoked"
- /// </summary>
- internal static Exception ExpressionTypeNotInvocable(object p0) {
- return new ArgumentException(Strings.ExpressionTypeNotInvocable(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Field '{0}' is not defined for type '{1}'"
- /// </summary>
- internal static Exception FieldNotDefinedForType(object p0, object p1) {
- return new ArgumentException(Strings.FieldNotDefinedForType(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Instance field '{0}' is not defined for type '{1}'"
- /// </summary>
- internal static Exception InstanceFieldNotDefinedForType(object p0, object p1) {
- return new ArgumentException(Strings.InstanceFieldNotDefinedForType(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Field '{0}.{1}' is not defined for type '{2}'"
- /// </summary>
- internal static Exception FieldInfoNotDefinedForType(object p0, object p1, object p2) {
- return new ArgumentException(Strings.FieldInfoNotDefinedForType(p0, p1, p2));
- }
-
- /// <summary>
- /// ArgumentException with message like "Incorrect number of indexes"
- /// </summary>
- internal static Exception IncorrectNumberOfIndexes() {
- return new ArgumentException(Strings.IncorrectNumberOfIndexes);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Incorrect number of arguments supplied for lambda invocation"
- /// </summary>
- internal static Exception IncorrectNumberOfLambdaArguments() {
- return new InvalidOperationException(Strings.IncorrectNumberOfLambdaArguments);
- }
-
- /// <summary>
- /// ArgumentException with message like "Incorrect number of parameters supplied for lambda declaration"
- /// </summary>
- internal static Exception IncorrectNumberOfLambdaDeclarationParameters() {
- return new ArgumentException(Strings.IncorrectNumberOfLambdaDeclarationParameters);
- }
-
- /// <summary>
- /// ArgumentException with message like "Incorrect number of arguments supplied for call to method '{0}'"
- /// </summary>
- internal static Exception IncorrectNumberOfMethodCallArguments(object p0) {
- return new ArgumentException(Strings.IncorrectNumberOfMethodCallArguments(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Incorrect number of arguments for constructor"
- /// </summary>
- internal static Exception IncorrectNumberOfConstructorArguments() {
- return new ArgumentException(Strings.IncorrectNumberOfConstructorArguments);
- }
-
- /// <summary>
- /// ArgumentException with message like " Incorrect number of members for constructor"
- /// </summary>
- internal static Exception IncorrectNumberOfMembersForGivenConstructor() {
- return new ArgumentException(Strings.IncorrectNumberOfMembersForGivenConstructor);
- }
-
- /// <summary>
- /// ArgumentException with message like "Incorrect number of arguments for the given members "
- /// </summary>
- internal static Exception IncorrectNumberOfArgumentsForMembers() {
- return new ArgumentException(Strings.IncorrectNumberOfArgumentsForMembers);
- }
-
- /// <summary>
- /// ArgumentException with message like "Lambda type parameter must be derived from System.Delegate"
- /// </summary>
- internal static Exception LambdaTypeMustBeDerivedFromSystemDelegate() {
- return new ArgumentException(Strings.LambdaTypeMustBeDerivedFromSystemDelegate);
- }
-
- /// <summary>
- /// ArgumentException with message like "Member '{0}' not field or property"
- /// </summary>
- internal static Exception MemberNotFieldOrProperty(object p0) {
- return new ArgumentException(Strings.MemberNotFieldOrProperty(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Method {0} contains generic parameters"
- /// </summary>
- internal static Exception MethodContainsGenericParameters(object p0) {
- return new ArgumentException(Strings.MethodContainsGenericParameters(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Method {0} is a generic method definition"
- /// </summary>
- internal static Exception MethodIsGeneric(object p0) {
- return new ArgumentException(Strings.MethodIsGeneric(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "The method '{0}.{1}' is not a property accessor"
- /// </summary>
- internal static Exception MethodNotPropertyAccessor(object p0, object p1) {
- return new ArgumentException(Strings.MethodNotPropertyAccessor(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "The property '{0}' has no 'get' accessor"
- /// </summary>
- internal static Exception PropertyDoesNotHaveGetter(object p0) {
- return new ArgumentException(Strings.PropertyDoesNotHaveGetter(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "The property '{0}' has no 'set' accessor"
- /// </summary>
- internal static Exception PropertyDoesNotHaveSetter(object p0) {
- return new ArgumentException(Strings.PropertyDoesNotHaveSetter(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "The property '{0}' has no 'get' or 'set' accessors"
- /// </summary>
- internal static Exception PropertyDoesNotHaveAccessor(object p0) {
- return new ArgumentException(Strings.PropertyDoesNotHaveAccessor(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "'{0}' is not a member of type '{1}'"
- /// </summary>
- internal static Exception NotAMemberOfType(object p0, object p1) {
- return new ArgumentException(Strings.NotAMemberOfType(p0, p1));
- }
-
- /// <summary>
- /// NotImplementedException with message like "The operator '{0}' is not implemented for type '{1}'"
- /// </summary>
- internal static Exception OperatorNotImplementedForType(object p0, object p1) {
- return new NotImplementedException(Strings.OperatorNotImplementedForType(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'"
- /// </summary>
- internal static Exception ParameterExpressionNotValidAsDelegate(object p0, object p1) {
- return new ArgumentException(Strings.ParameterExpressionNotValidAsDelegate(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Property '{0}' is not defined for type '{1}'"
- /// </summary>
- internal static Exception PropertyNotDefinedForType(object p0, object p1) {
- return new ArgumentException(Strings.PropertyNotDefinedForType(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Instance property '{0}' is not defined for type '{1}'"
- /// </summary>
- internal static Exception InstancePropertyNotDefinedForType(object p0, object p1) {
- return new ArgumentException(Strings.InstancePropertyNotDefinedForType(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Instance property '{0}' that takes no argument is not defined for type '{1}'"
- /// </summary>
- internal static Exception InstancePropertyWithoutParameterNotDefinedForType(object p0, object p1) {
- return new ArgumentException(Strings.InstancePropertyWithoutParameterNotDefinedForType(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Instance property '{0}{1}' is not defined for type '{2}'"
- /// </summary>
- internal static Exception InstancePropertyWithSpecifiedParametersNotDefinedForType(object p0, object p1, object p2) {
- return new ArgumentException(Strings.InstancePropertyWithSpecifiedParametersNotDefinedForType(p0, p1, p2));
- }
-
- /// <summary>
- /// ArgumentException with message like "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'"
- /// </summary>
- internal static Exception InstanceAndMethodTypeMismatch(object p0, object p1, object p2) {
- return new ArgumentException(Strings.InstanceAndMethodTypeMismatch(p0, p1, p2));
- }
-
- /// <summary>
- /// ArgumentException with message like "Type {0} contains generic parameters"
- /// </summary>
- internal static Exception TypeContainsGenericParameters(object p0) {
- return new ArgumentException(Strings.TypeContainsGenericParameters(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Type {0} is a generic type definition"
- /// </summary>
- internal static Exception TypeIsGeneric(object p0) {
- return new ArgumentException(Strings.TypeIsGeneric(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Type '{0}' does not have a default constructor"
- /// </summary>
- internal static Exception TypeMissingDefaultConstructor(object p0) {
- return new ArgumentException(Strings.TypeMissingDefaultConstructor(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "List initializers must contain at least one initializer"
- /// </summary>
- internal static Exception ListInitializerWithZeroMembers() {
- return new ArgumentException(Strings.ListInitializerWithZeroMembers);
- }
-
- /// <summary>
- /// ArgumentException with message like "Element initializer method must be named 'Add'"
- /// </summary>
- internal static Exception ElementInitializerMethodNotAdd() {
- return new ArgumentException(Strings.ElementInitializerMethodNotAdd);
- }
-
- /// <summary>
- /// ArgumentException with message like "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter"
- /// </summary>
- internal static Exception ElementInitializerMethodNoRefOutParam(object p0, object p1) {
- return new ArgumentException(Strings.ElementInitializerMethodNoRefOutParam(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Element initializer method must have at least 1 parameter"
- /// </summary>
- internal static Exception ElementInitializerMethodWithZeroArgs() {
- return new ArgumentException(Strings.ElementInitializerMethodWithZeroArgs);
- }
-
- /// <summary>
- /// ArgumentException with message like "Element initializer method must be an instance method"
- /// </summary>
- internal static Exception ElementInitializerMethodStatic() {
- return new ArgumentException(Strings.ElementInitializerMethodStatic);
- }
-
- /// <summary>
- /// ArgumentException with message like "Type '{0}' is not IEnumerable"
- /// </summary>
- internal static Exception TypeNotIEnumerable(object p0) {
- return new ArgumentException(Strings.TypeNotIEnumerable(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Type parameter is {0}. Expected a delegate."
- /// </summary>
- internal static Exception TypeParameterIsNotDelegate(object p0) {
- return new InvalidOperationException(Strings.TypeParameterIsNotDelegate(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Unexpected coalesce operator."
- /// </summary>
- internal static Exception UnexpectedCoalesceOperator() {
- return new InvalidOperationException(Strings.UnexpectedCoalesceOperator);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Cannot cast from type '{0}' to type '{1}"
- /// </summary>
- internal static Exception InvalidCast(object p0, object p1) {
- return new InvalidOperationException(Strings.InvalidCast(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Unhandled binary: {0}"
- /// </summary>
- internal static Exception UnhandledBinary(object p0) {
- return new ArgumentException(Strings.UnhandledBinary(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Unhandled binding "
- /// </summary>
- internal static Exception UnhandledBinding() {
- return new ArgumentException(Strings.UnhandledBinding);
- }
-
- /// <summary>
- /// ArgumentException with message like "Unhandled Binding Type: {0}"
- /// </summary>
- internal static Exception UnhandledBindingType(object p0) {
- return new ArgumentException(Strings.UnhandledBindingType(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Unhandled convert: {0}"
- /// </summary>
- internal static Exception UnhandledConvert(object p0) {
- return new ArgumentException(Strings.UnhandledConvert(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Unhandled Expression Type: {0}"
- /// </summary>
- internal static Exception UnhandledExpressionType(object p0) {
- return new ArgumentException(Strings.UnhandledExpressionType(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Unhandled unary: {0}"
- /// </summary>
- internal static Exception UnhandledUnary(object p0) {
- return new ArgumentException(Strings.UnhandledUnary(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Unknown binding type"
- /// </summary>
- internal static Exception UnknownBindingType() {
- return new ArgumentException(Strings.UnknownBindingType);
- }
-
- /// <summary>
- /// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types."
- /// </summary>
- internal static Exception UserDefinedOpMustHaveConsistentTypes(object p0, object p1) {
- return new ArgumentException(Strings.UserDefinedOpMustHaveConsistentTypes(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type."
- /// </summary>
- internal static Exception UserDefinedOpMustHaveValidReturnType(object p0, object p1) {
- return new ArgumentException(Strings.UserDefinedOpMustHaveValidReturnType(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators."
- /// </summary>
- internal static Exception LogicalOperatorMustHaveBooleanOperators(object p0, object p1) {
- return new ArgumentException(Strings.LogicalOperatorMustHaveBooleanOperators(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "No method '{0}' exists on type '{1}'."
- /// </summary>
- internal static Exception MethodDoesNotExistOnType(object p0, object p1) {
- return new InvalidOperationException(Strings.MethodDoesNotExistOnType(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "No method '{0}' on type '{1}' is compatible with the supplied arguments."
- /// </summary>
- internal static Exception MethodWithArgsDoesNotExistOnType(object p0, object p1) {
- return new InvalidOperationException(Strings.MethodWithArgsDoesNotExistOnType(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. "
- /// </summary>
- internal static Exception GenericMethodWithArgsDoesNotExistOnType(object p0, object p1) {
- return new InvalidOperationException(Strings.GenericMethodWithArgsDoesNotExistOnType(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "More than one method '{0}' on type '{1}' is compatible with the supplied arguments."
- /// </summary>
- internal static Exception MethodWithMoreThanOneMatch(object p0, object p1) {
- return new InvalidOperationException(Strings.MethodWithMoreThanOneMatch(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "More than one property '{0}' on type '{1}' is compatible with the supplied arguments."
- /// </summary>
- internal static Exception PropertyWithMoreThanOneMatch(object p0, object p1) {
- return new InvalidOperationException(Strings.PropertyWithMoreThanOneMatch(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "An incorrect number of type args were specified for the declaration of a Func type."
- /// </summary>
- internal static Exception IncorrectNumberOfTypeArgsForFunc() {
- return new ArgumentException(Strings.IncorrectNumberOfTypeArgsForFunc);
- }
-
- /// <summary>
- /// ArgumentException with message like "An incorrect number of type args were specified for the declaration of an Action type."
- /// </summary>
- internal static Exception IncorrectNumberOfTypeArgsForAction() {
- return new ArgumentException(Strings.IncorrectNumberOfTypeArgsForAction);
- }
-
- /// <summary>
- /// ArgumentException with message like "Argument type cannot be System.Void."
- /// </summary>
- internal static Exception ArgumentCannotBeOfTypeVoid() {
- return new ArgumentException(Strings.ArgumentCannotBeOfTypeVoid);
- }
-
- /// <summary>
- /// System.Reflection.AmbiguousMatchException with message like "More than one key matching '{0}' was found in the ExpandoObject."
- /// </summary>
- internal static Exception AmbiguousMatchInExpandoObject(object p0) {
- return new System.Reflection.AmbiguousMatchException(Strings.AmbiguousMatchInExpandoObject(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "An element with the same key '{0}' already exists in the ExpandoObject."
- /// </summary>
- internal static Exception SameKeyExistsInExpando(object p0) {
- return new ArgumentException(Strings.SameKeyExistsInExpando(p0));
- }
-
- /// <summary>
- /// System.Collections.Generic.KeyNotFoundException with message like "The specified key '{0}' does not exist in the ExpandoObject."
- /// </summary>
- internal static Exception KeyDoesNotExistInExpando(object p0) {
- return new System.Collections.Generic.KeyNotFoundException(Strings.KeyDoesNotExistInExpando(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "No or Invalid rule produced"
- /// </summary>
- internal static Exception NoOrInvalidRuleProduced() {
- return new InvalidOperationException(Strings.NoOrInvalidRuleProduced);
- }
-
- /// <summary>
- /// ArgumentException with message like "First argument of delegate must be CallSite"
- /// </summary>
- internal static Exception FirstArgumentMustBeCallSite() {
- return new ArgumentException(Strings.FirstArgumentMustBeCallSite);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Bind cannot return null."
- /// </summary>
- internal static Exception BindingCannotBeNull() {
- return new InvalidOperationException(Strings.BindingCannotBeNull);
- }
-
- /// <summary>
- /// ArgumentException with message like "Invalid operation: '{0}'"
- /// </summary>
- internal static Exception InvalidOperation(object p0) {
- return new ArgumentException(Strings.InvalidOperation(p0));
- }
-
- /// <summary>
- /// ArgumentOutOfRangeException with message like "{0} must be greater than or equal to {1}"
- /// </summary>
- internal static Exception OutOfRange(object p0, object p1) {
- return new ArgumentOutOfRangeException(Strings.OutOfRange(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Queue empty."
- /// </summary>
- internal static Exception QueueEmpty() {
- return new InvalidOperationException(Strings.QueueEmpty);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Cannot redefine label '{0}' in an inner block."
- /// </summary>
- internal static Exception LabelTargetAlreadyDefined(object p0) {
- return new InvalidOperationException(Strings.LabelTargetAlreadyDefined(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Cannot jump to undefined label '{0}'."
- /// </summary>
- internal static Exception LabelTargetUndefined(object p0) {
- return new InvalidOperationException(Strings.LabelTargetUndefined(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Control cannot leave a finally block."
- /// </summary>
- internal static Exception ControlCannotLeaveFinally() {
- return new InvalidOperationException(Strings.ControlCannotLeaveFinally);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Control cannot leave a filter test."
- /// </summary>
- internal static Exception ControlCannotLeaveFilterTest() {
- return new InvalidOperationException(Strings.ControlCannotLeaveFilterTest);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Cannot jump to ambiguous label '{0}'."
- /// </summary>
- internal static Exception AmbiguousJump(object p0) {
- return new InvalidOperationException(Strings.AmbiguousJump(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Control cannot enter a try block."
- /// </summary>
- internal static Exception ControlCannotEnterTry() {
- return new InvalidOperationException(Strings.ControlCannotEnterTry);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Control cannot enter an expression--only statements can be jumped into."
- /// </summary>
- internal static Exception ControlCannotEnterExpression() {
- return new InvalidOperationException(Strings.ControlCannotEnterExpression);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values."
- /// </summary>
- internal static Exception NonLocalJumpWithValue(object p0) {
- return new InvalidOperationException(Strings.NonLocalJumpWithValue(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Extension should have been reduced."
- /// </summary>
- internal static Exception ExtensionNotReduced() {
- return new InvalidOperationException(Strings.ExtensionNotReduced);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value."
- /// </summary>
- internal static Exception CannotCompileConstant(object p0) {
- return new InvalidOperationException(Strings.CannotCompileConstant(p0));
- }
-
- /// <summary>
- /// NotSupportedException with message like "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite."
- /// </summary>
- internal static Exception CannotCompileDynamic() {
- return new NotSupportedException(Strings.CannotCompileDynamic);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Invalid lvalue for assignment: {0}."
- /// </summary>
- internal static Exception InvalidLvalue(object p0) {
- return new InvalidOperationException(Strings.InvalidLvalue(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Invalid member type: {0}."
- /// </summary>
- internal static Exception InvalidMemberType(object p0) {
- return new InvalidOperationException(Strings.InvalidMemberType(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "unknown lift type: '{0}'."
- /// </summary>
- internal static Exception UnknownLiftType(object p0) {
- return new InvalidOperationException(Strings.UnknownLiftType(p0));
- }
-
- /// <summary>
- /// ArgumentException with message like "Invalid output directory."
- /// </summary>
- internal static Exception InvalidOutputDir() {
- return new ArgumentException(Strings.InvalidOutputDir);
- }
-
- /// <summary>
- /// ArgumentException with message like "Invalid assembly name or file extension."
- /// </summary>
- internal static Exception InvalidAsmNameOrExtension() {
- return new ArgumentException(Strings.InvalidAsmNameOrExtension);
- }
-
- /// <summary>
- /// NotSupportedException with message like "Collection is read-only."
- /// </summary>
- internal static Exception CollectionReadOnly() {
- return new NotSupportedException(Strings.CollectionReadOnly);
- }
-
- /// <summary>
- /// ArgumentException with message like "Cannot create instance of {0} because it contains generic parameters"
- /// </summary>
- internal static Exception IllegalNewGenericParams(object p0) {
- return new ArgumentException(Strings.IllegalNewGenericParams(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined"
- /// </summary>
- internal static Exception UndefinedVariable(object p0, object p1, object p2) {
- return new InvalidOperationException(Strings.UndefinedVariable(p0, p1, p2));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Cannot close over byref parameter '{0}' referenced in lambda '{1}'"
- /// </summary>
- internal static Exception CannotCloseOverByRef(object p0, object p1) {
- return new InvalidOperationException(Strings.CannotCloseOverByRef(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Unexpected VarArgs call to method '{0}'"
- /// </summary>
- internal static Exception UnexpectedVarArgsCall(object p0) {
- return new InvalidOperationException(Strings.UnexpectedVarArgsCall(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Rethrow statement is valid only inside a Catch block."
- /// </summary>
- internal static Exception RethrowRequiresCatch() {
- return new InvalidOperationException(Strings.RethrowRequiresCatch);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Try expression is not allowed inside a filter body."
- /// </summary>
- internal static Exception TryNotAllowedInFilter() {
- return new InvalidOperationException(Strings.TryNotAllowedInFilter);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type."
- /// </summary>
- internal static Exception MustRewriteToSameNode(object p0, object p1, object p2) {
- return new InvalidOperationException(Strings.MustRewriteToSameNode(p0, p1, p2));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite."
- /// </summary>
- internal static Exception MustRewriteChildToSameType(object p0, object p1, object p2) {
- return new InvalidOperationException(Strings.MustRewriteChildToSameType(p0, p1, p2));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is is intentional, override '{1}' and change it to allow this rewrite."
- /// </summary>
- internal static Exception MustRewriteWithoutMethod(object p0, object p1) {
- return new InvalidOperationException(Strings.MustRewriteWithoutMethod(p0, p1));
- }
-
- /// <summary>
- /// NotSupportedException with message like "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression."
- /// </summary>
- internal static Exception TryNotSupportedForMethodsWithRefArgs(object p0) {
- return new NotSupportedException(Strings.TryNotSupportedForMethodsWithRefArgs(p0));
- }
-
- /// <summary>
- /// NotSupportedException with message like "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression."
- /// </summary>
- internal static Exception TryNotSupportedForValueTypeInstances(object p0) {
- return new NotSupportedException(Strings.TryNotSupportedForValueTypeInstances(p0));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Collection was modified; enumeration operation may not execute."
- /// </summary>
- internal static Exception CollectionModifiedWhileEnumerating() {
- return new InvalidOperationException(Strings.CollectionModifiedWhileEnumerating);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Enumeration has either not started or has already finished."
- /// </summary>
- internal static Exception EnumerationIsDone() {
- return new InvalidOperationException(Strings.EnumerationIsDone);
- }
-
- /// <summary>
- /// InvalidOperationException with message like "Dynamic operations can only be performed in homogenous AppDomain."
- /// </summary>
- internal static Exception HomogenousAppDomainRequired() {
- return new InvalidOperationException(Strings.HomogenousAppDomainRequired);
- }
-
- /// <summary>
- /// ArgumentException with message like "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"
- /// </summary>
- internal static Exception TestValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) {
- return new ArgumentException(Strings.TestValueTypeDoesNotMatchComparisonMethodParameter(p0, p1));
- }
-
- /// <summary>
- /// ArgumentException with message like "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"
- /// </summary>
- internal static Exception SwitchValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) {
- return new ArgumentException(Strings.SwitchValueTypeDoesNotMatchComparisonMethodParameter(p0, p1));
- }
-
- /// <summary>
- /// InvalidOperationException with message like "An IDynamicMetaObjectProvider {0} created an invalid DynamicMetaObject instance."
- /// </summary>
- internal static Exception InvalidMetaObjectCreated(object p0) {
- return new InvalidOperationException(Strings.InvalidMetaObjectCreated(p0));
- }
-
- /// <summary>
- /// NotSupportedException with message like "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod."
- /// </summary>
- internal static Exception PdbGeneratorNeedsExpressionCompiler() {
- return new NotSupportedException(Strings.PdbGeneratorNeedsExpressionCompiler);
- }
-
- }
-
- // *** END GENERATED CODE ***
-
- #endregion
-
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Extension.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Extension.cs
deleted file mode 100644
index 81a0312c6bb..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Extension.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-using System;
-
-namespace System.Runtime.CompilerServices
-{
- /// <summary>
- /// Indicates that a method is an extension method, or that a class or assembly contains extension methods.
- /// </summary>
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
- public sealed class ExtensionAttribute : Attribute { }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Function.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Function.cs
deleted file mode 100644
index c33521a254b..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Function.cs
+++ /dev/null
@@ -1,649 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_FUNCS_5_16
-#if !FEATURE_CORE_DLR
-namespace Microsoft.Scripting.Utils {
-#else
-namespace System {
-#endif
-
- #region Generated Func Types
-
- // *** BEGIN GENERATED CODE ***
- // generated by function: gen_func_types from: generate_dynsites.py
-
-#if !FEATURE_VARIANCE
-
- /// <summary>
- /// Encapsulates a method that has five parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<T1, T2, T3, T4, T5, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
-
- /// <summary>
- /// Encapsulates a method that has six parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<T1, T2, T3, T4, T5, T6, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
-
- /// <summary>
- /// Encapsulates a method that has seven parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
-
- /// <summary>
- /// Encapsulates a method that has eight parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
-
- /// <summary>
- /// Encapsulates a method that has nine parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9);
-
- /// <summary>
- /// Encapsulates a method that has ten parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10);
-
- /// <summary>
- /// Encapsulates a method that has eleven parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11);
-
- /// <summary>
- /// Encapsulates a method that has twelve parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12);
-
- /// <summary>
- /// Encapsulates a method that has thirteen parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13);
-
- /// <summary>
- /// Encapsulates a method that has fourteen parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T14">The type of the fourteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg14">The fourteenth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14);
-
- /// <summary>
- /// Encapsulates a method that has fifteen parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T14">The type of the fourteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T15">The type of the fifteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg14">The fourteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg15">The fifteenth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15);
-
- /// <summary>
- /// Encapsulates a method that has sixteen parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T14">The type of the fourteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T15">The type of the fifteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T16">The type of the sixteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg14">The fourteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg15">The fifteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg16">The sixteenth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);
-#else
-
- /// <summary>
- /// Encapsulates a method that has nine parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9);
-
- /// <summary>
- /// Encapsulates a method that has ten parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10);
-
- /// <summary>
- /// Encapsulates a method that has eleven parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11);
-
- /// <summary>
- /// Encapsulates a method that has twelve parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12);
-
- /// <summary>
- /// Encapsulates a method that has thirteen parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13);
-
- /// <summary>
- /// Encapsulates a method that has fourteen parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T14">The type of the fourteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg14">The fourteenth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14);
-
- /// <summary>
- /// Encapsulates a method that has fifteen parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T14">The type of the fourteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T15">The type of the fifteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg14">The fourteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg15">The fifteenth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15);
-
- /// <summary>
- /// Encapsulates a method that has sixteen parameters and returns a value of the type specified by the TResult parameter.
- /// </summary>
- /// <typeparam name="T1">The type of the first parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T2">The type of the second parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T3">The type of the third parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T4">The type of the fourth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T5">The type of the fifth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T6">The type of the sixth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T7">The type of the seventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T8">The type of the eighth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T9">The type of the ninth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T10">The type of the tenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T11">The type of the eleventh parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T12">The type of the twelfth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T13">The type of the thirteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T14">The type of the fourteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T15">The type of the fifteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="T16">The type of the sixteenth parameter of the method that this delegate encapsulates.</typeparam>
- /// <typeparam name="TResult">The type of the return value of the method that this delegate encapsulates.</typeparam>
- /// <param name="arg1">The first parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg2">The second parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg3">The third parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg4">The fourth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg5">The fifth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg6">The sixth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg7">The seventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg8">The eighth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg9">The ninth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg10">The tenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg11">The eleventh parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg12">The twelfth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg13">The thirteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg14">The fourteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg15">The fifteenth parameter of the method that this delegate encapsulates.</param>
- /// <param name="arg16">The sixteenth parameter of the method that this delegate encapsulates.</param>
- /// <returns>The return value of the method that this delegate encapsulates.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
- public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);
-
-#endif
-
- // *** END GENERATED CODE ***
-
- #endregion
-}
-#endif
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Helpers.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Helpers.cs
deleted file mode 100644
index d8827d16968..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/Helpers.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-using Microsoft.Scripting.Utils;
-#else
-using System.Linq.Expressions;
-#endif
-
-using System.Collections.Generic;
-
-namespace System.Dynamic.Utils {
- // Miscellaneous helpers that don't belong anywhere else
- internal static class Helpers {
-
- internal static T CommonNode<T>(T first, T second, Func<T, T> parent) where T : class {
- var cmp = EqualityComparer<T>.Default;
- if (cmp.Equals(first, second)) {
- return first;
- }
- var set = new Set<T>(cmp);
- for (T t = first; t != null; t = parent(t)) {
- set.Add(t);
- }
- for (T t = second; t != null; t = parent(t)) {
- if (set.Contains(t)) {
- return t;
- }
- }
- return null;
- }
-
- internal static void IncrementCount<T>(T key, Dictionary<T, int> dict) {
- int count;
- dict.TryGetValue(key, out count);
- dict[key] = count + 1;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/IRuntimeVariables.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/IRuntimeVariables.cs
deleted file mode 100644
index 126763ea03f..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/IRuntimeVariables.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-namespace System.Runtime.CompilerServices {
- /// <summary>
- /// An interface to represent values of runtime variables.
- /// </summary>
- public interface IRuntimeVariables {
- /// <summary>
- /// Count of the variables.
- /// </summary>
- int Count { get; }
-
- /// <summary>
- /// An indexer to get/set the values of the runtime variables.
- /// </summary>
- /// <param name="index">An index of the runtime variable.</param>
- /// <returns>The value of the runtime variable.</returns>
- object this[int index] { get; set; }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReadOnlyCollectionBuilder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReadOnlyCollectionBuilder.cs
deleted file mode 100644
index c5bb77cc03e..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReadOnlyCollectionBuilder.cs
+++ /dev/null
@@ -1,523 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-#else
-using System.Linq.Expressions;
-#endif
-#if SILVERLIGHT
-using System.Core;
-#endif
-
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Dynamic.Utils;
-
-namespace System.Runtime.CompilerServices {
- /// <summary>
- /// The builder for read only collection.
- /// </summary>
- /// <typeparam name="T">The type of the collection element.</typeparam>
- [Serializable]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
- public sealed class ReadOnlyCollectionBuilder<T> : IList<T>, System.Collections.IList {
- private const int DefaultCapacity = 4;
-
- private T[] _items;
- private int _size;
- private int _version;
-
- [NonSerialized]
- private Object _syncRoot;
-
- static readonly T[] _emptyArray = new T[0];
-
- /// <summary>
- /// Constructs a ReadOnlyCollectionBuilder.
- /// </summary>
- public ReadOnlyCollectionBuilder() {
- _items = _emptyArray;
- }
-
- /// <summary>
- /// Constructs a ReadOnlyCollectionBuilder with a given initial capacity.
- /// The contents are empty but builder will have reserved room for the given
- /// number of elements before any reallocations are required.
- /// </summary>
- public ReadOnlyCollectionBuilder(int capacity) {
- ContractUtils.Requires(capacity >= 0, "capacity");
- _items = new T[capacity];
- }
-
- /// <summary>
- /// Constructs a ReadOnlyCollectionBuilder, copying contents of the given collection.
- /// </summary>
- /// <param name="collection"></param>
- public ReadOnlyCollectionBuilder(IEnumerable<T> collection) {
- ContractUtils.Requires(collection != null, "collection");
-
- ICollection<T> c = collection as ICollection<T>;
- if (c != null) {
- int count = c.Count;
- _items = new T[count];
- c.CopyTo(_items, 0);
- _size = count;
- } else {
- _size = 0;
- _items = new T[DefaultCapacity];
-
- using (IEnumerator<T> en = collection.GetEnumerator()) {
- while (en.MoveNext()) {
- Add(en.Current);
- }
- }
- }
- }
-
- /// <summary>
- /// Gets and sets the capacity of this ReadOnlyCollectionBuilder
- /// </summary>
- public int Capacity {
- get { return _items.Length; }
- set {
- ContractUtils.Requires(value >= _size, "value");
-
- if (value != _items.Length) {
- if (value > 0) {
- T[] newItems = new T[value];
- if (_size > 0) {
- Array.Copy(_items, 0, newItems, 0, _size);
- }
- _items = newItems;
- } else {
- _items = _emptyArray;
- }
- }
- }
- }
-
- /// <summary>
- /// Returns number of elements in the ReadOnlyCollectionBuilder.
- /// </summary>
- public int Count {
- get { return _size; }
- }
-
- #region IList<T> Members
-
- /// <summary>
- /// Returns the index of the first occurrence of a given value in the builder.
- /// </summary>
- /// <param name="item">An item to search for.</param>
- /// <returns>The index of the first occurrence of an item.</returns>
- public int IndexOf(T item) {
- return Array.IndexOf(_items, item, 0, _size);
- }
-
- /// <summary>
- /// Inserts an item to the <see cref="ReadOnlyCollectionBuilder{T}"/> at the specified index.
- /// </summary>
- /// <param name="index">The zero-based index at which item should be inserted.</param>
- /// <param name="item">The object to insert into the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
- public void Insert(int index, T item) {
- ContractUtils.Requires(index <= _size, "index");
-
- if (_size == _items.Length) {
- EnsureCapacity(_size + 1);
- }
- if (index < _size) {
- Array.Copy(_items, index, _items, index + 1, _size - index);
- }
- _items[index] = item;
- _size++;
- _version++;
- }
-
- /// <summary>
- /// Removes the <see cref="ReadOnlyCollectionBuilder{T}"/> item at the specified index.
- /// </summary>
- /// <param name="index">The zero-based index of the item to remove.</param>
- public void RemoveAt(int index) {
- ContractUtils.Requires(index >= 0 && index < _size, "index");
-
- _size--;
- if (index < _size) {
- Array.Copy(_items, index + 1, _items, index, _size - index);
- }
- _items[_size] = default(T);
- _version++;
- }
-
- /// <summary>
- /// Gets or sets the element at the specified index.
- /// </summary>
- /// <param name="index">The zero-based index of the element to get or set.</param>
- /// <returns>The element at the specified index.</returns>
- public T this[int index] {
- get {
- ContractUtils.Requires(index < _size, "index");
- return _items[index];
- }
- set {
- ContractUtils.Requires(index < _size, "index");
- _items[index] = value;
- _version++;
- }
- }
-
- #endregion
-
- #region ICollection<T> Members
-
- /// <summary>
- /// Adds an item to the <see cref="ReadOnlyCollectionBuilder{T}"/>.
- /// </summary>
- /// <param name="item">The object to add to the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
- public void Add(T item) {
- if (_size == _items.Length) {
- EnsureCapacity(_size + 1);
- }
- _items[_size++] = item;
- _version++;
- }
-
- /// <summary>
- /// Removes all items from the <see cref="ReadOnlyCollectionBuilder{T}"/>.
- /// </summary>
- public void Clear() {
- if (_size > 0) {
- Array.Clear(_items, 0, _size);
- _size = 0;
- }
- _version++;
- }
-
- /// <summary>
- /// Determines whether the <see cref="ReadOnlyCollectionBuilder{T}"/> contains a specific value
- /// </summary>
- /// <param name="item">the object to locate in the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
- /// <returns>true if item is found in the <see cref="ReadOnlyCollectionBuilder{T}"/>; otherwise, false.</returns>
- public bool Contains(T item) {
- if ((Object)item == null) {
- for (int i = 0; i < _size; i++) {
- if ((Object)_items[i] == null) {
- return true;
- }
- }
- return false;
- } else {
- EqualityComparer<T> c = EqualityComparer<T>.Default;
- for (int i = 0; i < _size; i++) {
- if (c.Equals(_items[i], item)) {
- return true;
- }
- }
- return false;
- }
- }
-
- /// <summary>
- /// Copies the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/> to an <see cref="Array"/>,
- /// starting at particular <see cref="Array"/> index.
- /// </summary>
- /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
- /// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
- public void CopyTo(T[] array, int arrayIndex) {
- Array.Copy(_items, 0, array, arrayIndex, _size);
- }
-
- bool ICollection<T>.IsReadOnly {
- get { return false; }
- }
-
- /// <summary>
- /// Removes the first occurrence of a specific object from the <see cref="ReadOnlyCollectionBuilder{T}"/>.
- /// </summary>
- /// <param name="item">The object to remove from the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
- /// <returns>true if item was successfully removed from the <see cref="ReadOnlyCollectionBuilder{T}"/>;
- /// otherwise, false. This method also returns false if item is not found in the original <see cref="ReadOnlyCollectionBuilder{T}"/>.
- /// </returns>
- public bool Remove(T item) {
- int index = IndexOf(item);
- if (index >= 0) {
- RemoveAt(index);
- return true;
- }
-
- return false;
- }
-
- #endregion
-
- #region IEnumerable<T> Members
-
- /// <summary>
- /// Returns an enumerator that iterates through the collection.
- /// </summary>
- /// <returns>A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.</returns>
- public IEnumerator<T> GetEnumerator() {
- return new Enumerator(this);
- }
-
- #endregion
-
- #region IEnumerable Members
-
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
- return GetEnumerator();
- }
-
- #endregion
-
- #region IList Members
-
- bool System.Collections.IList.IsReadOnly {
- get { return false; }
- }
-
- int System.Collections.IList.Add(object value) {
- ValidateNullValue(value, "value");
- try {
- Add((T)value);
- } catch (InvalidCastException) {
- ThrowInvalidTypeException(value, "value");
- }
- return Count - 1;
- }
-
- bool System.Collections.IList.Contains(object value) {
- if (IsCompatibleObject(value)) {
- return Contains((T)value);
- } else return false;
- }
-
- int System.Collections.IList.IndexOf(object value) {
- if (IsCompatibleObject(value)) {
- return IndexOf((T)value);
- }
- return -1;
- }
-
- void System.Collections.IList.Insert(int index, object value) {
- ValidateNullValue(value, "value");
- try {
- Insert(index, (T)value);
- } catch (InvalidCastException) {
- ThrowInvalidTypeException(value, "value");
- }
- }
-
- bool System.Collections.IList.IsFixedSize {
- get { return false; }
- }
-
- void System.Collections.IList.Remove(object value) {
- if (IsCompatibleObject(value)) {
- Remove((T)value);
- }
- }
-
- object System.Collections.IList.this[int index] {
- get {
- return this[index];
- }
- set {
- ValidateNullValue(value, "value");
-
- try {
- this[index] = (T)value;
- } catch (InvalidCastException) {
- ThrowInvalidTypeException(value, "value");
- }
- }
- }
-
- #endregion
-
- #region ICollection Members
-
- void System.Collections.ICollection.CopyTo(Array array, int index) {
- ContractUtils.RequiresNotNull(array, "array");
- ContractUtils.Requires(array.Rank == 1, "array");
- Array.Copy(_items, 0, array, index, _size);
- }
-
- bool System.Collections.ICollection.IsSynchronized {
- get { return false; }
- }
-
- object System.Collections.ICollection.SyncRoot {
- get {
- if (_syncRoot == null) {
- System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
- }
- return _syncRoot;
- }
- }
-
- #endregion
-
- /// <summary>
- /// Reverses the order of the elements in the entire <see cref="ReadOnlyCollectionBuilder{T}"/>.
- /// </summary>
- public void Reverse() {
- Reverse(0, Count);
- }
-
- /// <summary>
- /// Reverses the order of the elements in the specified range.
- /// </summary>
- /// <param name="index">The zero-based starting index of the range to reverse.</param>
- /// <param name="count">The number of elements in the range to reverse.</param>
- public void Reverse(int index, int count) {
- ContractUtils.Requires(index >= 0, "index");
- ContractUtils.Requires(count >= 0, "count");
-
- Array.Reverse(_items, index, count);
- _version++;
- }
-
- /// <summary>
- /// Copies the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/> to a new array.
- /// </summary>
- /// <returns>An array containing copies of the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/>.</returns>
- public T[] ToArray() {
- T[] array = new T[_size];
- Array.Copy(_items, 0, array, 0, _size);
- return array;
- }
-
- /// <summary>
- /// Creates a <see cref="ReadOnlyCollection{T}"/> containing all of the the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/>,
- /// avoiding copying the elements to the new array if possible. Resets the <see cref="ReadOnlyCollectionBuilder{T}"/> after the
- /// <see cref="ReadOnlyCollection{T}"/> has been created.
- /// </summary>
- /// <returns>A new instance of <see cref="ReadOnlyCollection{T}"/>.</returns>
- public ReadOnlyCollection<T> ToReadOnlyCollection() {
- // Can we use the stored array?
- T[] items;
- if (_size == _items.Length) {
- items = _items;
- } else {
- items = ToArray();
- }
- _items = _emptyArray;
- _size = 0;
- _version++;
-
- return new TrueReadOnlyCollection<T>(items);
- }
-
- private void EnsureCapacity(int min) {
- if (_items.Length < min) {
- int newCapacity = DefaultCapacity;
- if (_items.Length > 0) {
- newCapacity = _items.Length * 2;
- }
- if (newCapacity < min) {
- newCapacity = min;
- }
- Capacity = newCapacity;
- }
- }
-
- private static bool IsCompatibleObject(object value) {
- return ((value is T) || (value == null && default(T) == null));
- }
-
- private static void ValidateNullValue(object value, string argument) {
- if (value == null && !(default(T) == null)) {
- throw new ArgumentException(Strings.InvalidNullValue(typeof(T)), argument);
- }
- }
-
- private static void ThrowInvalidTypeException(object value, string argument) {
- throw new ArgumentException(Strings.InvalidObjectType(value != null ? value.GetType() : (object)"null", typeof(T)), argument);
- }
-
- [Serializable]
- private class Enumerator : IEnumerator<T>, System.Collections.IEnumerator {
- private readonly ReadOnlyCollectionBuilder<T> _builder;
- private readonly int _version;
-
- private int _index;
- private T _current;
-
- internal Enumerator(ReadOnlyCollectionBuilder<T> builder) {
- _builder = builder;
- _version = builder._version;
- _index = 0;
- _current = default(T);
- }
-
- #region IEnumerator<T> Members
-
- public T Current {
- get { return _current; }
- }
-
- #endregion
-
- #region IDisposable Members
-
- public void Dispose() {
- GC.SuppressFinalize(this);
- }
-
- #endregion
-
- #region IEnumerator Members
-
- object System.Collections.IEnumerator.Current {
- get {
- if (_index == 0 || _index > _builder._size) {
- throw Error.EnumerationIsDone();
- }
- return _current;
- }
- }
-
- public bool MoveNext() {
- if (_version == _builder._version) {
- if (_index < _builder._size) {
- _current = _builder._items[_index++];
- return true;
- } else {
- _index = _builder._size + 1;
- _current = default(T);
- return false;
- }
- } else {
- throw Error.CollectionModifiedWhileEnumerating();
- }
- }
-
- #endregion
-
- #region IEnumerator Members
-
- void System.Collections.IEnumerator.Reset() {
- if (_version != _builder._version) {
- throw Error.CollectionModifiedWhileEnumerating();
- }
- _index = 0;
- _current = default(T);
- }
-
- #endregion
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReadOnlyDictionary.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReadOnlyDictionary.cs
deleted file mode 100644
index 33194716d1f..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReadOnlyDictionary.cs
+++ /dev/null
@@ -1,203 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if !FEATURE_CORE_DLR
-using Microsoft.Scripting.Ast;
-#else
-using System.Linq.Expressions;
-#endif
-#if SILVERLIGHT
-using System.Core;
-#endif
-
-using System.Collections.Generic;
-
-namespace System.Dynamic.Utils {
-
- // Like ReadOnlyCollection<T>: wraps an IDictionary<K, V> in a read-only wrapper
- internal sealed class ReadOnlyDictionary<K, V> : IDictionary<K, V> {
-
- // For wrapping non-readonly Keys, Values collections
- // Not used for standard dictionaries, which return read-only Keys and Values
- private sealed class ReadOnlyWrapper<T> : ICollection<T> {
- // no idea why this warning is here
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
- private readonly ICollection<T> _collection;
-
- internal ReadOnlyWrapper(ICollection<T> collection) {
- _collection = collection;
- }
-
- #region ICollection<T> Members
-
- public void Add(T item) {
- throw Error.CollectionReadOnly();
- }
-
- public void Clear() {
- throw Error.CollectionReadOnly();
- }
-
- public bool Contains(T item) {
- return _collection.Contains(item);
- }
-
- public void CopyTo(T[] array, int arrayIndex) {
- _collection.CopyTo(array, arrayIndex);
- }
-
- public int Count {
- get { return _collection.Count; }
- }
-
- public bool IsReadOnly {
- get { return true; }
- }
-
- public bool Remove(T item) {
- throw Error.CollectionReadOnly();
- }
-
- #endregion
-
- #region IEnumerable<T> Members
-
- public IEnumerator<T> GetEnumerator() {
- return _collection.GetEnumerator();
- }
-
- #endregion
-
- #region IEnumerable Members
-
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
- return _collection.GetEnumerator();
- }
-
- #endregion
- }
-
- private readonly IDictionary<K, V> _dict;
-
- internal ReadOnlyDictionary(IDictionary<K, V> dict) {
- ReadOnlyDictionary<K, V> rodict = dict as ReadOnlyDictionary<K, V>;
- _dict = (rodict != null) ? rodict._dict : dict;
- }
-
- #region IDictionary<K,V> Members
-
- public bool ContainsKey(K key) {
- return _dict.ContainsKey(key);
- }
-
- public ICollection<K> Keys {
- get {
- ICollection<K> keys = _dict.Keys;
- if (!keys.IsReadOnly) {
- return new ReadOnlyWrapper<K>(keys);
- }
- return keys;
- }
- }
-
- public bool TryGetValue(K key, out V value) {
- return _dict.TryGetValue(key, out value);
- }
-
- public ICollection<V> Values {
- get {
- ICollection<V> values = _dict.Values;
- if (!values.IsReadOnly) {
- return new ReadOnlyWrapper<V>(values);
- }
- return values;
- }
- }
-
- public V this[K key] {
- get {
- return _dict[key];
- }
- }
-
-
- void IDictionary<K, V>.Add(K key, V value) {
- throw Error.CollectionReadOnly();
- }
-
- bool IDictionary<K, V>.Remove(K key) {
- throw Error.CollectionReadOnly();
- }
-
- V IDictionary<K, V>.this[K key] {
- get {
- return _dict[key];
- }
- set {
- throw Error.CollectionReadOnly();
- }
- }
-
- #endregion
-
- #region ICollection<KeyValuePair<K,V>> Members
-
- public bool Contains(KeyValuePair<K, V> item) {
- return _dict.Contains(item);
- }
-
- public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex) {
- _dict.CopyTo(array, arrayIndex);
- }
-
- public int Count {
- get { return _dict.Count; }
- }
-
- public bool IsReadOnly {
- get { return true; }
- }
-
- void ICollection<KeyValuePair<K, V>>.Add(KeyValuePair<K, V> item) {
- throw Error.CollectionReadOnly();
- }
-
- void ICollection<KeyValuePair<K, V>>.Clear() {
- throw Error.CollectionReadOnly();
- }
-
- bool ICollection<KeyValuePair<K,V>>.Remove(KeyValuePair<K, V> item) {
- throw Error.CollectionReadOnly();
- }
-
- #endregion
-
- #region IEnumerable<KeyValuePair<K,V>> Members
-
- public IEnumerator<KeyValuePair<K, V>> GetEnumerator() {
- return _dict.GetEnumerator();
- }
-
- #endregion
-
- #region IEnumerable Members
-
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
- return _dict.GetEnumerator();
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReferenceEqualityComparer.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReferenceEqualityComparer.cs
deleted file mode 100644
index 6b7d1fc1e68..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReferenceEqualityComparer.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Collections.Generic;
-using System.Runtime.CompilerServices;
-
-namespace System.Dynamic.Utils {
- internal sealed class ReferenceEqualityComparer<T> : IEqualityComparer<T> {
- internal static readonly ReferenceEqualityComparer<T> Instance = new ReferenceEqualityComparer<T>();
-
- private ReferenceEqualityComparer() { }
-
- public bool Equals(T x, T y) {
- return object.ReferenceEquals(x, y);
- }
-
- public int GetHashCode(T obj) {
- // CF RH.GetHashCode throws NullReferenceException if the argument is null
- return obj != null ? RuntimeHelpers.GetHashCode(obj) : 0;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReflectionUtils.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReflectionUtils.cs
deleted file mode 100644
index a4df5d651b5..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/ReflectionUtils.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-using System;
-
-namespace Microsoft.Scripting.Utils {
- internal static class ReflectionUtils {
- public static readonly Type[] EmptyTypes = new Type[0];
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/StrongBox.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/StrongBox.cs
deleted file mode 100644
index baee2988755..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/StrongBox.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-namespace System.Runtime.CompilerServices {
-
- /// <summary>
- /// Holds a reference to a value.
- /// </summary>
- /// <typeparam name="T">The type of the value that the <see cref = "StrongBox{T}"></see> references.</typeparam>
- public class StrongBox<T> : IStrongBox {
- /// <summary>
- /// Gets the strongly typed value associated with the <see cref = "StrongBox{T}"></see>
- /// <remarks>This is explicitly exposed as a field instead of a property to enable loading the address of the field.</remarks>
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
- public T Value;
-
- /// <summary>
- /// Initializes a new StrongBox which can receive a value when used in a reference call.
- /// </summary>
- public StrongBox() {
- }
-
- /// <summary>
- /// Initializes a new <see cref = "StrongBox{T}"></see> with the specified value.
- /// </summary>
- /// <param name="value">A value that the <see cref = "StrongBox{T}"></see> will reference.</param>
- public StrongBox(T value) {
- Value = value;
- }
-
- object IStrongBox.Value {
- get {
- return Value;
- }
- set {
- Value = (T)value;
- }
- }
- }
-
- /// <summary>
- /// Defines a property for accessing the value that an object references.
- /// </summary>
- public interface IStrongBox {
- /// <summary>
- /// Gets or sets the value the object references.
- /// </summary>
- object Value { get; set; }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/TrueReadOnlyCollection.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/TrueReadOnlyCollection.cs
deleted file mode 100644
index fc0ed6b3676..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/TrueReadOnlyCollection.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Dynamic.Utils;
-
-namespace System.Runtime.CompilerServices {
- sealed class TrueReadOnlyCollection<T> : ReadOnlyCollection<T> {
- /// <summary>
- /// Creates instnace of TrueReadOnlyCollection, wrapping passed in array.
- /// !!! DOES NOT COPY THE ARRAY !!!
- /// </summary>
- internal TrueReadOnlyCollection(T[] list)
- : base(list) {
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/TypeExtensions.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/TypeExtensions.cs
deleted file mode 100644
index 5b219237f66..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/TypeExtensions.cs
+++ /dev/null
@@ -1,114 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System.Diagnostics;
-using System.Reflection;
-#if FEATURE_REFEMIT
-using System.Reflection.Emit;
-#endif
-using System.Text;
-
-namespace System.Dynamic.Utils {
-
- // Extensions on System.Type and friends
- internal static class TypeExtensions {
-
- /// <summary>
- /// Creates a closed delegate for the given (dynamic)method.
- /// </summary>
- internal static Delegate CreateDelegate(this MethodInfo methodInfo, Type delegateType, object target) {
- Debug.Assert(methodInfo != null && delegateType != null);
-#if FEATURE_REFEMIT
- var dm = methodInfo as DynamicMethod;
- if (dm != null)
- return dm.CreateDelegate(delegateType, target);
-#endif
- return Delegate.CreateDelegate(delegateType, target, methodInfo);
- }
-
- internal static Type GetReturnType(this MethodBase mi) {
- return (mi.IsConstructor) ? mi.DeclaringType : ((MethodInfo)mi).ReturnType;
- }
-
- private static readonly CacheDict<MethodBase, ParameterInfo[]> _ParamInfoCache = new CacheDict<MethodBase, ParameterInfo[]>(75);
-
- internal static ParameterInfo[] GetParametersCached(this MethodBase method) {
- ParameterInfo[] pis;
- lock (_ParamInfoCache) {
- if (!_ParamInfoCache.TryGetValue(method, out pis)) {
- pis = method.GetParameters();
-
- Type t = method.DeclaringType;
- if (t != null && TypeUtils.CanCache(t)) {
- _ParamInfoCache[method] = pis;
- }
- }
- }
- return pis;
- }
-
- // Expression trees/compiler just use IsByRef, why do we need this?
- // (see LambdaCompiler.EmitArguments for usage in the compiler)
- internal static bool IsByRefParameter(this ParameterInfo pi) {
- // not using IsIn/IsOut properties as they are not available in Silverlight:
- if (pi.ParameterType.IsByRef) return true;
-
- return (pi.Attributes & (ParameterAttributes.Out)) == ParameterAttributes.Out;
- }
-
- // Returns the matching method if the parameter types are reference
- // assignable from the provided type arguments, otherwise null.
- internal static MethodInfo GetMethodValidated(
- this Type type,
- string name,
- BindingFlags bindingAttr,
- Binder binder,
- Type[] types,
- ParameterModifier[] modifiers) {
-
- var method = type.GetMethod(name, bindingAttr, binder, types, modifiers);
-
- return method.MatchesArgumentTypes(types) ? method : null;
- }
-
- /// <summary>
- /// Returns true if the method's parameter types are reference assignable from
- /// the argument types, otherwise false.
- ///
- /// An example that can make the method return false is that
- /// typeof(double).GetMethod("op_Equality", ..., new[] { typeof(double), typeof(int) })
- /// returns a method with two double parameters, which doesn't match the provided
- /// argument types.
- /// </summary>
- /// <returns></returns>
- private static bool MatchesArgumentTypes(this MethodInfo mi, Type[] argTypes) {
- if (mi == null || argTypes == null) {
- return false;
- }
- var ps = mi.GetParameters();
-
- if (ps.Length != argTypes.Length) {
- return false;
- }
-
- for (int i = 0; i < ps.Length; i++) {
- if (!TypeUtils.AreReferenceAssignable(ps[i].ParameterType, argTypes[i])) {
- return false;
- }
- }
- return true;
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting/ArgumentTypeException.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting/ArgumentTypeException.cs
deleted file mode 100644
index 5d1e9e2d726..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting/ArgumentTypeException.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Runtime.Serialization;
-
-namespace Microsoft.Scripting {
- [Serializable]
- public class ArgumentTypeException : Exception {
- public ArgumentTypeException()
- : base() {
- }
-
- public ArgumentTypeException(string message)
- : base(message) {
- }
-
- public ArgumentTypeException(string message, Exception innerException)
- : base(message, innerException) {
- }
-
-#if FEATURE_SERIALIZATION
- protected ArgumentTypeException(SerializationInfo info, StreamingContext context) : base(info, context) { }
-#endif
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting/InvalidImplementationException.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting/InvalidImplementationException.cs
deleted file mode 100644
index dff8c291a41..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting/InvalidImplementationException.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-using System.Runtime.Serialization;
-
-namespace Microsoft.Scripting {
- [Serializable]
- public class InvalidImplementationException : Exception {
- public InvalidImplementationException()
- : base() {
- }
-
- public InvalidImplementationException(string message)
- : base(message) {
- }
-
- public InvalidImplementationException(string message, Exception e)
- : base(message, e) {
- }
-
-#if FEATURE_SERIALIZATION
- protected InvalidImplementationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
-#endif
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting/PlatformAdaptationLayer.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting/PlatformAdaptationLayer.cs
deleted file mode 100644
index 4659f3d0f39..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting/PlatformAdaptationLayer.cs
+++ /dev/null
@@ -1,476 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if FEATURE_CORE_DLR
-using System.Linq.Expressions;
-#else
-using Microsoft.Scripting.Ast;
-#endif
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Security;
-using Microsoft.Scripting.Utils;
-using System.Runtime.CompilerServices;
-using System.Collections;
-
-namespace Microsoft.Scripting {
-
-#if !FEATURE_PROCESS
- public class ExitProcessException : Exception {
-
- public int ExitCode { get { return exitCode; } }
- int exitCode;
-
- public ExitProcessException(int exitCode) {
- this.exitCode = exitCode;
- }
- }
-#endif
-
- /// <summary>
- /// Abstracts system operations that are used by DLR and could potentially be platform specific.
- /// The host can implement its PAL to adapt DLR to the platform it is running on.
- /// For example, the Silverlight host adapts some file operations to work against files on the server.
- /// </summary>
- [Serializable]
- public class PlatformAdaptationLayer {
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
- public static readonly PlatformAdaptationLayer Default = new PlatformAdaptationLayer();
-
-#if MONO_INTERPRETER
- public const bool IsCompactFramework = false;
-#else
- public static readonly bool IsCompactFramework =
-#if WIN8
- false;
-#else
- Environment.OSVersion.Platform == PlatformID.WinCE ||
- Environment.OSVersion.Platform == PlatformID.Xbox;
-#endif
-
-#endif
-
-#if SILVERLIGHT
-
- // this dictionary is readonly after initialization:
- private Dictionary<string, string> _assemblyFullNames = new Dictionary<string, string>();
-
- public PlatformAdaptationLayer() {
- LoadSilverlightAssemblyNameMapping();
- }
-
- // TODO: remove the need for this
- private void LoadSilverlightAssemblyNameMapping() {
- // non-trasparent assemblies
- AssemblyName platformKeyVer = new AssemblyName(typeof(object).Assembly.FullName);
- AddAssemblyMappings(platformKeyVer,
- "mscorlib",
- "System",
- "System.Core",
- "System.Net",
- "System.Runtime.Serialization",
- "System.ServiceModel.Web",
- "System.Windows",
- "System.Windows.Browser",
- "System.Xml",
- "Microsoft.VisualBasic"
- );
-
- // DLR + language assemblies
- AssemblyName languageKeyVer = new AssemblyName(typeof(PlatformAdaptationLayer).Assembly.FullName);
- AddAssemblyMappings(languageKeyVer,
- "Microsoft.Scripting",
- "Microsoft.Dynamic",
- "Microsoft.Scripting.Core",
- "Microsoft.Scripting.Silverlight",
- "IronPython",
- "IronPython.Modules",
- "IronRuby",
- "IronRuby.Libraries"
- );
-
- // transparent assemblies => same version as mscorlib but uses transparent key (same as languages)
- AssemblyName transparentKeyVer = new AssemblyName(typeof(object).Assembly.FullName);
- transparentKeyVer.SetPublicKeyToken(languageKeyVer.GetPublicKeyToken());
- AddAssemblyMappings(transparentKeyVer,
- "System.ServiceModel",
- "System.ServiceModel.Syndication",
- "System.Windows.Controls",
- "System.Windows.Controls.Data",
- "System.Windows.Controls.Data.Design",
- "System.Windows.Controls.Design",
- "System.Windows.Controls.Extended",
- "System.Windows.Controls.Extended.Design",
- "System.Xml.Linq",
- "System.Xml.Serialization"
- );
- }
-
- private void AddAssemblyMappings(AssemblyName keyVersion, params string[] names) {
- foreach (string asm in names) {
- keyVersion.Name = asm;
- _assemblyFullNames.Add(asm.ToLower(), keyVersion.FullName);
- }
- }
-
- protected string LookupFullName(string name) {
- AssemblyName asm = new AssemblyName(name);
- if (asm.Version != null || asm.GetPublicKeyToken() != null || asm.GetPublicKey() != null) {
- return name;
- }
- return _assemblyFullNames.ContainsKey(name.ToLower()) ? _assemblyFullNames[name.ToLower()] : name;
- }
-#endif
- #region Assembly Loading
-
- public virtual Assembly LoadAssembly(string name) {
-#if WIN8
- throw new NotImplementedException();
-#elif !SILVERLIGHT
- return Assembly.Load(name);
-#else
- return Assembly.Load(LookupFullName(name));
-#endif
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFile")]
- public virtual Assembly LoadAssemblyFromPath(string path) {
-#if FEATURE_FILESYSTEM
- return Assembly.LoadFile(path);
-#else
- throw new NotImplementedException();
-#endif
- }
-
- public virtual void TerminateScriptExecution(int exitCode) {
-#if FEATURE_PROCESS
- System.Environment.Exit(exitCode);
-#else
- throw new ExitProcessException(exitCode);
-#endif
- }
-
- #endregion
-
- #region Virtual File System
-
- public virtual bool IsSingleRootFileSystem {
- get {
-#if FEATURE_FILESYSTEM
- return Environment.OSVersion.Platform == PlatformID.Unix
- || Environment.OSVersion.Platform == PlatformID.MacOSX;
-#elif WIN8
- return false;
-#else
- return true;
-#endif
- }
- }
-
- public virtual StringComparer PathComparer {
- get {
-#if FEATURE_FILESYSTEM
- return Environment.OSVersion.Platform == PlatformID.Unix ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
-#else
- return StringComparer.OrdinalIgnoreCase;
-#endif
- }
- }
-
- public virtual bool FileExists(string path) {
-#if FEATURE_FILESYSTEM
- return File.Exists(path);
-#else
- throw new NotImplementedException();
-#endif
- }
-
- public virtual bool DirectoryExists(string path) {
-#if FEATURE_FILESYSTEM
- return Directory.Exists(path);
-#else
- throw new NotImplementedException();
-#endif
- }
-
-#if !CLR2
- // TODO: better APIs
- public virtual Stream OpenFileStream(string path, FileMode mode = FileMode.OpenOrCreate, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read, int bufferSize = 8192) {
-#if FEATURE_FILESYSTEM
- if (string.Equals("nul", path, StringComparison.InvariantCultureIgnoreCase)) {
- return Stream.Null;
- }
- return new FileStream(path, mode, access, share, bufferSize);
-#else
- throw new NotImplementedException();
-#endif
- }
-
- // TODO: better APIs
- public virtual Stream OpenInputFileStream(string path, FileMode mode = FileMode.Open, FileAccess access = FileAccess.Read, FileShare share = FileShare.Read, int bufferSize = 8192) {
- return OpenFileStream(path, mode, access, share, bufferSize);
- }
-
- // TODO: better APIs
- public virtual Stream OpenOutputFileStream(string path) {
- return OpenFileStream(path, FileMode.Create, FileAccess.Write);
- }
-#else
- public virtual Stream OpenFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) {
-#if FEATURE_FILESYSTEM
- if (string.Equals("nul", path, StringComparison.InvariantCultureIgnoreCase)) {
- return Stream.Null;
- }
- return new FileStream(path, mode, access, share, bufferSize);
-#else
- throw new NotImplementedException();
-#endif
- }
-
- // TODO: better APIs
- public virtual Stream OpenInputFileStream(string path, FileMode mode, FileAccess access, FileShare share) {
- return OpenFileStream(path, mode, access, share, 8912);
- }
-
- // TODO: better APIs
- public virtual Stream OpenInputFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) {
- return OpenFileStream(path, mode, access, share, bufferSize);
- }
-
- // TODO: better APIs
- public virtual Stream OpenInputFileStream(string path) {
- return OpenFileStream(path, FileMode.Open, FileAccess.Read, FileShare.None, 8912);
- }
-
- // TODO: better APIs
- public virtual Stream OpenOutputFileStream(string path) {
- return OpenFileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 8912);
- }
-#endif
-
- public virtual void DeleteFile(string path, bool deleteReadOnly) {
-#if FEATURE_FILESYSTEM
- FileInfo info = new FileInfo(path);
-#if !ANDROID
- if (deleteReadOnly && info.IsReadOnly) {
- info.IsReadOnly = false;
- }
-#endif
- info.Delete();
-#else
- throw new NotImplementedException();
-#endif
- }
-
- public string[] GetFiles(string path, string searchPattern) {
- return GetFileSystemEntries(path, searchPattern, true, false);
- }
-
- public string[] GetDirectories(string path, string searchPattern) {
- return GetFileSystemEntries(path, searchPattern, false, true);
- }
-
- public string[] GetFileSystemEntries(string path, string searchPattern) {
- return GetFileSystemEntries(path, searchPattern, true, true);
- }
-
- public virtual string[] GetFileSystemEntries(string path, string searchPattern, bool includeFiles, bool includeDirectories) {
-#if FEATURE_FILESYSTEM
- if (includeFiles && includeDirectories) {
- return Directory.GetFileSystemEntries(path, searchPattern);
- }
- if (includeFiles) {
- return Directory.GetFiles(path, searchPattern);
- }
- if (includeDirectories) {
- return Directory.GetDirectories(path, searchPattern);
- }
- return ArrayUtils.EmptyStrings;
-#else
- throw new NotImplementedException();
-#endif
- }
-
- /// <exception cref="ArgumentException">Invalid path.</exception>
- public virtual string GetFullPath(string path) {
-#if FEATURE_FILESYSTEM
- try {
- return Path.GetFullPath(path);
- } catch (Exception) {
- throw Error.InvalidPath();
- }
-#else
- throw new NotImplementedException();
-#endif
- }
-
- public virtual string CombinePaths(string path1, string path2) {
- return Path.Combine(path1, path2);
- }
-
- public virtual string GetFileName(string path) {
- return Path.GetFileName(path);
- }
-
- public virtual string GetDirectoryName(string path) {
- return Path.GetDirectoryName(path);
- }
-
- public virtual string GetExtension(string path) {
- return Path.GetExtension(path);
- }
-
- public virtual string GetFileNameWithoutExtension(string path) {
- return Path.GetFileNameWithoutExtension(path);
- }
-
- /// <exception cref="ArgumentException">Invalid path.</exception>
- public virtual bool IsAbsolutePath(string path) {
- if (String.IsNullOrEmpty(path)) {
- return false;
- }
-
- // no drives, no UNC:
- if (IsSingleRootFileSystem) {
- return IsDirectorySeparator(path[0]);
- }
-
- if (IsDirectorySeparator(path[0])) {
- // UNC path
- return path.Length > 1 && IsDirectorySeparator(path[1]);
- }
-
- if (path.Length > 2 && path[1] == ':' && IsDirectorySeparator(path[2])) {
- return true;
- }
-
- return false;
- }
-
-#if FEATURE_FILESYSTEM
- private bool IsDirectorySeparator(char c) {
- return c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar;
- }
-#else
- private bool IsDirectorySeparator(char c) {
- return c == '\\' || c == '/';
- }
-#endif
-
- public virtual string CurrentDirectory {
- get {
-#if FEATURE_FILESYSTEM
- return Directory.GetCurrentDirectory();
-#else
- throw new NotImplementedException();
-#endif
- }
- set {
-#if FEATURE_FILESYSTEM
- Directory.SetCurrentDirectory(value);
-#else
- throw new NotImplementedException();
-#endif
- }
- }
-
- public virtual void CreateDirectory(string path) {
-#if FEATURE_FILESYSTEM
- Directory.CreateDirectory(path);
-#else
- throw new NotImplementedException();
-#endif
- }
-
- public virtual void DeleteDirectory(string path, bool recursive) {
-#if FEATURE_FILESYSTEM
- Directory.Delete(path, recursive);
-#else
- throw new NotImplementedException();
-#endif
- }
-
- public virtual void MoveFileSystemEntry(string sourcePath, string destinationPath) {
-#if FEATURE_FILESYSTEM
- Directory.Move(sourcePath, destinationPath);
-#else
- throw new NotImplementedException();
-#endif
- }
-
- #endregion
-
- #region Environmental Variables
-
- public virtual string GetEnvironmentVariable(string key) {
-#if FEATURE_PROCESS
- return Environment.GetEnvironmentVariable(key);
-#else
- throw new NotImplementedException();
-#endif
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
- public virtual void SetEnvironmentVariable(string key, string value) {
-#if FEATURE_PROCESS
- if (value != null && value.Length == 0) {
- SetEmptyEnvironmentVariable(key);
- } else {
- Environment.SetEnvironmentVariable(key, value);
- }
-#else
- throw new NotImplementedException();
-#endif
- }
-
-#if FEATURE_PROCESS
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2149:TransparentMethodsMustNotCallNativeCodeFxCopRule")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2140:TransparentMethodsMustNotReferenceCriticalCodeFxCopRule")]
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static void SetEmptyEnvironmentVariable(string key) {
- // System.Environment.SetEnvironmentVariable interprets an empty value string as
- // deleting the environment variable. So we use the native SetEnvironmentVariable
- // function here which allows setting of the value to an empty string.
- // This will require high trust and will fail in sandboxed environments
- if (!NativeMethods.SetEnvironmentVariable(key, String.Empty)) {
- throw new ExternalException("SetEnvironmentVariable failed", Marshal.GetLastWin32Error());
- }
- }
-#endif
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
- public virtual Dictionary<string, string> GetEnvironmentVariables() {
-#if FEATURE_PROCESS
- var result = new Dictionary<string, string>();
-
- foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
- {
- result.Add((string)entry.Key, (string)entry.Value);
- }
-
- return result;
-#else
- throw new NotImplementedException();
-#endif
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting/Runtime/NotNullAttribute.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting/Runtime/NotNullAttribute.cs
deleted file mode 100644
index 43cc1af4653..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting/Runtime/NotNullAttribute.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-
-namespace Microsoft.Scripting.Runtime {
- /// <summary>
- /// This attribute marks a parameter that is not allowed to be null.
- /// It is used by the method binding infrastructure to generate better error
- /// messages and method selection.
- /// </summary>
- [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
- public sealed class NotNullAttribute : Attribute {
- public NotNullAttribute() {
- }
- }
-
- /// <summary>
- /// This attribute marks a parameter whose type is an array that is not allowed to have null items.
- /// It is used by the method binding infrastructure to generate better error
- /// messages and method selection.
- /// </summary>
- [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
- public sealed class NotNullItemsAttribute : Attribute {
- public NotNullItemsAttribute() {
- }
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting/Runtime/ParamDictionaryAttribute.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting/Runtime/ParamDictionaryAttribute.cs
deleted file mode 100644
index 3f0a081ea1c..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting/Runtime/ParamDictionaryAttribute.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-using System;
-
-namespace Microsoft.Scripting {
- /// <summary>
- /// This attribute is used to mark a parameter that can accept any keyword parameters that
- /// are not bound to normal arguments. The extra keyword parameters will be
- /// passed in a dictionary which is created for the call.
- ///
- /// Most languages which support params dictionaries will support the following types:
- /// IDictionary&lt;string, anything&gt;
- /// IDictionary&lt;object, anything&gt;
- /// Dictionary&lt;string, anything&gt;
- /// Dictionary&lt;object, anything&gt;
- /// IDictionary
- /// IAttributesCollection (deprecated)
- ///
- /// For languages which don't have language level support the user will be required to
- /// create and populate the dictionary by hand.
- ///
- /// This attribute is the dictionary equivalent of the System.ParamArrayAttribute.
- /// </summary>
- /// <example>
- /// public static void KeywordArgFunction([ParamsDictionary]IDictionary&lt;string, object&gt; dict) {
- /// foreach (var v in dict) {
- /// Console.WriteLine("Key: {0} Value: {1}", v.Key, v.Value);
- /// }
- /// }
- ///
- /// Called from Python:
- ///
- /// KeywordArgFunction(a = 2, b = "abc")
- ///
- /// will print:
- /// Key: a Value = 2
- /// Key: b Value = abc
- /// </example>
- [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
- public sealed class ParamDictionaryAttribute : Attribute {
- }
-}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting/Stubs.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting/Stubs.cs
deleted file mode 100644
index ff378fff15d..00000000000
--- a/mcs/class/dlr/Runtime/Microsoft.Scripting/Stubs.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-/* ****************************************************************************
- *
- * Copyright (c) Microsoft Corporation.
- *
- * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
- * copy of the license can be found in the License.html file at the root of this distribution. If
- * you cannot locate the Apache License, Version 2.0, please send an email to
- * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
- * by the terms of the Apache License, Version 2.0.
- *
- * You must not remove this notice, or any other, from this software.
- *
- *
- * ***************************************************************************/
-
-#if WIN8
-
-// When compiled with Dev10 VS CSC reports errors if this is not defined
-// error CS0656: Missing compiler required member 'System.Threading.Thread.get_ManagedThreadId'
-// error CS0656: Missing compiler required member 'System.Threading.Thread.get_CurrentThread'
-namespace System.Threading {
- internal class Thread {
- public int ManagedThreadId { get { throw new NotImplementedException(); } }
- public static Thread CurrentThread { get { throw new NotImplementedException(); } }
- }
-}
-
-namespace System.IO {
- [Serializable]
- public enum FileMode {
- CreateNew = 1,
- Create,
- Open,
- OpenOrCreate,
- Truncate,
- Append
- }
-
- [Serializable]
- public enum FileAccess {
- Read = 1,
- Write = 2,
- ReadWrite = 3
- }
-
- [Serializable]
- public enum FileShare {
- None = 0,
- Read = 1,
- Write = 2,
- ReadWrite = 3,
- Delete = 4,
- Inheritable = 16
- }
-}
-#else
-namespace System {
- public static class TypeExtensions {
-#if !FEATURE_GET_TYPE_INFO
- public static Type GetTypeInfo(this Type type) {
- return type;
- }
-#endif
-
- public static Type AsType(this Type type) {
- return type;
- }
- }
-}
-#endif
-
-#if !FEATURE_SERIALIZATION
-
-namespace System {
- using System.Diagnostics;
-
- [Conditional("STUB")]
- public class SerializableAttribute : Attribute {
- }
-
- [Conditional("STUB")]
- public class NonSerializedAttribute : Attribute {
- }
-
- namespace Runtime.Serialization {
- public interface ISerializable {
- }
-
- public interface IDeserializationCallback {
- }
- }
-
- public class SerializationException : Exception {
- }
-}
-
-#endif
-
-#if SILVERLIGHT && !CLR2
-
-namespace System {
- namespace Runtime.InteropServices {
- /// <summary>
- /// The Default Parameter Value Attribute.
- /// </summary>
- public sealed class DefaultParameterValueAttribute : Attribute {
- /// <summary>
- /// The constructor
- /// </summary>
- /// <param name="value">The value.</param>
- public DefaultParameterValueAttribute(object value) { }
- }
- }
-}
-
-#endif
diff --git a/mcs/class/dlr/sync.sh b/mcs/class/dlr/sync.sh
deleted file mode 100755
index 133bb21ff31..00000000000
--- a/mcs/class/dlr/sync.sh
+++ /dev/null
@@ -1,5 +0,0 @@
-
-# git clone git://github.com/IronLanguages/main.git
-
-rsync -r /home/marek/git/dlr/main/Runtime/Microsoft.Dynamic/ Runtime/Microsoft.Dynamic --exclude=".*/" --exclude="*.snk"
-rsync -r /home/marek/git/dlr/main/Runtime/Microsoft.Scripting.Core/ Runtime/Microsoft.Scripting.Core --exclude=".*/" --exclude="*.snk"